FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Fix naturalsize() ValueError for custom formats containing text by Sanjays2402 · Pull Request #367 · python-humanize/humanize · GitHub

Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
4 changes: 3 additions & 1 deletion src/humanize/filesize.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ 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:
# `format` may contain text around the conversion, so compare the rendered
# mantissa with the rendered base instead of parsing it back to a float.
if exp < len(suffix) and format % (abs_bytes / (base**exp)) == format % base:
exp += 1
space = "" if gnu else " "
ret: str = format % (bytes_ / (base**exp)) + space + _(suffix[exp - 1])
Expand Down
4 changes: 4 additions & 0 deletions tests/test_filesize.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@
([1024**2 - 1, True], "1.0 MiB"),
([1024**3 - 1, True], "1.0 GiB"),
([1024**2 - 1, False, True], "1.0M"),
# A custom format may contain text around the numeric conversion, which
# must not break the rounding carry-over check above.
([999999, False, True, "%.1f~"], "976.6~K"),
([999999, False, False, "%.1f~"], "1.0~ MB"),
],
)
def test_naturalsize(test_args: list[int] | list[int | bool], expected: str) -> None:
Expand Down

Back | FazBrowse Home | New Git URL