Python Glossary Русский

all Python 3tracebackfunction

traceback.format_exception()

formatting tracebacks

A list of lines with the full traceback of a given exception — like format_exc(), but for any saved exception object, not only the current one.

Syntax

lines = traceback.format_exception(exc, /, limit=None, chain=True)

Since Python 3.10 a single argument is enough: format_exception(e); the old form format_exception(type(e), e, e.__traceback__) still works. One list item may hold several lines of text, so join with ''.join(), not '\n'.join() — otherwise blank lines appear. An exception that was created but never raised has no traceback: the result is a single line with the type and message.

Examples

# Python 3.10+
import traceback
print(traceback.format_exception(ValueError('плохо')))  # → ['ValueError: плохо\n']
try:
    {}['k']
except KeyError as e:
    saved = e
text = ''.join(traceback.format_exception(saved))
print(text.splitlines()[-1])  # → KeyError: 'k'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy