ActiveState Code

Recipe 576925: Caller and Callee


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

Python
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]

Discussion

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

Sign in to comment