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

A recipe to find out which function is the caller of the current function.

The caller function can be helpful for debugging — if there is no real debugger available. In terms of software engineering (loose coupling etc.) this should not be used in production code though.

Python, 7 lines
1
2
3
4
5
6
7
import inspect

def callee():
    return inspect.getouterframes(inspect.currentframe())[1][1:4]

def caller():
    return inspect.getouterframes(inspect.currentframe())[2][1:4]

Example usage:

def anyfunction():
    print "Function %s called from function %s" % (callee(), caller())

def anotherfunction():
    anyfunction()

anotherfunction()

Output:

Function ('/tmp/caller.py', 11, 'anyfunction') called from function ('/tmp/caller.py', 14, 'anotherfunction')
Created by Michael Grünewald on Thu, 8 Oct 2009 (MIT)
Python recipes (4591)
Michael Grünewald's recipes (7)

Required Modules

Other Information and Tasks