code.py

Overview

This module provides a comprehensive framework for capturing, representing, and formatting Python exceptions and their associated tracebacks. It wraps low-level Python internals such as code objects, frames, and tracebacks into high-level abstractions that simplify inspection, filtering, and human-readable rendering of errors.

Key features include:

This module is a core part of the pytest error reporting system, enabling detailed yet readable exception tracebacks during test failures.


Classes and Functions


Class: Code

**Purpose:** Wrapper around Python's low-level `code` objects (`types.CodeType`). Provides convenient access to source file paths, first line numbers, argument names, and full source retrieval.

**Key Methods and Properties:**

**Example Usage:**

def foo(x, y): pass

code = Code.from_function(foo)
print(code.name)  # "foo"
print(code.firstlineno)  # starting line number - 1
print(code.getargs())  # ("x", "y")

Class: Frame

**Purpose:** Wraps a Python execution frame (`types.FrameType`) to provide access to local and global variables, the associated code object, and evaluation facilities.

**Key Methods and Properties:**

**Example Usage:**

import sys

frame = Frame(sys._getframe())
print(frame.lineno)
print(frame.code.name)
print(frame.getargs())
result = frame.eval("x + y", x=2, y=3)
print(result)  # 5

Class: TracebackEntry

**Purpose:** Represents a single frame in a traceback, wrapping a `traceback` object (`TracebackType`). Provides rich access to source code, frame locals, and traceback metadata.

**Key Methods and Properties:**

**Notes:**


Class: Traceback (inherits from list[TracebackEntry])

**Purpose:** Represents a full traceback as a list of `TracebackEntry` objects. Offers slicing, filtering, and recursive traceback detection.

**Key Methods:**


Function: stringify_exception(exc: BaseException, include_subexception_msg: bool = True) -> str

**Purpose:** Convert an exception into a string including PEP 678 `__notes__` if available, with workarounds for certain Python version bugs.

**Parameters:**

**Returns:** A string representation of the exception and its notes.


Class: ExceptionInfo(Generic[E])

**Purpose:** Wraps exception info tuples (`sys.exc_info()` or an exception) to provide easy navigation and formatting of exceptions and their tracebacks.

**Key Methods and Properties:**


Class: FormattedExcinfo

**Purpose:** Handles formatting of exception tracebacks and related information for display, including locals, function args, source highlighting, and chained exceptions.

**Key Parameters:**

**Key Methods:**


Terminal Representation Classes

These classes provide terminal-friendly representations of exceptions and tracebacks, integrating with pytest's terminal writer.


Utility Functions


Important Implementation Details


Interaction with Other System Components


Visual Diagram

classDiagram
    class Code {
        -raw: CodeType
        +from_function(obj: object): Code
        +firstlineno: int
        +name: str
        +path: Path|str
        +fullsource: Source|None
        +source(): Source
        +getargs(var: bool): tuple[str,...]
    }

    class Frame {
        -raw: FrameType
        +lineno: int
        +f_globals: dict
        +f_locals: dict
        +code: Code
        +statement: Source
        +eval(code, **vars)
        +repr(object): str
        +getargs(var: bool): list[tuple[str, Any]]
    }

    class TracebackEntry {
        -_rawentry: TracebackType
        -_repr_style: Literal["short","long"]|None
        +lineno: int
        +frame: Frame
        +relline: int
        +statement: Source
        +path: Path|str
        +locals: dict
        +getsource(astcache): Source|None
        +ishidden(excinfo): bool
        +name: str
    }

    class Traceback {
        +__init__(tb: TracebackType|Iterable[TracebackEntry])
        +cut(path, lineno, firstlineno, excludepath): Traceback
        +filter(excinfo_or_fn): Traceback
        +recursionindex(): int|None
    }

    class ExceptionInfo {
        -_excinfo: tuple[type, BaseException, TracebackType]|None
        -_striptext: str
        -_traceback: Traceback|None
        +from_exception(exception): ExceptionInfo
        +from_exc_info(exc_info): ExceptionInfo
        +from_current(): ExceptionInfo
        +for_later(): ExceptionInfo
        +fill_unfilled(exc_info)
        +type: type
        +value: BaseException
        +tb: TracebackType
        +typename: str
        +traceback: Traceback
        +exconly(tryshort): str
        +errisinstance(exc): bool
        +getrepr(...)
        +match(regexp): True
        +group_contains(...)
    }

    Code <--> Frame : "code object"
    Frame <--> TracebackEntry : "frame in entry"
    TracebackEntry <--> Traceback : "entries in traceback"
    TracebackEntry --> ExceptionInfo : "used in ExceptionInfo.traceback"
    ExceptionInfo --> Traceback : "wraps"

Summary

This module is a core utility in pytest for handling exceptions and tracebacks. It abstracts away Python internals to provide rich, high-level APIs for exception inspection, filtering, and rendering. Its classes wrap code objects, frames, and tracebacks and link them with source code context. It supports modern Python features, including exception groups and traceback column info.

The formatting subsystem produces user-friendly, colored, and annotated tracebacks tailored for terminal output, enhancing pytest's error reporting capabilities. This module interacts closely with other pytest internals and is essential for delivering detailed failure diagnostics to users.


End of documentation for code.py