all Python 3inspectfunction
inspect.getframeinfo()
stack and frames
A summary of a frame or traceback object: file, line number, function name and the surrounding source lines. Returns an inspect.Traceback.
Syntax
inspect.getframeinfo(frame, context=1)
For a caught exception, e.__traceback__ points at the frame that caught it, not the one that raised it: follow tb_next to the end to reach the failing line. code_context is read from the file and is None when there is no source (exec, REPL); context=0 skips reading the file and is faster. The filename path is machine-specific.
Examples
import inspect
def f():
return 1 / 0
try:
f()
except ZeroDivisionError as e:
tb = e.__traceback__
print(inspect.getframeinfo(tb).function) # → <module>
while tb.tb_next:
tb = tb.tb_next
info = inspect.getframeinfo(tb)
print(info.function, info.lineno, info.code_context)
# → f 3 [' return 1 / 0\n']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy