How to get a function definition from an object?

Suppose we have the following code defined in tester.py

class Tester( object ): def method( self ): print 'I am a Tester' 

and we have the following definition specified in main.py

 from tester import Tester t = Tester() #print definition of t 

In any case, could we systematically define class / function definitions from an object? or do we need to parse the code and extract the code definition manually and then save them to a string?

+4
source share
1 answer

You can use the inspect module:

 import inspect class Tester( object ): def method( self ): print 'I am a Tester' print inspect.getsource(Tester) 

Output:

 class Tester( object ): def method( self ): print 'I am a Tester' 
+8
source

All Articles