python get caller function name code example
Example: can python function find name of its caller
import inspect
def f():
print(inspect.stack()[1].function)
def g():
f()
g()
g
import sys
getframe_expr = 'sys._getframe({}).f_code.co_name'
def foo():
print "I am foo, calling bar:"
bar()
def bar():
print "I am bar, calling baz:"
baz()
def baz():
print "I am baz:"
caller = eval(getframe_expr.format(2))
callers_caller = eval(getframe_expr.format(3))
print "I was called from", caller
print caller, "was called from", callers_caller
foo()
I am foo, calling bar:
I am bar, calling baz:
I am baz:
I was called from bar
bar was called from foo
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