Skip to content

Comments

gh-145117: fix pprint.isreadable() for non-finite float and complex values#145120

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

gh-145117: fix pprint.isreadable() for non-finite float and complex values#145120
zetzschest wants to merge 7 commits intopython:mainfrom
zetzschest:fix/pprint_isreadable_float_specials_v2

Conversation

@zetzschest
Copy link

@zetzschest zetzschest commented Feb 22, 2026

Issue

isreadable is documented as returning True if the object's repr is readable by the interpreter — implying eval(pformat(obj)) == obj. For non-finite float and complex values, isreadable returns True, but the roundtrip fails — eval raises NameError since inf and nan aren't valid Python expressions.

Reproducer

import pprint

print(pprint.isreadable(float('inf')))        # True — but eval('inf') raises NameError
print(pprint.isreadable(float('nan')))        # True
print(pprint.isreadable(complex(float('inf'), 0)))  # True

Fix

Two options: update the documentation to weaken the guarantee so isreadable no longer implies the eval roundtrip, or fix the implementation so non-finite float and complex values are correctly marked as not readable. We think the latter is the right call — the documented contract is reasonable and worth preserving. In _safe_repr, use cmath.isfinite() to catch both float and complex non-finite values:

if (typ is float or typ is complex) and not _cmath.isfinite(object):
    return rep, False, False

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

@zetzschest zetzschest changed the title gh-145117: Fix pprint.isreadable() returning True for inf/nan gh-145117: fix pprint.isreadable() for non-finite float and complex values Feb 24, 2026
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