Python Glossary Русский

all Python 3tracebackfunction

traceback.format_exception_only()

formatting tracebacks

Only the last part of a traceback — "Type: message" — without stack frames; for a short message to the user.

Syntax

lines = traceback.format_exception_only(exc, /, *, show_group=False)

It returns a list of lines, usually one, but a SyntaxError gives several (file, text and a "^" under the error), and since Python 3.11 notes from add_note() are appended. Compared with str(e): str gives only the message without the type, and for KeyError just the quoted key, which looks odd; this function prefixes the type name. The single-argument form (exc) exists since 3.10; earlier code passed the type and the value.

Examples

# Python 3.11+
import traceback
e = ValueError('пустой ввод')
e.add_note('введите число')
print(traceback.format_exception_only(e))
# → ['ValueError: пустой ввод\n', 'введите число\n']
import traceback
e = KeyError('id')
print(str(e))  # → 'id'
print(traceback.format_exception_only(type(e), e))  # → ["KeyError: 'id'\n"]

See also

Open in the full glossarydocs.python.orgReport an inaccuracy