# pydoc > traceback

---
type: CommandReference
command: traceback
mode: pydoc
section: ""
source: pydoc3
---

## Quick Reference
- `traceback.print_exc()` — Print exception info to sys.stderr (shorthand for `print_exception(*sys.exc_info())`)
- `traceback.format_exc()` — Like `print_exc` but return a string
- `traceback.print_exception(exc, /, value, tb, limit=None, file=None, chain=True)` — Print exception and traceback
- `traceback.format_exception(exc, /, value, tb, limit=None, chain=True)` — Format exception as list of strings
- `traceback.extract_tb(tb, limit=None)` — Return `StackSummary` from traceback
- `traceback.format_tb(tb, limit=None)` — Shorthand for `format_list(extract_tb(tb, limit))`
- `traceback.extract_stack(f=None, limit=None)` — Extract raw traceback from current stack
- `traceback.walk_tb(tb)` — Walk traceback yielding `(frame, line)` pairs; used with `StackSummary.extract`

## Name
Extract, format and print information about Python stack traces.

## Synopsis
python
import traceback
traceback.print_exc()
traceback.format_exc()
traceback.print_exception(exc, value, tb, limit=None, file=None, chain=True)
traceback.format_exception(exc, value, tb, limit=None, chain=True)
# Classes:
traceback.FrameSummary(filename, lineno, name, *, lookup_line=True, locals=None, line=None)
traceback.StackSummary(iterable=())
traceback.TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False)
## Functions

### Printing and Formatting
- `print_exc(limit=None, file=None, chain=True)` — Shorthand for `print_exception(*sys.exc_info(), limit, file, chain=chain)`. Prints exception info to `file` (default sys.stderr).
- `format_exc(limit=None, chain=True)` — Like `print_exc` but returns a string.
- `print_exception(exc, /, value, tb, limit=None, file=None, chain=True)` — Print exception up to `limit` stack trace entries from `tb` to `file`. Prints header "Traceback (most recent call last):" if tb not None, then exception type and value.
- `format_exception(exc, /, value, tb, limit=None, chain=True)` — Format a stack trace and exception information. Returns a list of strings, each ending in newline.
- `format_exception_only(exc, value)` — Format the exception part of a traceback. Returns list of strings; for SyntaxError, multiple lines with caret.
- `print_last(limit=None, file=None, chain=True)` — Shorthand for `print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain=chain)`.
- `print_stack(f=None, limit=None, file=None)` — Print a stack trace from its invocation point. Optional `f` specifies alternate starting frame.
- `print_tb(tb, limit=None, file=None)` — Print up to `limit` stack trace entries from traceback `tb`. If limit omitted, all entries. File defaults to sys.stderr.

### Extracting and Formatting Raw Tracebacks
- `extract_tb(tb, limit=None)` — Return a `StackSummary` object representing a list of pre-processed entries from traceback. Each entry is a `FrameSummary` with attributes `filename`, `lineno`, `name`, `line`.
- `format_tb(tb, limit=None)` — Shorthand for `format_list(extract_tb(tb, limit))`.
- `extract_stack(f=None, limit=None)` — Extract the raw traceback from the current stack frame. Returns list of tuples `(filename, line number, function name, text)` from oldest to newest.
- `format_stack(f=None, limit=None)` — Shorthand for `format_list(extract_stack(f, limit))`.
- `format_list(extracted_list)` — Format a list of tuples or `FrameSummary` objects (as returned by `extract_tb` or `extract_stack`) for printing. Returns list of strings, each ending in newline.

### Walking Frames
- `walk_tb(tb)` — Walk a traceback yielding `(frame, line_number)` for each frame. Follows `tb.tb_next`. Used with `StackSummary.extract`.
- `walk_stack(f=None)` — Walk a stack yielding `(frame, line_number)` for each frame. Follows `f.f_back` from the given frame. If no frame, uses current stack. Used with `StackSummary.extract`.

### Other
- `clear_frames(tb)` — Clear all references to local variables in the frames of a traceback. (Helps break reference cycles.)

## Classes

### `FrameSummary(filename, lineno, name, *, lookup_line=True, locals=None, line=None)`
A single frame from a traceback.

