On this page
traceback
Prev: trace | Up: stdlib_module | Next: tracemalloc
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — traceback
Tags: #public #python3 #stdlib
Import
import traceback
Overview
Extracts, formats, and prints Python stack traces and exception chains (format_exc, format_exception, extract_tb, TracebackException). Reach for traceback when capturing structured error diagnostics for logs, worker pools, or custom CLI error reporters.
Quick Start
import traceback
try:
1 / 0
except ZeroDivisionError:
text = traceback.format_exc()
assert "ZeroDivisionError" in text
Implementation Walkthrough
1. Formatting a Stored Exception Object Outside except:
Use format_exception(exc) (Python 3.10+ accepts the exception instance directly) when reporting errors collected from worker threads or tasks:
import traceback
def summarize_error(exc: BaseException) -> str:
return "".join(traceback.format_exception(exc, limit=5))
try:
int("not-an-int")
except ValueError as err:
report = summarize_error(err)
assert "ValueError" in report
2. Extracting Structured Frame Metadata (TracebackException)
import traceback
try:
{}["missing"]
except KeyError as err:
te = traceback.TracebackException.from_exception(err)
frames = [(f.filename, f.lineno, f.name) for f in te.stack]
assert len(frames) >= 1
Gotchas & Boundaries
format_exc()only works inside an activeexceptblock: Outside one it returns'NoneType: None\n'; pass the exception instance toformat_exception(exc)instead.- In logging, prefer
logger.exception("...")over manually callingtraceback.format_exc(). - Do not leak raw tracebacks to untrusted end users: Stack traces expose file paths, library versions, and sometimes local values; log them internally and return sanitized error codes.
Common Functions
- traceback.clear_frames() —
clear_frames(tb)— Clear all references to local variables in the frames of a traceback. - traceback.extract_stack() —
extract_stack(f=None, limit=None)— Extract the raw traceback from the current stack frame. - traceback.extract_tb() —
extract_tb(tb, limit=None)— Return a StackSummary object representing a list of pre-processed entries from traceback. - traceback.format_exc() —
format_exc(limit=None, chain=True)— Like print_exc() but return a string. - traceback.format_exception() —
format_exception(exc, /, value=<implicit>, tb=<implicit>, limit=None, chain=True, **kwargs)— Format a stack trace and the exception information. - traceback.format_exception_only() —
format_exception_only(exc, /, value=<implicit>, *, show_group=False, **kwargs)— Format the exception part of a traceback. - traceback.format_list() —
format_list(extracted_list)— Format a list of tuples or FrameSummary objects for printing. - traceback.format_stack() —
format_stack(f=None, limit=None)— Shorthand for 'format_list(extract_stack(f, limit))'. - traceback.format_tb() —
format_tb(tb, limit=None)— A shorthand for 'format_list(extract_tb(tb, limit))'. - traceback.print_exc() —
print_exc(limit=None, file=None, chain=True)— Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'. - traceback.print_exception() —
print_exception(exc, /, value=<implicit>, tb=<implicit>, limit=None, file=None, chain=True, **kwargs)— Print exception up to 'limit' stack trace entries from 'tb' to 'file'. - traceback.print_last() —
print_last(limit=None, file=None, chain=True)— This is a shorthand for 'print_exception(sys.last_exc, limit=limit, file=file, chain=chain)'. - traceback.print_list() —
print_list(extracted_list, file=None)— Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file. - traceback.print_stack() —
print_stack(f=None, limit=None, file=None)— Print a stack trace from its invocation point. - traceback.print_tb() —
print_tb(tb, limit=None, file=None)— Print up to 'limit' stack trace entries from the traceback 'tb'. - traceback.walk_stack() —
walk_stack(f)— Walk a stack yielding the frame and line number for each frame. - traceback.walk_tb() —
walk_tb(tb)— Walk a traceback yielding the frame and line number for each frame.
Classes & Objects
- traceback.FrameSummary — Information about a single frame from a traceback. (Methods:
.line()) - traceback.StackSummary — A list of FrameSummary objects, representing a stack of frames. (Methods:
.append(),.clear(),.copy(),.count(),.extend(),.extract()) - traceback.TracebackException — An exception ready for rendering. (Methods:
.exc_type(),.exc_type_str(),.format(),.format_exception_only(),.from_exception(),.print())
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/linecache
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/trace
- tuts/python3/stdlib_module/traceback/clear_frames
- tuts/python3/stdlib_module/traceback/extract_stack
- tuts/python3/stdlib_module/traceback/extract_tb
- tuts/python3/stdlib_module/traceback/format_exc
- tuts/python3/stdlib_module/traceback/format_exception
- tuts/python3/stdlib_module/traceback/format_exception_only
- tuts/python3/stdlib_module/traceback/format_list
- tuts/python3/stdlib_module/traceback/format_stack
- tuts/python3/stdlib_module/traceback/format_tb
- tuts/python3/stdlib_module/traceback/FrameSummary
- tuts/python3/stdlib_module/traceback/print_exc
- tuts/python3/stdlib_module/traceback/print_exception
- tuts/python3/stdlib_module/traceback/print_last
- tuts/python3/stdlib_module/traceback/print_list
- tuts/python3/stdlib_module/traceback/print_stack
- tuts/python3/stdlib_module/traceback/print_tb
- tuts/python3/stdlib_module/traceback/StackSummary
- tuts/python3/stdlib_module/traceback/TracebackException
- tuts/python3/stdlib_module/traceback/walk_stack
- tuts/python3/stdlib_module/traceback/walk_tb
- tuts/python3/stdlib_module/tracemalloc
- tuts/python3/tutorials/intermediate_python_and_software_engineering/error_handling_and_context_managers
- tuts/python3/tutorials/intermediate_python_and_software_engineering/testing_and_debugging
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/trace Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/clear_frames Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/extract_stack Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/extract_tb Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/format_exc Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/format_exception Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/format_exception_only Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/format_list Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/traceback/format_stack Linked here; links to this page; shared tags: #stdlib