snim2
snim2

Reputation: 4079

Is there a way to retrieve source code from a live Python interpreter session or a dynamically created object?

When a Python object is created dynamically, either in a live interpreter session, by un-marshalling a pickled object or some other way, the inspect module can no longer be used to retrieve its source code (as inspect relies on the idea that the source has been compiled from some file on disk).

If I have a simple class like this:

>>> class Foo(object):
...     def __init__(self):
...             self.a = 100
...     def bar(self):
...             print 'hello'
... 
>>> f = Foo()
>>> 

is there some straight forward way to get hold of the source code of the Foo class, or the f object?

I'm aware that there are a few ways around at least part of this problem. For example, one can use inspect.getmembers to find all members of f, iterate through the members to find callables and non-callables, use inspect.getargspec to determine method signatures, etc. From all that, at least some of the source code can be regenerated, but not the code inside each method. A bytecode version of each method can be generated by the dis module, but that would still need to be decompiled into source code.

Is there a better way to do this that I've missed? Can something be done with the results of sys._getframe()?

Upvotes: 3

Views: 411

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375574

You can't get the source code, but you can get the bytecode, and that can be disassembled with the stdlib dis module. The bytecode can usually be read pretty easily by someone with a little experience.

Upvotes: 2

Related Questions