Skip to content
Closed
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
10 changes: 8 additions & 2 deletions src/humanize/filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,14 @@ 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):
mantissa_text = format % (abs_bytes / (base**exp))
try:
mantissa = float(mantissa_text)
except ValueError:
mantissa = None
if mantissa is not None and abs(mantissa) >= base:
exp += 1
space = "" if gnu else " "
ret: str = format % (bytes_ / (base**exp)) + space + _(suffix[exp - 1])
return ret
11 changes: 11 additions & 0 deletions tests/test_filesize.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,14 @@ 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


def test_naturalsize_custom_format_with_text() -> None:
# regression: custom format strings with surrounding text must not crash
# https://github.com/python-humanize/humanize/issues/366
assert (
humanize.naturalsize(999_999, gnu=True, format="Size: %.1f") == "Size: 976.6K"
)
assert (
humanize.naturalsize(999_999, gnu=True, format="%.1f bytes") == "976.6 bytesK"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"976.6 bytesK" is nonsense! 🙃

)
Loading