Skip to content

filesize: raise ValueError for non-finite bytes in naturalsize#349

Closed
HrachShah wants to merge 3 commits into
python-humanize:mainfrom
HrachShah:fix/naturalsize-reject-non-finite
Closed

filesize: raise ValueError for non-finite bytes in naturalsize#349
HrachShah wants to merge 3 commits into
python-humanize:mainfrom
HrachShah:fix/naturalsize-reject-non-finite

Conversation

@HrachShah

Copy link
Copy Markdown

Bug

naturalsize(float('nan')) raised ValueError: cannot convert float NaN to integer from inside the int(min(log(...))) exponent calculation, which is several levels removed from the call site. naturalsize(float('inf')) and naturalsize(float('-inf')) silently rendered as 'inf QB' / '-inf QB', which is not a meaningful byte count for any real caller.

Fix

Reject NaN, +inf, and -inf up front with a single math.isfinite(bytes_) check that names the rejected value in the error message. The same check covers string inputs that float() accepts but that don't represent a meaningful byte count ('inf', 'INF', 'NaN', etc.); non-numeric strings still reach the existing float() call and raise ValueError as before.

Tests

Eight new cases in tests/test_filesize.py:

  • test_naturalsize_rejects_non_finite: parametrized over float('nan'), float('inf'), float('-inf').
  • test_naturalsize_rejects_non_finite_strings: parametrized over 'nan', 'inf', '-inf', 'NaN', 'INF'.

Both assert that pytest.raises(ValueError, match='finite number of bytes') fires, so the fix is checked end-to-end on every relevant shape of non-finite input.

Three new doctest cases in naturalsize: naturalsize(0) (the abs < base path was previously untested), and explicit Traceback / ValueError cases for naturalsize(float('nan')) and naturalsize(float('inf')).

Full suite: 723 passed, 69 skipped (no regressions).

Zo Bot and others added 3 commits July 9, 2026 15:32
naturalsize(float('nan')) fell through to int(log(abs(nan), base)) and
raised a confusing 'cannot convert float NaN to integer' from int() on
the suffix exponent, far from the user's call site. naturalsize(+/-inf)
silently rendered as 'inf QB' / '-inf QB', a stringified float pasted in
front of a binary-scaled suffix.

Reject both up front with math.isfinite(bytes_) and a clear
ValueError naming the offending value. Strings like 'inf' / 'NaN' /
'-inf' go through float() first and trip the same check.

Adds 8 new test cases (3 floats + 5 strings) and 2 doctest examples.
@hugovk

hugovk commented Jul 9, 2026

Copy link
Copy Markdown
Member

Blocking and reporting @HrachShah for deleting CI here and python-attrs/attrs#1585 and opening duplicate PRs (#342) and updating that PR while my question.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants