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
This is more-or-less impossible without static analysis, and even then, it won't always work. You can get the line where a function was defined and in which file by examining its code object, but beyond that, there's not much you can do. The inspect
module can help with this. So:
import ab
a = ab.A()
meth = a.x
# So, now we have the method.
func = meth.im_func
# And the function from the method.
code = func.func_code
# And the code from the function!
print code.co_firstlineno, code.co_filename
# Or:
import inspect
print inspect.getsource(meth), inspect.getfile(meth)
But consider:
def some_method(self):
pass
ab.A.some_method = some_method
ab.A.some_class_attribute = None
Or worse:
some_cls = ab.A
some_string_var = 'another_instance_attribute'
setattr(some_cls, some_string_var, None)
Especially in the latter case, what do you want or expect to get?