Skip to content

fix(time): catch OverflowError for non-finite floats (#333) - #373

Open
MeiSiristhebest wants to merge 4 commits into
python-humanize:mainfrom
MeiSiristhebest:fix/overflow-error-inf
Open

fix(time): catch OverflowError for non-finite floats (#333)#373
MeiSiristhebest wants to merge 4 commits into
python-humanize:mainfrom
MeiSiristhebest:fix/overflow-error-inf

Conversation

@MeiSiristhebest

Copy link
Copy Markdown

Description

Fixes #333 where naturaldelta(), naturaltime(), and precisedelta() raise an uncaught OverflowError when passed float('inf') or float('-inf').

Proposed Solution

Expand exception handling in _date_and_delta() and naturaldelta() from (ValueError, TypeError) to (ValueError, TypeError, OverflowError).

Testing Evidence

  • Added tests in tests/test_time.py covering float('inf') and float('-inf').
  • Full test suite passed (719 passed, 74 skipped, 0 failed).

@hugovk

hugovk commented Aug 2, 2026

Copy link
Copy Markdown
Member

Why is this better than the other 5 or so PRs opened for #333?

@MeiSiristhebest

Copy link
Copy Markdown
Author

Good point. #334 handles naturaldelta, but naturaltime and precisedelta also crash on inf because they go through _date_and_delta:

>>> humanize.naturaltime(float("inf"))
OverflowError: cannot convert float infinity to integer
>>> humanize.precisedelta(float("inf"))
OverflowError: cannot convert float infinity to integer

This PR patches _date_and_delta so all three functions handle non-finite floats.

You're right that catching OverflowError broadly was wrong — it suppressed exceptions for large finite floats like 1e30. I've updated this PR to match #334's check using math.isfinite(), restored the docstring, and added a test for the finite overflow behavior.

If you'd prefer to fold the _date_and_delta fix into #334 instead, I'm also happy to close this one.

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