python-humanize / python-humanize/humanize

`naturalsize()` raises `ValueError` for custom format strings with text

未关闭 适合新手
#366 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
757
派生
148
平均合并
6 天 1 小时
30 天内合并 PR
12

描述

Environment

  • humanize 4.16.0 and current main at 42b4a1db
  • Python 3.11.15

Reproduction

import humanize

print(humanize.naturalsize(999_999, gnu=True, format="Size: %.1f"))

humanize 4.15.0 returns:

Size: 976.6K

humanize 4.16.0 and current main raise:

ValueError: could not convert string to float: 'Size: 976.6'

Expected behavior

The documented custom formatter should continue to accept text around the numeric conversion.
Since this behavior worked in 4.15.0, preserving it would avoid a backward compatibility regression.

Cause

PR #329 added unit rollover handling. The new condition formats the mantissa with the
user-provided format and passes the entire result to float():

float(format % (abs_bytes / (base**exp)))

This works for a plain numeric format such as "%.1f", but not for a general formatter
such as "Size: %.1f".

Suggested fix

It might be preferable not to require the complete user-formatted result to be parseable as a float. One
backward-compatible option is to apply rollover only when the formatted result is a
plain numeric string, and otherwise preserve the pre-4.16 behavior. A more complete
solution could derive the rounded numeric mantissa independently from surrounding text.

It might also be worth adding a regression test covering both a prefix and a suffix.

How this was found

This was found by change-directed differential testing: reviewing the recent rollover change, mapping it to the public naturalsize() API, and constructing a documented custom formatter that reaches the newly added float(format % value) expression.

Related: #329, which fixes rollover but does not discuss custom format strings.

Thanks for taking the time to review this report! I appreciate all the work that goes into maintaining this project.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 naturalsize() 入口点开始,检查 PR #329 引入的单位进位处理,尤其是报告中描述的自定义格式路径。为同时包含前缀和后缀的格式字符串添加回归测试,然后运行相关测试套件;完成的标准是这些格式保持 4.16 之前的行为,同时普通数字格式仍能正常进行进位。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
api
Issue 类型
缺陷
难度
2/5
预计耗时
1-3 小时
活跃度
冷清
描述清晰度
描述清楚
新手友好度
75/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。