Skip to content

Don't raise OverflowError for ints larger than a float - #481

Closed
beduldul wants to merge 1 commit into
python-humanize:mainfrom
beduldul:fix/overflow-on-large-int
Closed

beduldul wants to merge 1 commit into
python-humanize:mainfrom
beduldul:fix/overflow-on-large-int

Conversation

@beduldul

Copy link
Copy Markdown

Fixes #419

Six functions in humanize.number call float(value) only to check for NaN and infinity before converting to int. An int outside the float range raises OverflowError, which isn't caught, so it reaches the caller:

>>> import humanize
>>> humanize.apnumber(10**400)
OverflowError: int too large to convert to float

intword, ordinal, metric, scientific and fractional do the same. intcomma is fine because it skips the float conversion when the value is already an int.

Changes proposed in this pull request:

  • Catch OverflowError alongside TypeError and ValueError, falling back to str(value) — what the docstrings already say happens to values that can't be converted.
  • Give metric a try block, since it called math.isfinite(value) with no guard at all.
  • Add test_large_int_does_not_overflow, parametrized over the six functions.

Without the change those six cases fail with OverflowError; with it the suite is 752 passed, 132 skipped.

Six functions in humanize.number call float(value) just to test for NaN and
infinity before converting to int. For an int outside the float range that
conversion raises OverflowError, which isn't in the except clause, so it
escapes to the caller:

    >>> humanize.apnumber(10**400)
    OverflowError: int too large to convert to float

Same for intword, ordinal, metric, scientific and fractional. intcomma is
unaffected because it skips the float conversion when the value is an int.

Catch OverflowError alongside TypeError and ValueError and fall back to
str(value), which is what the docstrings already promise for values that
can't be converted. metric had no try block at all, so it gets one.
@hugovk

hugovk commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Fixes #419

This is the fourth PR for this issue.

@hugovk hugovk closed this Oct 25, 2026
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.

Several number functions raise OverflowError on integers larger than a float

2 participants