Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How to retrieve source code from Python objects?

I have this sample code.

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

How do I retrieve the source code of this script baz.py?


1 Answer
Rajendra Dharmkar

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

#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'
 
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.