diff --git a/Lib/pprint.py b/Lib/pprint.py index 7355021998081d..3871b2f0c46320 100644 --- a/Lib/pprint.py +++ b/Lib/pprint.py @@ -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 diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py index 041c2072b9e253..33cc25e3679ca7 100644 --- a/Lib/test/test_pprint.py +++ b/Lib/test/test_pprint.py @@ -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 diff --git a/Misc/NEWS.d/next/Library/2026-07-06-10-00-00.gh-issue-89774.d3Pth1.rst b/Misc/NEWS.d/next/Library/2026-07-06-10-00-00.gh-issue-89774.d3Pth1.rst new file mode 100644 index 00000000000000..689b870ef8bd52 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-06-10-00-00.gh-issue-89774.d3Pth1.rst @@ -0,0 +1,2 @@ +Fix :mod:`pprint` ignoring the *depth* limit when a small *width* forces +nested structures onto multiple lines.