Python 3.5+tracebackfunction
traceback.walk_tb()
frames and stack
A generator of (frame, line number) pairs along an exception's traceback via tb_next — from where it was caught to where it was raised.
Syntax
for frame, lineno in traceback.walk_tb(tb): ...
It yields live frames, so frame.f_locals shows variable values at the moment of the error — this is how "with variable values" crash reports work. The direction is the opposite of walk_stack: from the outer frame inwards, the last one being the failure point. While you hold these frames (or the exception) their variables are not freed.
Examples
import traceback
def div(a, b):
return a / b
try:
div(1, 0)
except ZeroDivisionError as e:
*_, (frame, line) = traceback.walk_tb(e.__traceback__)
print(frame.f_code.co_name, dict(frame.f_locals)) # → div {'a': 1, 'b': 0}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy