all Python 3inspectfunction
inspect.currentframe()
stack and frames
Returns the frame object of the code that called it, exposing the function name, the line number, the local variables and the calling frame.
Syntax
frame = inspect.currentframe()
A frame references every local variable, and holding the frame in a variable inside that same frame creates a reference cycle that only the garbage collector can break. So delete it in finally (del frame). The caller is reached through f_back; on Python implementations without frame support the function returns None. inspect.stack() covers the whole stack but is slow because it reads source files.
Examples
import inspect
def caller_name():
frame = inspect.currentframe()
try:
return frame.f_back.f_code.co_name
finally:
del frame
def work():
return caller_name()
print(work()) # → work
import inspect
x = 10
frame = inspect.currentframe()
print(frame.f_code.co_name, frame.f_locals['x'], frame.f_lineno) # → <module> 10 4
del frame
See also
Open in the full glossarydocs.python.orgReport an inaccuracy