Skip to content

Commit 672b0f2

Browse files
gh-XXXXX: Fix pprint.isreadable() returning True for inf/nan
inf, -inf, nan are not valid Python literals so eval() fails on them. isreadable() should return False for these values.
1 parent 5944a53 commit 672b0f2

2 files changed

Lines changed: 12 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

0 commit comments

Comments
 (0)