On this page
  1. traceback
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Formatting a Stored Exception Object Outside except:
  7. 2. Extracting Structured Frame Metadata (TracebackException)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes