Python Glossary Русский

Python 3.5+tracebackterm

traceback.TracebackException

exception snapshot

A print-ready snapshot of an exception: type, message, stack and the __cause__/__context__ chain — without references to frames or their variables.

Syntax

te = traceback.TracebackException.from_exception(exc, *, limit=None, capture_locals=False)

Keeping the exception itself around is expensive: e.__traceback__ holds every frame and with them every local variable — big lists, open files. TracebackException.from_exception(e) captures what printing needs right away, so the exception can be released. format() returns a generator of strings, not one string — join them with ''.join(...). With capture_locals=True the snapshot also stores the repr of each frame's locals; the print(file=...) method arrived in Python 3.11.

Examples

import traceback
try:
    int('x')
except ValueError as e:
    te = traceback.TracebackException.from_exception(e)
print(''.join(te.format_exception_only()), end='')
# → ValueError: invalid literal for int() with base 10: 'x'
print(te.stack[-1].name)  # → <module>
print(next(te.format()), end='')  # → Traceback (most recent call last):

See also

Open in the full glossarydocs.python.orgReport an inaccuracy