pprint.py


Overview

The `pprint.py` module provides a flexible and extensible system for **pretty-printing Python data structures**. It formats complex and nested Python objects into readable, indented, and well-structured string representations. This module is particularly useful for debugging, logging, or displaying data structures that are deeply nested or contain mixed types, making them easier to understand at a glance.

Modeled after Lisp/Scheme-style pretty-printing, this module was originally created to aid in visualizing heavily nested tuples and other collections with non-descriptive content.


Main Components

Class: PrettyPrinter

This is the core class responsible for formatting Python objects into human-readable strings with configurable indentation and width settings.

Initialization

PrettyPrinter(indent: int = 4, width: int = 80, depth: int | None = None) -> None

Methods


pformat(object: Any) -> str

_format(object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int) -> None

_repr(object: Any, context: set[int], level: int) -> str

_safe_repr(object: Any, context: set[int], maxlevels: int | None, level: int) -> str

Formatting Methods for Built-in and Special Types

The class maintains a `_dispatch` dictionary mapping specific `__repr__` methods to custom formatting functions that handle types like:

Each method formats the object type with indentation and recursively formats contained items, handling empty containers and special cases gracefully.


Helper Formatting Functions

Supporting Classes and Functions

Class: _safe_key

Function: _safe_tuple(t)


Important Implementation Details


Interaction with Other Modules


Usage Example

from pprint import PrettyPrinter

data = {
    "users": [
        {"name": "Alice", "age": 30, "tags": {"python", "developer"}},
        {"name": "Bob", "age": 25, "tags": {"java", "tester"}},
    ],
    "count": 2,
}

printer = PrettyPrinter(indent=2, width=50)
print(printer.pformat(data))

Output:

{
  'count': 2,
  'users': [
    {
      'age': 30,
      'name': 'Alice',
      'tags': {'developer', 'python'},
    },
    {
      'age': 25,
      'name': 'Bob',
      'tags': {'java', 'tester'},
    },
  ],
}

Mermaid Diagram: Structure of pprint.py

classDiagram
    class PrettyPrinter {
        -_depth: int | None
        -_indent_per_level: int
        -_width: int
        -_dispatch: dict
        +__init__(indent: int, width: int, depth: int | None)
        +pformat(object: Any) str
        -_format(object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int) void
        -_repr(object: Any, context: set[int], level: int) str
        -_safe_repr(object: Any, context: set[int], maxlevels: int | None, level: int) str
        -_pprint_dict(...)
        -_pprint_list(...)
        -_pprint_tuple(...)
        -_pprint_set(...)
        -_pprint_str(...)
        -_pprint_bytes(...)
        -_pprint_bytearray(...)
        -_pprint_default_dict(...)
        -_pprint_counter(...)
        -_pprint_ordered_dict(...)
        -_pprint_mappingproxy(...)
        -_pprint_simplenamespace(...)
        -_pprint_chain_map(...)
        -_pprint_deque(...)
        -_pprint_user_dict(...)
        -_pprint_user_list(...)
        -_pprint_user_string(...)
        -_format_dict_items(...)
        -_format_namespace_items(...)
        -_format_items(...)
    }

    class _safe_key {
        -obj: Any
        +__init__(obj: Any)
        +__lt__(other: _safe_key) bool
    }

    PrettyPrinter --> "_safe_key" : uses for sorting
    PrettyPrinter ..> "collections.*" : formats various types
    PrettyPrinter ..> "dataclasses.*" : formats dataclasses
    PrettyPrinter ..> "types.*" : formats special types

Summary

The `pprint.py` module is a robust and extensible pretty-printing utility for Python. It supports a wide variety of built-in and user-defined types, detects recursion to prevent infinite loops, and provides nicely formatted, readable string representations of complex nested data structures.

Its design centers around the `PrettyPrinter` class, which can be configured for indentation, line width, and depth, and uses a dispatch mechanism to handle different data types gracefully.

This module is a foundational tool for debugging and presenting data clearly in Python applications.