Skip to content

gh-161114: Speed up pprint on deeply nested containers - #161115

Open
gpshead wants to merge 1 commit into
python:mainfrom
gpshead:pprint-nested-width-cutoff
Open

gpshead wants to merge 1 commit into
python:mainfrom
gpshead:pprint-nested-width-cutoff

Conversation

@gpshead

@gpshead gpshead commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

PrettyPrinter._format() now asks _safe_repr() for a container's one-line repr with the remaining line width as a limit, and the list/tuple, dict and dict-view loops stop with a private _TooWide as soon as the repr gets wider than that, so the "does it fit?" check costs at most a line's worth of work per nesting level instead of the whole subtree. The limit is passed through an instance attribute so format()'s signature is unchanged, and it is not applied when format() is overridden, since an override may shorten what it gets from PrettyPrinter.format(); such subclasses keep the current speed. pformat() output, isreadable() and isrecursive() were compared against main on 18,000 random nested structures with various width/compact/expand/depth/sort_dicts options and are identical. A 300-deep list of 20,000 ints goes from 2.7 s to 0.11 s and ordinary wrapped output gets about 20% faster; small objects that fit on one line are a few percent slower from the extra bookkeeping.

Fixes #161114

ANT-2026-1RHKXQEC

Stop building a container's one-line repr as soon as it is wider than the
remaining line, instead of formatting the whole subtree at every level.
@gpshead gpshead self-assigned this Nov 1, 2026
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 1, 2026
@gpshead
gpshead marked this pull request as ready for review November 1, 2026 18:50
@gpshead
gpshead requested a review from warsaw November 1, 2026 21:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting core review type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Speed up pprint on deeply nested containers

1 participant