Skip to content

gh-89774: Fix pprint ignoring the depth limit at small width#153157

Open
tonghuaroot wants to merge 1 commit into
python:mainfrom
tonghuaroot:pprint-depth-width
Open

gh-89774: Fix pprint ignoring the depth limit at small width#153157
tonghuaroot wants to merge 1 commit into
python:mainfrom
tonghuaroot:pprint-depth-width

Conversation

@tonghuaroot

@tonghuaroot tonghuaroot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

PrettyPrinter._format re-dispatches to the per-type formatter (_pprint_dict, _pprint_list, ...) whenever a node's repr exceeds the available line width. Those formatters re-expand children that _safe_repr had already folded to ... at the depth limit, so a small width silently defeats depth.

>>> import pprint
>>> pprint.pformat({1: {2: {3: 3}}}, depth=1, width=80)
'{1: {...}}'
>>> pprint.pformat({1: {2: {3: 3}}}, depth=1, width=5)
'{1: {2: {3: 3}}}'   # depth ignored

The fix skips the re-dispatch once the depth limit is reached, using the same boundary _safe_repr uses (level >= self._depth). Depth truncation is now independent of width, which also restores the narrow-width example documented in Doc/library/pprint.rst.

The regression test covers the dict, list, and tuple formatter branches and asserts that a narrow width folds at the same level as the default width. depth is always positive (__init__ rejects depth <= 0), so the is not None guard and _safe_repr's truthiness check are equivalent here.

I have left the backport labels for a maintainer to assign.

Skip the per-type re-dispatch in _format once the depth limit is reached, so depth truncation no longer depends on width.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant