On this page
  1. pprint
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Controlling Width, Depth & Insertion Order
  7. 2. Reusable PrettyPrinter Instance & Logging Integration
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

pprint

Prev: posixpath | Up: stdlib_module | Next: profile
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — pprint
Tags: #public #python3 #stdlib


Import

import pprint

Overview

Pretty-prints nested Python data structures (dict, list, tuple, set, dataclasses) with clean indentation, line wrapping, and optional depth truncation. Reach for pprint.pprint() or pprint.pformat() during debugging, CLI diagnostics, and readable test failure messages.

Quick Start

import pprint

data = {"users": [{"id": 1, "name": "Ada", "roles": ["admin", "dev"]}], "active": True}
formatted = pprint.pformat(data, width=40, sort_dicts=False)
assert "'name': 'Ada'" in formatted

Implementation Walkthrough

1. Controlling Width, Depth & Insertion Order

Pass sort_dicts=False (Python 3.8+) to preserve dictionary insertion order and depth= to prevent giant nested trees from flooding the terminal:

import pprint

nested = {"a": {"b": {"c": {"d": [1, 2, 3]}}}}
summary = pprint.pformat(nested, depth=2, sort_dicts=False)
assert summary == "{'a': {'b': {...}}}"

2. Reusable PrettyPrinter Instance & Logging Integration

Use pformat() when integrating with logging so output goes through your logger rather than printing directly to stdout:

import logging
import pprint

pp = pprint.PrettyPrinter(indent=2, width=80, compact=True, sort_dicts=False)
logging.getLogger(__name__).debug("State:\n%s", pp.pformat({"items": list(range(10))}))

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes