Skip to content

Commit b48b37b

Browse files
uttam12331hugovkpre-commit-ci[bot]
authored
Return non-finite floats unchanged from naturaldelta (#334)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 08cf2c3 commit b48b37b

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

src/humanize/time.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,16 @@ def naturaldelta(
153153
delta = dt.timedelta(seconds=value)
154154
except (ValueError, TypeError):
155155
return str(value)
156+
except OverflowError:
157+
# `int(value)` raises OverflowError for non-finite floats (inf/-inf),
158+
# which, like NaN, are returned unchanged. A too-large *finite* value
159+
# (whose OverflowError comes from `timedelta`) is still raised, per
160+
# the documented `OverflowError` contract.
161+
import math
162+
163+
if not math.isfinite(value):
164+
return str(value)
165+
raise
156166

157167
use_months = months
158168

tests/test_time.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,25 @@ def test_naturaldelta(test_input: float | dt.timedelta, expected: str) -> None:
138138
assert humanize.naturaldelta(-test_input) == expected
139139

140140

141+
@pytest.mark.parametrize(
142+
"value, expected",
143+
[
144+
(float("nan"), "nan"),
145+
(float("inf"), "inf"),
146+
(float("-inf"), "-inf"),
147+
],
148+
)
149+
def test_naturaldelta_non_finite(value: float, expected: str) -> None:
150+
"""Non-finite floats are returned unchanged instead of raising."""
151+
assert humanize.naturaldelta(value) == expected
152+
153+
154+
def test_naturaldelta_too_large_value_raises() -> None:
155+
"""A too-large *finite* value still raises OverflowError (unlike inf)."""
156+
with pytest.raises(OverflowError):
157+
humanize.naturaldelta(1e30)
158+
159+
141160
@freeze_time(FROZEN_DATE)
142161
@pytest.mark.parametrize(
143162
"test_input, expected",

0 commit comments

Comments
 (0)