Computer >> Computer tutorials >  >> Programming >> Python

How to retrieve source code from Python objects?


We use the getsource() method of inspect module to get the source code of the function.

inspect.getsource(object)

Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.

If the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.

We import the inspect module and retrieve the source code for given script as follows

Example

#baz.py
import inspect
class foo:
      def bar():
          print 'Hello'
print(inspect.getsource(foo))

Output

C:/Users/TutorialsPoint1/~.py
class foo:
      def bar():
          print 'Hello'