**Attributes:**
- `filename` — The filename for the frame.
- `lineno` — The line number within filename active when the frame was captured.
- `name` — The name of the function or method executing.
- `line` — The text from the linecache for the running code (readonly property).
- `locals` — Either None or a dict mapping variable names to their `repr()`. (readonly property)

**Methods:**
- `__eq__(other)` — Equality.
- `__getitem__(pos)` — Access item.
- `__init__(self, filename, lineno, name, *, lookup_line=True, locals=None, line=None)` — Construct. If `lookup_line` True, `linecache` consulted for source line. `locals` captured as object representations. `line` if provided used instead of lookup.
- `__iter__()` — Iterate.
- `__len__()` — Length.
- `__repr__()` — Representation.

### `StackSummary(iterable=())`
A stack of frames (subclass of `list`).

**Methods:**
- `format(self)` — Format the stack ready for printing. Returns list of strings, each ending in newline. For long sequences of same frame and line, first few repetitions shown then summary line with exact number of further repetitions.
- `extract(frame_gen, *, limit=None, lookup_lines=True, capture_locals=False)` (classmethod) — Create a `StackSummary` from a traceback or stack object. `frame_gen` yields `(frame, lineno)` tuples. `limit` None or number of frames. `lookup_lines` True to lookup lines immediately. `capture_locals` True to capture local variables as object representations.
- `from_list(a_list)` (classmethod) — Create a `StackSummary` from a list of `FrameSummary` objects or old-style list of tuples.

**Inherited from `list`:** `append`, `clear`, `copy`, `count`, `extend`, `index`, `insert`, `pop`, `remove`, `reverse`, `sort`, and standard operators.

### `TracebackException(exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False, _seen=None)`
An exception ready for rendering. Captures attributes from original exception to avoid holding references while still enabling full printing/formatting.

**Attributes:**
- `__cause__` — A `TracebackException` of the original `__cause__`.
- `__context__` — A `TracebackException` of the original `__context__`.
- `__suppress_context__` — The original `__suppress_context__` value.
- `stack` — A `StackSummary` representing the traceback.
- `exc_type` — The class of the original traceback.
- `filename` — (SyntaxError) The filename where error occurred.
- `lineno` — (SyntaxError) The line number.
- `end_lineno` — (SyntaxError) The end line number (can be None).
- `text` — (SyntaxError) The text where error occurred.
- `offset` — (SyntaxError) The offset into the text.
- `end_offset` — (SyntaxError) The end offset (can be None).
- `msg` — (SyntaxError) The compiler error message.

**Methods:**
- `__init__(self, exc_type, exc_value, exc_traceback, *, limit=None, lookup_lines=True, capture_locals=False, compact=False, _seen=None)` — Initialize.
- `__eq__(other)` — Equality.
- `__str__()` — String representation.
- `format(self, *, chain=True)` — Format the exception. If `chain` not True, `__cause__` and `__context__` not formatted. Returns generator of strings, each ending in newline. Last string is the exception message.
- `format_exception_only(self)` — Format the exception part. Returns generator of strings. For SyntaxError, multiple lines with detailed info; last string always indicates exception.
- `from_exception(exc, *args, **kwargs)` (classmethod) — Create a `TracebackException` from an exception.

## Examples
python
import traceback
import sys

try:
    raise ValueError("example")
except ValueError:
    # Print full traceback to stderr
    traceback.print_exc()
    # Get formatted string
    err_str = traceback.format_exc()
    print("Formatted exception:", err_str)
python
import traceback

# Extract and format stack frames
stack = traceback.extract_stack()
formatted = traceback.format_list(stack)
for line in formatted:
    print(line, end='')
python
import traceback

# Walk a traceback manually
def inner():
    return traceback.walk_stack(None)

for frame, lineno in inner():
    print(f"Frame: {frame.f_code.co_name}, Line: {lineno}")
## See Also
- [Python traceback module documentation](https://docs.python.org/3.10/library/traceback.html)
- `sys.exc_info()`
- `linecache` module

## Exit Codes
Not applicable.