Get function callers' information in python
Question: 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?


Answer: Yes, the
[`sys._getframe()`](http://docs.python.org/library/sys.html#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 the [`inspect`
module](http://docs.python.org/library/inspect.html); you'll be looking for
specific locals in the `f_locals` attribute, as well as for the `f_code`
information:

    
    
    import sys
    def special_func(x):
        callingframe = sys._getframe(1)
        print 'My caller is the %r function in a %r class' % (
            callingframe.f_code.co_name, 
            callingframe.f_locals['self'].__class__.__name__)
    

Note that you'll need to take some care to detect what kind of information you
find in each frame.

