Answers for "python caller name"

1

can python function find name of its caller

# YES, here are two methods I have found so far:
# These methods work with the version Python 3.5+
# Method 1: https://tinyurl.com/54c8cvcp
import inspect

def f():
	print(inspect.stack()[1].function)

def g():
	f()

g()
# OUTPUT:
g

# Method 2: https://tinyurl.com/up3yg9m2
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()
# OUTPUT:
I am foo, calling bar:
I am bar, calling baz:
I am baz:
I was called from bar
bar was called from foo

# Method 3: https://tinyurl.com/2p864o7k
import inspect

def f1():
    f2()

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

f1()
# OUTPUT:
caller name: f1
Posted by: Guest on February-20-2021

Python Answers by Framework

Browse Popular Code Answers by Language