traceback
The Python traceback module provides utilities for working with error tracebacks in Python programs. It’s particularly useful for debugging and error handling, as it allows you to capture and display the call stack of a program when an exception occurs.
Here’s a quick example:
Language: Python
>>> import traceback
>>> try:
... {"a": 1}["b"]
... except KeyError:
... traceback.print_exc()
Traceback (most recent call last):
...
KeyError: 'b'
Key Features
- Extracts stack traces from traceback objects
- Formats stack traces for display
- Prints exceptions and their stack traces to standard error
- Supports customization of traceback formatting
- Colorizes traceback output by default in Python 3.13 and later, configurable through the
PYTHON_COLORSandNO_COLORenvironment variables - Captures complete exception information for debugging and
logging - Works with both caught and uncaught exceptions
Frequently Used Classes and Functions
| Object | Type | Description |
|---|---|---|
traceback.TracebackException |
Class | Captures an exception for later rendering without holding references to traceback and frame objects |
traceback.format_exc() |
Function | Returns a string representation of the current exception |
traceback.print_exc() |
Function | Prints the current exception to sys.stderr |
traceback.extract_tb() |
Function | Returns a StackSummary, which is a list of FrameSummary objects extracted from a traceback object |
traceback.format_tb() |
Function | Formats a traceback object as a list of strings |
traceback.format_list() |
Function | Formats a list of traceback frames as a list of strings |
Examples
Formats and prints the current exception’s stack trace:
Language: Python