Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
14 changes: 12 additions & 2 deletions src/humanize/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@

from __future__ import annotations

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

from math import log
from math import isfinite, log

# Import isfinite so we can check whether a number is
# a normal finite number or NaN / positive infinity / negative infinity.
# Reuse the existing helper from number.py so that
# naturalsize() behaves consistently with other numeric
# humanization functions in the library.
from humanize.i18n import _gettext as _
from humanize.number import _format_not_finite

suffixes = {
"decimal": (
Expand Down Expand Up @@ -92,6 +98,10 @@ def naturalsize(
bytes_ = float(value)
abs_bytes = abs(bytes_)

# Handle NaN and infinity before filesize formatting.
if not isfinite(bytes_):
return _format_not_finite(bytes_)

if abs_bytes == 1 and not gnu:
return _("%d Byte") % int(bytes_)

Expand Down
17 changes: 16 additions & 1 deletion 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 @@ -95,11 +97,24 @@
)
def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) -> None:
assert humanize.naturalsize(*test_args) == expected

# Retest with negative input
if isinstance(test_args[0], int):
test_args[0] *= -1
else:
test_args[0] = f"-{test_args[0]}"

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


@pytest.mark.parametrize(
"test_input, expected",
[
(math.nan, "NaN"),
(math.inf, "+Inf"),
(-math.inf, "-Inf"),
],
)
def test_naturalsize_not_finite(test_input: float, expected: str) -> None:
assert humanize.naturalsize(test_input) == expected
assert humanize.naturalsize(test_input, binary=True) == expected
assert humanize.naturalsize(test_input, gnu=True) == expected