views:

359

answers:

2

If you have 2 functions like:

def A
def B

and A calls B, can you get who is calling B inside B, like:

def A () :
    B ()

def B () :
    this.caller.name
+11  A: 

You can use the inspect module to get the calling stack. It returns a list of frame records. The third element in each record is the caller name. What you want is this:

f():
  print inspect.stack()[1][3]

g():
  f()

>>> g()
g

Of course, it is a good idea to check that enough frame records exist before trying to access a particular index.

Ayman Hourieh
+4  A: 

sys._getframe(1).f_code.co_name like in the example below:

>>> def foo():
...  global x
...  x = sys._getframe(1)
...
>>> def y(): foo()
...
>>> y()
>>> x.f_code.co_name
'y'
>>>  
Piotr Findeisen