Skip to content

Commit b11ec5d

Browse files
gh-145117: Fix pprint.isreadable() returning True for inf/nan
inf, -inf, nan repr strings are not valid Python literals so eval() fails on them. Check repr string inside _builtin_scalars branch instead of using math.isinf/isnan.
1 parent 5944a53 commit b11ec5d

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

Lib/pprint.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -627,7 +627,10 @@ def _safe_repr(self, object, context, maxlevels, level):
627627
# Return triple (repr_string, isreadable, isrecursive).
628628
typ = type(object)
629629
if typ in _builtin_scalars:
630-
return repr(object), True, False
630+
rep = repr(object)
631+
if typ is float and rep in ("inf", "-inf", "nan"):
632+
return rep, False, False
633+
return rep, True, False
631634

632635
r = getattr(typ, "__repr__", None)
633636

Lib/test/test_pprint.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,14 @@ def test_basic(self):
182182
self.assertTrue(pp.isreadable(safe),
183183
"expected isreadable for %r" % (safe,))
184184

185+
def test_isreadable_float_specials(self):
186+
# inf, -inf, nan are not valid Python literals so isreadable should be False
187+
for v in (float("inf"), float("-inf"), float("nan")):
188+
self.assertFalse(pprint.isreadable(v),
189+
"expected not isreadable for %r" % (v,))
190+
self.assertFalse(pprint.PrettyPrinter().isreadable(v),
191+
"expected not isreadable for %r" % (v,))
192+
185193
def test_stdout_is_None(self):
186194
with contextlib.redirect_stdout(None):
187195
# smoke test - there is no output to check
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix :func:`pprint.isreadable` to return ``False`` for ``float('inf')``,
2+
``float('-inf')``, and ``float('nan')``. Their string representations
3+
(``inf``, ``-inf``, ``nan``) are not valid Python literals and cannot
4+
be reconstructed via :func:`eval`, violating the documented contract of
5+
:func:`~pprint.isreadable`.

0 commit comments

Comments
 (0)