I want to get information about the callers of a specific function in python. For example:
class SomeClass():
def __init__(self, x):
self.x = x
def caller(self):
return special_func(self.x)
def special_func(x):
print "My caller is the 'caller' function in an 'SomeClass' class."
Is it possible with python?
Yes, the
sys._getframe()function let’s you retrieve frames from the current execution stack, which you can then inspect with the methods and documentation found in theinspectmodule; you’ll be looking for specific locals in thef_localsattribute, as well as for thef_codeinformation:Note that you’ll need to take some care to detect what kind of information you find in each frame.
sys._getframe()returns a frame object, you can chain through the whole stack by following thef_backreference on each. Or you can use theinspect.stack()function to produce a lists of frames with additional information.