Tom
Tom

Reputation: 3336

How to get module source code by a python 'object' of that module? (not inspect.getsource)

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.)

Upvotes: 4

Views: 4687

Answers (1)

Ben
Ben

Reputation: 2472

Instances don't have source code.

Use:

print inspect.getsource(type(ob))

or:

print inspect.getsource(ob.__class__)

Upvotes: 5

Related Questions