Skip to content

Return non-finite floats unchanged from naturaldelta#343

Open
eeshsaxena wants to merge 1 commit into
python-humanize:mainfrom
eeshsaxena:fix-naturaldelta-inf
Open

Return non-finite floats unchanged from naturaldelta#343
eeshsaxena wants to merge 1 commit into
python-humanize:mainfrom
eeshsaxena:fix-naturaldelta-inf

Conversation

@eeshsaxena

Copy link
Copy Markdown

Summary

Fixes #333.

naturaldelta() documents that a value which cannot be converted to a number is "returned unchanged." float("nan") is handled (its int() raises ValueError, which is caught), but float("inf")/float("-inf") raise an uncaught OverflowError from int(value), because the except (ValueError, TypeError) clause omitted OverflowError. The behavior was asymmetric and contradicted the docstring.

Before

>>> humanize.naturaldelta(float("nan"))
'nan'
>>> humanize.naturaldelta(float("inf"))
OverflowError: cannot convert float infinity to integer

After

>>> humanize.naturaldelta(float("inf"))
'inf'
>>> humanize.naturaldelta(float("-inf"))
'-inf'

Implementation note

The catch is scoped to the int(value) guard only. A finite value too large to convert to a datetime.timedelta (e.g. 1e40) still raises OverflowError from timedelta(), as documented under Raises: - this is verified by an added test so the non-finite guard does not swallow the legitimate overflow.

Tests

Added test_naturaldelta_nonfinite (nan, inf, -inf returned unchanged) and test_naturaldelta_overflow (finite 1e40 still raises OverflowError). Full tests/test_time.py passes (387 passed).

naturaldelta() documents that a value which cannot be converted to a
number is returned unchanged. float("nan") was handled because int(nan)
raises ValueError, but float("inf")/float("-inf") raised an uncaught
OverflowError from int(value), which the except clause omitted.

Catch OverflowError alongside ValueError/TypeError around the int()
guard so infinity is returned unchanged, symmetric with nan. The catch
is scoped to the int() conversion only, so a finite value too large for
datetime.timedelta still raises OverflowError from timedelta(), as
documented.

Fixes python-humanize#333
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

1 participant