Skip to content

Commit 313474a

Browse files
committed
gh-89774: Fix pprint ignoring the depth limit at small width
Skip the per-type re-dispatch in _format once the depth limit is reached, so depth truncation no longer depends on width.
1 parent 0621639 commit 313474a

3 files changed

Lines changed: 24 additions & 1 deletion

File tree

Lib/pprint.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,10 @@ def _format(self, object, stream, indent, allowance, context, level):
195195
return
196196
rep = self._repr(object, context, level)
197197
max_width = self._width - indent - allowance
198-
if len(rep) > max_width:
198+
# Past the depth limit _safe_repr already folded this to '...'; do not
199+
# re-expand it just because it does not fit the width.
200+
if len(rep) > max_width and not (
201+
self._depth is not None and level >= self._depth):
199202
p = self._dispatch.get(type(object).__repr__, None)
200203
# Lazy import to improve module import time
201204
from dataclasses import is_dataclass

Lib/test/test_pprint.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,6 +1039,24 @@ def test_depth(self):
10391039
self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
10401040
self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
10411041

1042+
def test_depth_with_narrow_width(self):
1043+
# gh-89774: a narrow width must not override the depth limit.
1044+
nested_dict = {1: {2: {3: 3}}}
1045+
nested_list = [1, [2, [3, [4]]]]
1046+
nested_tuple = (1, (2, (3,)))
1047+
self.assertEqual(pprint.pformat(nested_dict, depth=1, width=5),
1048+
'{1: {...}}')
1049+
self.assertEqual(pprint.pformat(nested_dict, depth=2, width=5),
1050+
'{1: {2: {...}}}')
1051+
self.assertEqual(pprint.pformat(nested_list, depth=1, width=6),
1052+
'[1,\n [...]]')
1053+
self.assertEqual(pprint.pformat(nested_tuple, depth=1, width=6),
1054+
'(1,\n (...))')
1055+
# Depth folding is independent of width: a narrow width folds at the
1056+
# same level as the default wide width.
1057+
self.assertEqual(pprint.pformat(nested_dict, depth=1, width=5),
1058+
pprint.pformat(nested_dict, depth=1))
1059+
10421060
def test_sort_unorderable_values(self):
10431061
# Issue 3976: sorted pprints fail for unorderable values.
10441062
n = 20
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`pprint` ignoring the *depth* limit when a small *width* forces
2+
nested structures onto multiple lines.

0 commit comments

Comments
 (0)