Skip to content

Commit fec14ca

Browse files
committed
fix(filesize): don't parse formatted mantissa back to float
naturalsize()'s unit rollover check ran the user-supplied format string through float(), which raises ValueError whenever that format contains text around the numeric conversion (e.g. "Size: %.1f"), a regression from 4.15.0. Compare the rendered mantissa against the rendered base instead, so the carry-over still works and arbitrary formats are accepted again. Closes #366
1 parent 42b4a1d commit fec14ca

2 files changed

Lines changed: 7 additions & 1 deletion

File tree

src/humanize/filesize.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,9 @@ def naturalsize(
103103
# mantissa afterward; rounding can push it up to `base` (e.g. 999999 is
104104
# 999.999 kB, which formats to "1000.0 kB"). When that happens and a larger
105105
# suffix is available, step up one suffix so the result reads "1.0 MB".
106-
if exp < len(suffix) and abs(float(format % (abs_bytes / (base**exp)))) >= base:
106+
# `format` may contain text around the conversion, so compare the rendered
107+
# mantissa with the rendered base instead of parsing it back to a float.
108+
if exp < len(suffix) and format % (abs_bytes / (base**exp)) == format % base:
107109
exp += 1
108110
space = "" if gnu else " "
109111
ret: str = format % (bytes_ / (base**exp)) + space + _(suffix[exp - 1])

tests/test_filesize.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@
9191
([1024**2 - 1, True], "1.0 MiB"),
9292
([1024**3 - 1, True], "1.0 GiB"),
9393
([1024**2 - 1, False, True], "1.0M"),
94+
# A custom format may contain text around the numeric conversion, which
95+
# must not break the rounding carry-over check above.
96+
([999999, False, True, "%.1f~"], "976.6~K"),
97+
([999999, False, False, "%.1f~"], "1.0~ MB"),
9498
],
9599
)
96100
def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) -> None:

0 commit comments

Comments
 (0)