Skip to content

Fix ValueError in metric()/scientific() with precision 0#352

Open
santhreal wants to merge 1 commit into
python-humanize:mainfrom
santhreal:fix/scientific-negative-precision
Open

Fix ValueError in metric()/scientific() with precision 0#352
santhreal wants to merge 1 commit into
python-humanize:mainfrom
santhreal:fix/scientific-negative-precision

Conversation

@santhreal

Copy link
Copy Markdown

metric(value, precision=0) raises ValueError: Format specifier missing precision when the magnitude falls back to scientific(), because metric calls scientific(value, precision - 1), so precision 0 becomes -1 and builds an invalid format spec "{:.-1e}". scientific(value, -1) directly hits the same path.

#159 fixed this for the non-scientific metric path; this covers the scientific() fallback it did not reach. scientific now clamps a negative precision to zero.

import humanize
humanize.metric(1e300, "m", 0)   # was: ValueError; now: "1 x 10³⁰⁰m"
humanize.scientific(1e300, -1)   # was: ValueError; now: "1 x 10³⁰⁰"

scientific() built its format spec as f"{{:.{int(precision)}e}}", so a
negative precision produced an invalid spec ("{:.-1e}") and raised
ValueError. This is reachable from the public API through metric(value,
precision=0): for magnitudes that fall back to scientific notation,
metric() calls scientific(value, precision - 1), i.e. scientific(value,
-1). PR python-humanize#159 added the same max(0, ...) clamp to metric()'s main path but
not to scientific(). Clamp the precision to zero.
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