Reflection/Get source

Revision as of 00:29, 22 July 2016 by rosettacode>Outis (creation: JavaScript, Python, Ruby)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The goal is to get the source code or file path and line number where a programming object (e.g. module, class, function, method) is defined.

Task
Reflection/Get source
You are encouraged to solve this task according to the task description, using any language you may know.
Task

JavaScript

Function.toString() will return the source code for user-defined functions.

<lang javascript>function foo() {...} foo.toString(); // "function foo() {...}" </lang>

For native functions, the function body typically will be a syntactically invalid string indicating the function is native. This behavior isn't part of any ECMAScript standard, but is common practice. <lang javascript>Math.sqrt.toString(); // "function sqrt() { [native code] }" </lang>

Python

Modules loaded from files have a __file__ attribute. <lang python>import os os.__file__

  1. "/usr/local/lib/python3.5/os.pyc"

</lang>

Ruby

Method#source_location will return the file and line number of a Ruby method. If a method wasn't defined in Ruby, Method#source_location returns nil. <lang ruby>require 'mathn' Math.method(:sqrt).source_location

  1. ["/usr/local/lib/ruby2.3/2.3.0/mathn.rb", 119]

Class.method(:nesting).source_location

  1. nil, since Class#nesting is native

</lang>