Skip to content

Commit 82c0a27

Browse files
committed
Handle non-finite values in naturalsize
1 parent 3201e70 commit 82c0a27

2 files changed

Lines changed: 22 additions & 1 deletion

File tree

src/humanize/filesize.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44

55
__lazy_modules__ = {"humanize.i18n", "math"}
66

7-
from math import log
7+
from math import isfinite, log
88

99
from humanize.i18n import _gettext as _
10+
from humanize.number import _format_not_finite
1011

1112
suffixes = {
1213
"decimal": (
@@ -90,6 +91,10 @@ def naturalsize(
9091

9192
base = 1024 if (gnu or binary) else 1000
9293
bytes_ = float(value)
94+
if not isfinite(bytes_):
95+
# Match the rest of the library (see humanize.number): format NaN and
96+
# infinities instead of crashing or emitting a bogus suffix like "inf QB".
97+
return _format_not_finite(bytes_)
9398
abs_bytes = abs(bytes_)
9499

95100
if abs_bytes == 1 and not gnu:

tests/test_filesize.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
from __future__ import annotations
66

7+
import math
8+
79
import pytest
810

911
import humanize
@@ -103,3 +105,17 @@ def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) ->
103105
test_args[0] = f"-{test_args[0]}"
104106

105107
assert humanize.naturalsize(*test_args) == "-" + expected
108+
109+
@pytest.mark.parametrize(
110+
"value, expected",
111+
[
112+
(math.nan, "NaN"),
113+
(math.inf, "+Inf"),
114+
(-math.inf, "-Inf"),
115+
("nan", "NaN"),
116+
("inf", "+Inf"),
117+
("-inf", "-Inf"),
118+
],
119+
)
120+
def test_naturalsize_non_finite(value: float | str, expected: str) -> None:
121+
assert humanize.naturalsize(value) == expected

0 commit comments

Comments
 (0)