Given an instance of some class in Python, it would be useful to be able to determine which line of source code defined each method and property (e.g. to implement
You are looking for the inspect module, specifically inspect.getsourcefile()
and inspect.getsourcelines()
. For example
a.py:
class Hello(object):
def say(self):
print 1
>>> from a import Hello
>>> hi = Hello()
>>> inspect.getsourcefile(hi.say)
a.py
>>> inspect.getsourcelines(A, foo)
([' def say(self):\n print 1\n'], 2)
Given the dynamic nature of Python, doing this for more complicated situations may simply not be possible...