can python function find name of its caller

Solutions on MaxInterview for can python function find name of its caller by the best coders in the world

showing results for - "can python function find name of its caller"
Valentina
18 Oct 2020
1# YES, here are two methods I have found so far:
2# These methods work with the version Python 3.5+
3# Method 1: https://tinyurl.com/54c8cvcp
4import inspect
5
6def f():
7	print(inspect.stack()[1].function)
8
9def g():
10	f()
11
12g()
13# OUTPUT:
14g
15
16# Method 2: https://tinyurl.com/up3yg9m2
17import sys
18
19getframe_expr = 'sys._getframe({}).f_code.co_name'
20
21def foo():
22    print "I am foo, calling bar:"
23    bar()
24
25def bar():
26    print "I am bar, calling baz:"
27    baz()
28
29def baz():
30    print "I am baz:"
31    caller = eval(getframe_expr.format(2))
32    callers_caller = eval(getframe_expr.format(3))
33    print "I was called from", caller
34    print caller, "was called from", callers_caller
35
36foo()
37# OUTPUT:
38I am foo, calling bar:
39I am bar, calling baz:
40I am baz:
41I was called from bar
42bar was called from foo
43
44# Method 3: https://tinyurl.com/2p864o7k
45import inspect
46
47def f1():
48    f2()
49
50def f2():
51    curframe = inspect.currentframe()
52    calframe = inspect.getouterframes(curframe, 2)
53    print('caller name:', calframe[1][3])
54
55f1()
56# OUTPUT:
57caller name: f1
58