Question
Asked By – Joan Venge
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
Now we will see solution for issue: Getting the caller function name inside another function in Python? [duplicate]
Answer
You can use the inspect module to get the info you want. Its stack method returns a list of frame records.
-
For Python 2 each frame record is a list. The third element in each record is the caller name. What you want is this:
>>> import inspect >>> def f(): ... print inspect.stack()[1][3] ... >>> def g(): ... f() ... >>> g() g
-
For Python 3.5+, each frame record is a named tuple so you need to replace
print inspect.stack()[1][3]
with
print(inspect.stack()[1].function)
on the above code.
This question is answered By – Ayman Hourieh
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0