Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,10 @@ def _format(self, object, stream, indent, allowance, context, level):
return
rep = self._repr(object, context, level)
max_width = self._width - indent - allowance
if len(rep) > max_width:
# Past the depth limit _safe_repr already folded this to '...'; do not
# re-expand it just because it does not fit the width.
if len(rep) > max_width and not (
self._depth is not None and level >= self._depth):
p = self._dispatch.get(type(object).__repr__, None)
# Lazy import to improve module import time
from dataclasses import is_dataclass
Expand Down
18 changes: 18 additions & 0 deletions Lib/test/test_pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,6 +1039,24 @@ def test_depth(self):
self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)

def test_depth_with_narrow_width(self):
# gh-89774: a narrow width must not override the depth limit.
nested_dict = {1: {2: {3: 3}}}
nested_list = [1, [2, [3, [4]]]]
nested_tuple = (1, (2, (3,)))
self.assertEqual(pprint.pformat(nested_dict, depth=1, width=5),
'{1: {...}}')
self.assertEqual(pprint.pformat(nested_dict, depth=2, width=5),
'{1: {2: {...}}}')
self.assertEqual(pprint.pformat(nested_list, depth=1, width=6),
'[1,\n [...]]')
self.assertEqual(pprint.pformat(nested_tuple, depth=1, width=6),
'(1,\n (...))')
# Depth folding is independent of width: a narrow width folds at the
# same level as the default wide width.
self.assertEqual(pprint.pformat(nested_dict, depth=1, width=5),
pprint.pformat(nested_dict, depth=1))

def test_sort_unorderable_values(self):
# Issue 3976: sorted pprints fail for unorderable values.
n = 20
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :mod:`pprint` ignoring the *depth* limit when a small *width* forces
nested structures onto multiple lines.
Loading