Skip to content

Handle non-finite values in naturalsize - #390

Open
AnishPatel526 wants to merge 2 commits into
python-humanize:mainfrom
AnishPatel526:naturalsize-non-finite
Open

Handle non-finite values in naturalsize#390
AnishPatel526 wants to merge 2 commits into
python-humanize:mainfrom
AnishPatel526:naturalsize-non-finite

Conversation

@AnishPatel526

@AnishPatel526 AnishPatel526 commented Sep 5, 2026

Copy link
Copy Markdown

Changes proposed in this pull request:

  • naturalsize() now handles non-finite input consistently with the rest of the library. Every numeric formatter in humanize.number (ordinal, intcomma, intword, apnumber, fractional, scientific, clamp) already returns "NaN" / "+Inf" / "-Inf" for non-finite values via _format_not_finite. naturalsize() was the exception: naturalsize(float("nan")) raised ValueError: cannot convert float NaN to integer, and naturalsize(float("inf")) produced the bogus string "inf QB". It now returns "NaN" / "+Inf" / "-Inf".
  • Added a parametrized test_naturalsize_non_finite covering nan, inf, -inf as both floats and strings; it fails on main and passes with this change.

Before

>>> import humanize
>>> humanize.naturalsize(float("nan"))
ValueError: cannot convert float NaN to integer
>>> humanize.naturalsize(float("inf"))
'inf QB'

After

>>> humanize.naturalsize(float("nan"))
'NaN'
>>> humanize.naturalsize(float("inf"))
'+Inf'
>>> humanize.naturalsize(float("-inf"))
'-Inf'

The fix reuses the existing humanize.number._format_not_finite helper so output matches the other formatters exactly, and guards right after the float(value) conversion. Finite values are unaffected.

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.

1 participant