Python pprint Indentation and Nesting Depth

Python's pprint module provides the PrettyPrinter class to format complex data structures into clean, readable text. When handling deeply nested lists, tuples, or dictionaries, the default output of standard printing can quickly become unwieldy. This article explores how to configure pprint.PrettyPrinter using its core parameters—specifically indent and depth—to regulate visual spacing and suppress excessive hierarchy levels for clearer data inspection.

Controlling Indentation with the indent Parameter

The indent parameter determines the number of spaces added for each successive nesting level.

import pprint

data = {
    'users': [
        {'name': 'Alice', 'role': 'Admin'},
        {'name': 'Bob', 'role': 'User'}
    ]
}

# Standard 4-space indentation
printer = pprint.PrettyPrinter(indent=4)
printer.pprint(data)

Output:

{   'users': [   {   'name': 'Alice', 'role': 'Admin'},
                 {   'name': 'Bob', 'role': 'User'}]}

Increasing indent visually offsets nested structures, making boundaries between nested levels distinct.


Limiting Nesting Hierarchy with the depth Parameter

The depth parameter controls how many levels of nested data structures are displayed before truncation occurs.

import pprint

deep_data = {
    'level1': {
        'level2': {
            'level3': {
                'level4': 'secret_value'
            }
        }
    }
}

# Restrict visibility to 2 levels
printer = pprint.PrettyPrinter(depth=2)
printer.pprint(deep_data)

Output:

{'level1': {'level2': {...}}}

The depth setting is particularly useful when analyzing high-level schemas or large JSON-like responses where inspecting deep inner contents is unnecessary.


Combining indent and depth with Line Constraints

indent and depth are frequently used together with the width and compact parameters to achieve optimal readability:

import pprint

payload = {
    'status': 'success',
    'records': [
        {'id': 1, 'meta': {'tags': ['python', 'dev'], 'active': True}},
        {'id': 2, 'meta': {'tags': ['api', 'rest'], 'active': False}},
    ]
}

# 2-space indentation, max depth of 3, constrained width
custom_printer = pprint.PrettyPrinter(indent=2, depth=3, width=50)
custom_printer.pprint(payload)

Output:

{ 'records': [ { 'id': 1,
                 'meta': {'active': True, 'tags': [...]}},
               { 'id': 2,
                 'meta': {'active': False, 'tags': [...]}}],
  'status': 'success'}

In this output, indent=2 preserves neat alignment, depth=3 hides the low-level list values inside the 'tags' field using [...], and width=50 wraps dictionaries into multi-line representations.