From cb0fc367a6f03ba7a11b17728c98e4f22ade5aca Mon Sep 17 00:00:00 2001 From: longint2 <251122526+longint2@users.noreply.github.com> Date: Sat, 5 Dec 2026 22:46:17 +0800 Subject: [PATCH] fix: preserve literal text in custom filesize formats --- src/humanize/filesize.py | 13 +++++++++++-- tests/test_filesize.py | 17 +++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/humanize/filesize.py b/src/humanize/filesize.py index 386752b2..618a1f84 100644 --- a/src/humanize/filesize.py +++ b/src/humanize/filesize.py @@ -104,8 +104,17 @@ def naturalsize( # mantissa afterward; rounding can push it up to `base` (e.g. 999999 is # 999.999 kB, which formats to "1000.0 kB"). When that happens and a larger # suffix is available, step up one suffix so the result reads "1.0 MB". - if exp < len(suffix) and abs(float(format % (abs_bytes / (base**exp)))) >= base: - exp += 1 + if exp < len(suffix): + formatted = format % (abs_bytes / (base**exp)) + try: + rounded = float(formatted) + except ValueError: + # Custom formats may include literal text (e.g. "~%.1f"). + # Keep the suffix chosen from the byte count in that case. + pass + else: + if abs(rounded) >= base: + exp += 1 space = "" if gnu else " " ret: str = format % (bytes_ / (base**exp)) + space + _(suffix[exp - 1]) return ret diff --git a/tests/test_filesize.py b/tests/test_filesize.py index 645751b9..af3fd9b5 100644 --- a/tests/test_filesize.py +++ b/tests/test_filesize.py @@ -7,6 +7,23 @@ import humanize +@pytest.mark.parametrize( + "value, binary, gnu, fmt, expected", + [ + (3000, False, False, "~%.1f", "~3.0 kB"), + (-3000, False, False, "~%.1f", "~-3.0 kB"), + (3000000, False, False, "%.1f (approx)", "3.0 (approx) MB"), + (3072, True, False, "~%.2f", "~3.00 KiB"), + (3072, False, True, "~%.2f", "~3.00K"), + (3000, False, False, "%.1f%%", "3.0% kB"), + ], +) +def test_custom_format_with_literal_text( + value: int, binary: bool, gnu: bool, fmt: str, expected: str +) -> None: + assert humanize.naturalsize(value, binary=binary, gnu=gnu, format=fmt) == expected + + @pytest.mark.parametrize( "test_args, expected", [