Skip to content

Comments

gh-145117: Fix pprint.isreadable() returning True for inf/nan#145120

Open
zetzschest wants to merge 2 commits intopython:mainfrom
zetzschest:fix/pprint_isreadable_float_specials_v2
Open

gh-145117: Fix pprint.isreadable() returning True for inf/nan#145120
zetzschest wants to merge 2 commits intopython:mainfrom
zetzschest:fix/pprint_isreadable_float_specials_v2

Conversation

@zetzschest
Copy link

Problem

pprint.isreadable() returns True for float('inf'), float('-inf'), and float('nan'), but their repr() values are not valid Python literals — eval() raises NameError. The documented contract of isreadable is that the representation can be used to recreate the value via eval().

Reproducer

import pprint
print(pprint.isreadable(float('inf')))  # True — but eval('inf') raises NameError

Fix

In Lib/pprint.py, in _safe_repr, add a check for float specials and return readable=False for them.

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.
@python-cla-bot
Copy link

python-cla-bot bot commented Feb 22, 2026

All commit authors signed the Contributor License Agreement.

CLA signed

if typ in _builtin_scalars:
return repr(object), True, False
rep = repr(object)
if typ is float and rep in ("inf", "-inf", "nan"):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This "problem" affects also complex numbers. You could use cmath.isfinite() to handle both cases.

Though, as I said in the issue thread - this looks rather as a documentation issue for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants