Argparse: inconsistent default handling between `nargs` values
未关闭
还没有人认领这个 Issue。
docs
stdlib
type-bug
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
day_names = ["mo", "tu", "we", "th", "fr", "sa", "su"]
days = [1, 2, 3, 4, 5, 6, 7]
def name_day(value):
return day_names.index(value) + 1
parser.add_argument(
'--day',
type=name_day,
default="mo",
nargs='?',
help="pick a day",
)
args = parser.parse_args()
print(args.day)
Actual results:
The above code block will print the value 1. However, if we change the arguments to
default=["mo"],
nargs='+',
The code will print the value ["mo"]. So it seems type conversion does not happen for default arguments when nargs specifies multiple arguments.
Expected results:
The supplied default values are converted, irrespective of the value of nargs.
CPython versions tested on:
3.13, 3.10
Operating systems tested on:
Linux
Linked PRs
- gh-132724
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先使用 argparse 重现该示例,并比较 nargs='?' 和 nargs='+' 的默认处理方式。跟踪 argparse 的参数处理入口,查看类型转换的差异所在,然后验证对于这两种形式,所提供的默认值都能以一致的方式进行转换,并保留预期的解析值。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- cli
- Issue 类型
- 缺陷
- 难度
- 3/5
- 预计耗时
- 1-2 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 35/100