Skip to content
Open
5 changes: 4 additions & 1 deletion Lib/pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,10 @@ def _safe_repr(self, object, context, maxlevels, level):
# Return triple (repr_string, isreadable, isrecursive).
typ = type(object)
if typ in _builtin_scalars:
return repr(object), True, False
rep = repr(object)
if typ is float and rep in ("inf", "-inf", "nan"):
Comment thread
zetzschest marked this conversation as resolved.
Outdated
return rep, False, False
return rep, True, False

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

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_pprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,14 @@ def test_basic(self):
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))

def test_isreadable_float_specials(self):
# inf, -inf, nan are not valid Python literals so isreadable should be False
for v in (float("inf"), float("-inf"), float("nan")):
self.assertFalse(pprint.isreadable(v),
"expected not isreadable for %r" % (v,))
self.assertFalse(pprint.PrettyPrinter().isreadable(v),
"expected not isreadable for %r" % (v,))

def test_stdout_is_None(self):
with contextlib.redirect_stdout(None):
# smoke test - there is no output to check
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Fix :func:`pprint.isreadable` to return ``False`` for ``float('inf')``,
``float('-inf')``, and ``float('nan')``. Their string representations
(``inf``, ``-inf``, ``nan``) are not valid Python literals and cannot
be reconstructed via :func:`eval`, violating the documented contract of
:func:`~pprint.isreadable`.
Loading