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:
Wrappers around Python code objects (
Code), frames (Frame), and traceback entries (TracebackEntry) providing detailed access to source code context.The
Tracebackclass encapsulates entire tracebacks as lists ofTracebackEntryobjects with utilities for filtering and slicing.The
ExceptionInfoclass wraps exception information fromsys.exc_info()or exceptions, allowing easier analysis and formatting.Rich formatting support for exceptions and tracebacks through
FormattedExcinfoand severalRepr*classes, which produce terminal-friendly output with syntax highlighting and source code snippets.Utilities for filtering internal or irrelevant traceback frames, handling recursion in tracebacks, and working with exception groups.
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:**
__init__(obj: CodeType): Initialize with a raw code object.@classmethod from_function(cls, obj: object) -> Code: Create aCodeinstance from a Python function or callable by extracting its raw code.firstlineno: int: The zero-based first line number of the code object's source.name: str: The code object's name (co_name).path: Path | str: Absolute path to the source file for this code object; falls back to the raw filename if inaccessible.fullsource: Source | None: Returns the full source file wrapped in_pytest._code.source.Source.source() -> Source: Returns source corresponding exactly to this code object.getargs(var: bool = False) -> tuple[str, ...]: Returns argument names. Ifvar=True, includes variable and keyword argument names.
**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:**
__init__(frame: FrameType): Initialize with a raw frame.lineno: int: Zero-based current line number in the frame.f_globals: dict[str, Any]: Global variables in the frame.f_locals: dict[str, Any]: Local variables in the frame.code: Code: TheCodewrapper for this frame's code object.statement: Source: The source statement at the current line.eval(code, **vars): Evaluate code string within the frame's globals and locals, optionally augmented byvars.repr(object) -> str: Return a safe one-line string representation of an object.getargs(var: bool = False) -> list[tuple[str, Any]]: List of (name, value) tuples for function arguments, optionally including*argsand**kwargs.
**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:**
__init__(rawentry: TracebackType, repr_style: Literal["short","long"]|None=None): Initialize with raw traceback entry.with_repr_style(repr_style: Literal["short", "long"] | None) -> TracebackEntry: Returns a copy with a different representation style.lineno: int: Zero-based line number where the exception occurred.frame: Frame: WrappedFrameobject for this traceback entry.relline: int: Line number relative to the start of the code object.statement: Source: Source statement at the current line.path: Path | str: Source file path.locals: dict[str, Any]: Local variables in this frame.getsource(astcache: dict | None = None) -> Source | None: Returns source code related to this traceback entry.ishidden(excinfo: ExceptionInfo | None) -> bool: Checks if this entry should be hidden based on__tracebackhide__variable.name: str: The function or code name of this frame.
**Notes:**
Supports Python 3.11+ features such as column offsets and end line numbers.
Provides a
__str__method that mimics traceback entry formatting but is not identical to Python's built-in.
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:**
__init__(tb: TracebackType | Iterable[TracebackEntry]): Construct from a raw traceback or iterable of entries.cut(path=None, lineno=None, firstlineno=None, excludepath=None) -> Traceback: Return a truncated traceback starting from a frame matching the given criteria.filter(excinfo_or_fn: ExceptionInfo | Callable[[TracebackEntry], bool]) -> Traceback: Filter entries based on an exception info or a predicate function.recursionindex() -> int | None: Detect recursion in the traceback by comparing locals and returning the index of recursion origin.
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:**
exc: The exception instance to stringify.include_subexception_msg: Whether to include messages from sub-exceptions (default True).
**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:**
from_exception(exception: E, exprinfo: str | None = None) -> ExceptionInfo[E]: Create from an existing exception instance.from_exc_info(exc_info: tuple[type, BaseException, TracebackType], exprinfo: str | None = None) -> ExceptionInfo[E]: Create from an exc_info tuple.from_current(exprinfo: str | None = None) -> ExceptionInfo[BaseException]: Create from the current exception insys.exc_info().for_later() -> ExceptionInfo[E]: Create an empty ExceptionInfo to be filled later.fill_unfilled(exc_info: tuple): Fill an empty ExceptionInfo.type: type[E]: Exception class.value: E: Exception instance.tb: TracebackType: Raw traceback.typename: str: Exception class name.traceback: Traceback: Wrapped traceback object.exconly(tryshort: bool = False) -> str: Return exception string, optionally shortened for AssertionErrors.errisinstance(exc) -> bool: Shortcut forisinstance(self.value, exc).getrepr(...): Returns a representation of the exception info suitable for terminal display, supporting styles like "long", "short", "native", and others.match(regexp) -> True: Assert the exception message matches a regex, raising AssertionError otherwise.group_contains(...) -> bool: ForBaseExceptionGroupexceptions, checks for matching exceptions within nested groups.
Class: FormattedExcinfo
**Purpose:** Handles formatting of exception tracebacks and related information for display, including locals, function args, source highlighting, and chained exceptions.
**Key Parameters:**
showlocals,style,abspath,tbfilter,funcargs,truncate_locals,truncate_args,chain: Control aspects of formatting and filtering.
**Key Methods:**
repr_excinfo(excinfo: ExceptionInfo) -> ExceptionChainRepr: Format an exception info into a rich representation.repr_traceback(excinfo: ExceptionInfo) -> ReprTraceback: Format a traceback with entries and optional truncation on recursion.repr_traceback_entry(entry: TracebackEntry, excinfo: ExceptionInfo | None = None) -> ReprEntry: Format a single traceback entry.get_source(...) -> list[str]: Return source code lines with highlights and markers.get_highlight_arrows_for_line(...) -> list[str]: Generate caret arrows highlighting error columns in source.repr_locals(locals: Mapping[str, object]) -> ReprLocals | None: Format locals for display.repr_args(entry: TracebackEntry) -> ReprFuncArgs | None: Format function arguments._truncate_recursive_traceback(traceback: Traceback) -> tuple[Traceback, str | None]: Detect and truncate recursive tracebacks.Various helper methods for path formatting and terminal rendering.
Terminal Representation Classes
These classes provide terminal-friendly representations of exceptions and tracebacks, integrating with pytest's terminal writer.
TerminalRepr: Abstract base class.ExceptionRepr: Base for exception representations; handles sections and terminal output.ExceptionChainRepr: Handles chained exceptions printing.ReprExceptionInfo: Representation of a single exception info.ReprTraceback: Representation of a traceback with multiple entries.ReprTracebackNative: Native traceback formatting.ReprEntry: Single traceback entry with source, locals, and func args.ReprEntryNative: Native traceback entry.ReprFileLocation: File and line location with message.ReprLocals: Formatted local variables.ReprFuncArgs: Formatted function arguments.
Utility Functions
getfslineno(obj: object) -> tuple[str | Path, int]: Get source file and zero-based line number for an object._byte_offset_to_character_offset(str, offset) -> int: Convert byte offset to character offset for UTF-8 strings.filter_traceback(entry: TracebackEntry) -> bool: Return whether to include a traceback entry, filters out internal pytest and pluggy frames.filter_excinfo_traceback(tbfilter, excinfo) -> Traceback: Filter an ExceptionInfo's traceback according to a boolean or callable filter.
Important Implementation Details
Uses
__slots__in key wrapper classes (Code,Frame,TracebackEntry) for memory optimization.Supports Python 3.11+ enhancements, such as column numbers in tracebacks.
Exception groups (
BaseExceptionGroup) support with recursive searching for nested exceptions.Filters internal traceback entries by inspecting file paths relative to pytest and pluggy installation directories.
Implements recursion detection in tracebacks by comparing locals dictionaries frame-by-frame.
Uses dataclasses and generics extensively for type safety and clarity.
Uses a layered representation approach: low-level wrappers (
Code,Frame), then higher-level traceback and exception info (Traceback,ExceptionInfo), then terminal formatting (FormattedExcinfo,Repr*classes).
Interaction with Other System Components
Relies heavily on
_pytest._code.source.Sourcefor source code manipulation and extraction.Integrates with pytest's terminal output system through
TerminalWriterfor colored and formatted output.Imports and uses components from
_pytest._io.safereprfor safe string representations.Uses
pluggyand_pytestpaths to identify and filter internal frames.Works closely with Python's built-in
traceback,inspect, andastmodules.Used by pytest during test failure reporting to produce detailed tracebacks and exception summaries for end users.
Provides APIs that other pytest plugins or internals can use to analyze or format exceptions.
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.