4

Suppose we have following code defined in tester.py

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

and we have following defined in main.py

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

is there anyway we could get the definitions of a class/function from an object in a systematic way? or we have to parse the code and extract the code definition manually then save them into a string?

1
  • 3
    You might want to explain the bigger goal you're trying to achieve, since there's probably a better way to do it than whatever you've got in mind. Commented Oct 29, 2011 at 21:21

1 Answer 1

9

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Nice and simple. Good answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.