Fix Python – How to get the caller’s method name in the called method?

Question

Asked By – zs2020

Python: How to get the caller’s method name in the called method?

Assume I have 2 methods:

def method1(self):
    ...
    a = A.method2()

def method2(self):
    ...

If I don’t want to do any change for method1, how to get the name of the caller (in this example, the name is method1) in method2?

Now we will see solution for issue: How to get the caller’s method name in the called method?


Answer

inspect.getframeinfo and other related functions in inspect can help:

>>> import inspect
>>> def f1(): f2()
... 
>>> def f2():
...   curframe = inspect.currentframe()
...   calframe = inspect.getouterframes(curframe, 2)
...   print('caller name:', calframe[1][3])
... 
>>> f1()
caller name: f1

this introspection is intended to help debugging and development; it’s not advisable to rely on it for production-functionality purposes.

This question is answered By – Alex Martelli

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