Implications of Union in argparse.Action.__call__ parameter types
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 5.1k
- 派生
- 2.1k
- 平均合并
- 1 天 19 小时
- 30 天内合并 PR
- 82
描述
https://github.com/python/typeshed/blob/c41034c3540c5abda10008dd6c17d8e6ff6cc634/stdlib/argparse.pyi#L364-L366
I'm wondering if the reasoning behind this choice has been discussed before. Return types of library functions generally avoid Union (python/mypy#1693). To me, the parameters of a user-provided callback are similar to the return type of a library function—the annotations reflect objects passed to user code, and the user may have runtime control of their types. It is, however, more removed from the runtime context because the class must be first defined and then referenced.
If I override __call__ with an implementation that will only ever see str:
import argparse
class CSVCallback(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, list(values.split(',')))
parser = argparse.ArgumentParser()
parser.add_argument('-o', action=CSVCallback, default=[])
args = parser.parse_args()
pyright complains, based on what appears to be a correct interpretation of the stub:
repr.py:5:51 - error: Cannot access member "split" for type "Sequence[Any]"
Member "split" is unknown (reportGeneralTypeIssues)
repr.py:5:51 - error: "split" is not a known member of "None" (reportOptionalMemberAccess)
Would the appropriate solution be to add assert isinstance(values, str) at the beginning of every callback? Or is this actually abuse of action=..., which should be replaced with type=..., like this?
def csv_callback(value: str) -> list[str]:
return list(value.split(','))
parser.add_argument('-o', type=csv_callback, default=[])
Since these examples are based on 10-year-old optparse code that was ported 1:1 to argparse 2 years ago, I'm not considering reimplementing them like that—they aren't broken, and the less trivial examples reference parser.error and the previous value of self.dest. But I'd rather avoid the asserts, so for new code I would probably prefer that pattern.
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先检查 stdlib/argparse.pyi 的第 364-366 行以及关于库接口中 Union 的关联讨论。将 Action callback 示例与 type= 示例进行比较,并确定应该修改 stub,还是应该记录现有的 annotation;完成此项工作需要获得 maintainer 批准的解决方案。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- tooling
- Issue 类型
- 缺陷
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100