4

How to get module source code by a python 'object' of that module?

class TestClass(object):

    def __init__(self):
        pass

    def testMethod(self):
        print 'abc'    
        return 'abc'

It's well-known that

print inspect.getsource(TestClass)

can be used to get source code of 'TestClass'.

However, the result of

ob = TestClass()
print inspect.getsource(ob)

as below, is not as expected.

Traceback (most recent call last):
  File "D:\Workspaces\WS1\SomeProject\src\python\utils\ModuleUtils.py", line 154, in <module>
    print inspect.getsource(ob)
  File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 701, in getsource
    lines, lnum = getsourcelines(object)
  File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 690, in getsourcelines
    lines, lnum = findsource(object)
  File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 526, in findsource
    file = getfile(object)
  File "C:\SciSoft\WinPython-64bit-2.7.10.3\python-2.7.10.amd64\lib\inspect.py", line 420, in getfile
    'function, traceback, frame, or code object'.format(object))
TypeError: <utils.TestClass.TestClass object at 0x0000000003C337B8> is not a module, class, method, function, traceback, frame, or code object

The question is:

If there is an object like 'ob' above, how to check the module source code of ob, or 'TestClass', via a method that takes 'ob' itself as a parameter?

In short, implement the following module

def getSource(obj):
   ###returns the result which is exactly identical to inspect.getsource(TestClass)

ob = TestClass()
###prints the result which is exactly identical to inspect.getsource(TestClass)
print getSource(ob)

(The scenario of a method like this is much more common than inspect.getsource(); for example, check the source code of an unknown, unpickled object.)

1 Answer 1

5

Instances don't have source code.

Use:

print inspect.getsource(type(ob))

or:

print inspect.getsource(ob.__class__)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I didn't know such a simple method 'type'

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.