Skip to content

Speed up pprint on deeply nested containers #161114

Description

@gpshead

Feature or enhancement

Proposal:

pprint.pformat() decides whether a container fits on the current line by building its complete one-line repr, and when it doesn't, it repeats that for each child. For deeply nested data the innermost items are therefore formatted once per enclosing level, so the time grows with size times depth.

import json, pprint, time
flat = json.loads("[" + ",".join(["1"] * 20000) + "]")
deep = json.loads("[" * 300 + ",".join(["1"] * 20000) + "]" * 300)
for o in flat, deep:
    t = time.perf_counter(); pprint.pformat(o); print(time.perf_counter() - t)

The nested version takes about 40x longer than the flat one (0.07 s vs 2.6 s on a release build). The fit check can stop once the line is full, which makes it cost at most the line width per level; output stays the same.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Activity

  1. self-assigned this
    on Nov 1, 2026
  2. added
    type-featureA feature request or enhancement
    performancePerformance or resource usage
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions