Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/humanize/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

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

from math import log
from math import isfinite, log

from humanize.i18n import _gettext as _
from humanize.number import _format_not_finite

suffixes = {
"decimal": (
Expand Down Expand Up @@ -90,6 +91,10 @@ def naturalsize(

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

if abs_bytes == 1 and not gnu:
Expand Down
17 changes: 17 additions & 0 deletions tests/test_filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

from __future__ import annotations

import math

import pytest

import humanize
Expand Down Expand Up @@ -103,3 +105,18 @@ def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) ->
test_args[0] = f"-{test_args[0]}"

assert humanize.naturalsize(*test_args) == "-" + expected


@pytest.mark.parametrize(
"value, expected",
[
(math.nan, "NaN"),
(math.inf, "+Inf"),
(-math.inf, "-Inf"),
("nan", "NaN"),
("inf", "+Inf"),
("-inf", "-Inf"),
],
)
def test_naturalsize_non_finite(value: float | str, expected: str) -> None:
assert humanize.naturalsize(value) == expected