---
source: https://iinventedlight.com/library/notes/python-traceback.md
title: "Python traceback - print or capture exception stack traces as strings"
license: CC-BY-4.0
license_url: https://creativecommons.org/licenses/by/4.0/
source_license: "PSF-2.0 (Python docs); PSF-2.0 (python/cpython (GitHub)); prose restates cited source lines in own words"
license_family: mixed-green
attribution: "Summary by iinventedlight (AI-assisted). Sources: Python docs, traceback - Print or retrieve a stack traceback; python/cpython (GitHub), Lib/traceback.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation."
author: "iinventedlight (synthesis of cited sources); text drafted with AI assistance"
date: 2026-11-18
status: published
approved_by: "Cole Withington, 2026-11-20 13:14 PT: \"Publish the full batch and rewrite the 6 live notes\""
checked_on: 2026-11-18
as_of: 2026-11-18
confidence: medium
untested: "Not reproduced (2026-11-18). Official docs and source files were read; no test suite, server, or API call was run for this note."
category: coding-references
topic_area: "code-python: traceback"
tags: [python, traceback, exceptions, debugging, logging, stdlib]
client: Librarian
sources:
  - id: S1
    title: "traceback - Print or retrieve a stack traceback"
    publisher: Python docs
    url: https://docs.python.org/3/library/traceback.html
    accessed: 2026-11-18
    license: "PSF-2.0"
  - id: S2
    title: "Lib/traceback.py"
    publisher: python/cpython (GitHub)
    url: https://github.com/python/cpython/blob/main/Lib/traceback.py
    accessed: 2026-11-18
    license: "PSF-2.0"
---
# Python traceback - print or capture exception stack traces as strings
**Answer:** The traceback module provides a standard interface to extract, format and print stack traces. `print_exc()` prints the exception being handled, and `format_exc()` is like it but returns a string instead of printing to a file. Use `format_exception(exc)` for any exception object and `TracebackException` to capture one for later rendering.

## Examples

```python
import sys
import traceback

try:
    1 / 0
except ZeroDivisionError as exc:
    traceback.print_exc()                    # to sys.stderr
    text = traceback.format_exc()            # same text as a str
    lines = traceback.format_exception(exc)  # list of str
    traceback.print_exc(limit=1, file=sys.stdout)

    saved = traceback.TracebackException.from_exception(exc)

print("".join(saved.format()))
traceback.print_stack(limit=3)               # where am I now?
```

## Functions

| Function | What it does |
|---|---|
| `print_exc(limit=None, file=None, chain=True)` | shorthand for `print_exception(sys.exception(), ...)` |
| `format_exc()` | like `print_exc()` but returns a string |
| `print_exception(exc)` | prints the `Traceback (most recent call last):` header, entries, then the exception type and value |
| `format_exception(exc)` | a list of strings, each ending in a newline; joined, they match `print_exception()` |
| `print_stack(limit=None)` | prints stack trace entries from the invocation point |

## Arguments

- `limit` prints up to that many entries if positive; otherwise the last `abs(limit)` entries. `None` prints all of them.
- `file` defaults to `sys.stderr` when omitted or `None`.
- `chain=True` also prints chained exceptions (`__cause__` and `__context__`).

## TracebackException

`TracebackException` captures enough information about an exception to print it later, without keeping a reference to the actual exception. Exceptions can be the roots of large object graphs, so this can significantly improve memory management.

## Related

Traceback objects are assigned to the `__traceback__` field of exceptions. The `faulthandler` module dumps Python tracebacks on a fault, after a timeout, or on a user signal.

## See also

- [python-exceptions-hierarchy](https://iinventedlight.com/library/notes/python-exceptions-hierarchy/)

## Claims

- id: C1
  claim: format_exc returns a string instead of printing.
  source: S1
  evidence: "This is like print_exc(limit) but returns a string instead of printing to a file."

- id: C2
  claim: TracebackException can improve memory management.
  source: S1
  evidence: "this utility can significantly improve memory management."

- id: C3
  claim: print_exc is shorthand for print_exception with sys.exception().
  source: S2
  evidence: "Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'."

## Sources

- [S1] traceback - Print or retrieve a stack traceback. Python docs. https://docs.python.org/3/library/traceback.html . License: PSF-2.0. Accessed 2026-11-18.

- [S2] Lib/traceback.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/traceback.py . License: PSF-2.0. Accessed 2026-11-18.

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, traceback - Print or retrieve a stack traceback; python/cpython (GitHub), Lib/traceback.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

---

Agents: [/agents.md](/agents.md) | [/.well-known/agent-library.json](/.well-known/agent-library.json).
