all Python 3inspectfunction
inspect.stack()
stack and frames
A list of FrameInfo records for every frame on the call stack, from the current function out to the module.
Syntax
inspect.stack(context=1) -> list[FrameInfo]
The call is expensive: for every frame inspect reads the source file to fill code_context, so hot code uses inspect.stack(0) or fetches one frame via inspect.currentframe().f_back. The second trap is a leak: a FrameInfo holds a live frame, the frame holds its local variables, and a list stored in a local variable closes a reference cycle, so objects outlive the function until the garbage collector runs. Delete the result in a finally block (del st). File paths and line numbers depend on where the file lives.
Examples
import inspect
def inner():
st = inspect.stack(0) # 0 — без чтения исходников
try:
return [fi.function for fi in st]
finally:
del st # разорвать цикл кадр → список → кадр
def outer():
return inner()
print(outer()) # → ['inner', 'outer', '<module>']
print(inspect.stack()[0].lineno) # → ? номер строки в файле
import gc, inspect, weakref
class Obj: pass
def work():
obj = Obj()
st = inspect.stack(0) # кадр ссылается на st, st — на кадр
return weakref.ref(obj)
gc.disable()
r = work()
print(r() is None) # → False — obj пережил функцию
gc.collect()
print(r() is None) # → True — освободил только сборщик циклов
See also
Open in the full glossarydocs.python.orgReport an inaccuracy