Skip to content

naturaldelta: include OverflowError in the int() guard so float('inf') returns unchanged#342

Open
HrachShah wants to merge 3 commits into
python-humanize:mainfrom
HrachShah:fix/naturaldelta-integer-overflow-from-inf
Open

naturaldelta: include OverflowError in the int() guard so float('inf') returns unchanged#342
HrachShah wants to merge 3 commits into
python-humanize:mainfrom
HrachShah:fix/naturaldelta-integer-overflow-from-inf

Conversation

@HrachShah

Copy link
Copy Markdown

Fixes #333.

naturaldelta() documents that a non-finite float value (e.g. NaN, inf) is "returned unchanged." The previous code wrapped the int(value) probe in except (ValueError, TypeError), which catches NaN (int(float('nan')) raises ValueError) but misses float('inf') and float('-inf') — those raise OverflowError from the same conversion. The result was an uncaught OverflowError: cannot convert float infinity to integer for humanize.naturaldelta(float('inf')), in contradiction with the docstring.

Adding OverflowError to the caught tuple restores the documented behaviour: naturaldelta(float('inf')) now returns 'inf' and naturaldelta(float('-inf')) returns '-inf', symmetric with the existing NaN case.

Two new parametrized cases (float("inf") and float("-inf")) on the existing test_naturaldelta exercise the issue. They fail on the pre-fix code with the exact OverflowError reported in #333 and pass with the fix. The math.isfinite(test_input) guard on the existing naturaldelta(-test_input) symmetry assertion is needed because -float('inf') is float('-inf') (and vice versa), so negating and re-formatting would not round-trip.

Verified with python3 -m pytest tests/: 727 passed, 69 skipped (unrelated).

Zo Bot and others added 3 commits July 1, 2026 01:55
…) returns unchanged

The docstring says naturaldelta returns non-number input unchanged. int(float('inf')) raises OverflowError (not ValueError or TypeError), so the existing except (ValueError, TypeError) clause let it escape.

The two new test cases (float('inf') and float('-inf')) fail on the pre-fix code with OverflowError and pass once OverflowError is added to the except tuple. The existing 'NaN' string case still returns "NaN" because str('NaN') is 'NaN' and float('NaN') → nan → int(nan) still raises ValueError which is still caught.
@hugovk

hugovk commented Jul 2, 2026

Copy link
Copy Markdown
Member

There's already an approved PR for this: #334.

What's wrong with that PR? What does this PR add or do better?

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

naturaldelta() raises OverflowError on float('inf') instead of returning it unchanged

2 participants