From 82c0a279f18fbcd8401af673df57ef2f22097f2c Mon Sep 17 00:00:00 2001 From: Anish Patel Date: Sat, 5 Sep 2026 15:10:18 -0400 Subject: [PATCH 1/2] Handle non-finite values in naturalsize --- src/humanize/filesize.py | 7 ++++++- tests/test_filesize.py | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/humanize/filesize.py b/src/humanize/filesize.py index fb675fdc..f1ef2e36 100644 --- a/src/humanize/filesize.py +++ b/src/humanize/filesize.py @@ -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": ( @@ -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: diff --git a/tests/test_filesize.py b/tests/test_filesize.py index e6956399..84fe161b 100644 --- a/tests/test_filesize.py +++ b/tests/test_filesize.py @@ -4,6 +4,8 @@ from __future__ import annotations +import math + import pytest import humanize @@ -103,3 +105,17 @@ 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 From d205f650606d8b6780a341fb21045147e397d2da Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 5 Sep 2026 19:12:28 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- tests/test_filesize.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_filesize.py b/tests/test_filesize.py index 84fe161b..9cea09bb 100644 --- a/tests/test_filesize.py +++ b/tests/test_filesize.py @@ -106,6 +106,7 @@ def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) -> assert humanize.naturalsize(*test_args) == "-" + expected + @pytest.mark.parametrize( "value, expected", [