Welcome, guest | Sign In | My Account | Store | Cart

This recipe shows how a Python function can find out the name of its caller, i.e. which other Python function has called it.

Python, 23 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File: find_callers_with_eval.py
# Run with: python find_callers_with_eval.py

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()

The function uses the sys._getframe function to get the stack frame of the caller and the caller's caller, and from each of those frames, it gets the corresponding function name. The use of eval is not strictly necessary.

1 comment

Vasudev Ram (author) 8 years, 6 months ago  # | flag

More details and program output in this blog post:

http://jugad2.blogspot.in/2015/09/find-caller-and-callers-caller-of.html