python / python/cpython

argparse: fix inconsistency in `add_argument()` API when using positional argument with `dest=` parameter

未关闭
#117,834 0 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

type-feature
主要语言
Python
星标
77.2k
派生
36k
PR 合并指标
PR 指标待抓取

描述

Feature or enhancement

Proposal:

Current behaviour is ugly and inconsistent between options and positional arguments:

parser.add_argument("--option-foo",    dest="my_foo_option_var")
parser.add_argument(metavar="BAR_ARG", dest="my_bar_arg_var")
# or even worse
parser.add_argument("my_bar_arg_var",  metavar="BAR_ARG")

Proposed change streamlines the library API

parser.add_argument("--option-foo", dest="my_foo_option_var")
parser.add_argument("BAR_ARG",      dest="my_bar_arg_var")

I think a small patch could fix this without breaking any existing code.

--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -1423,7 +1423,7 @@
     # =======================
     def add_argument(self, *args, **kwargs):
         """
-        add_argument(dest, ..., name=value, ...)
+        add_argument(arg, ..., name=value, ...)
         add_argument(option_string, option_string, ..., name=value, ...)
         """
 
@@ -1433,7 +1433,11 @@
         chars = self.prefix_chars
         if not args or len(args) == 1 and args[0][0] not in chars:
             if args and 'dest' in kwargs:
-                raise ValueError('dest supplied twice for positional argument')
+                if 'metavar' not in kwargs:
+                    kwargs['metavar'] = args[0]
+                else:
+                    raise ValueError('`arg` supplied with both `dest` and `metavar` for positional argument')
+                args = (kwargs.pop('dest'), )
             kwargs = self._get_positional_kwargs(*args, **kwargs)
 
         # otherwise, we're adding an optional argument
Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

贡献指南

打开贡献指南

从这里开始

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

调研方向

从 Lib/argparse.py 中的 add_argument 入口开始,根据该提案检查当前对位置参数的处理。检查现有的 argparse 测试,并确认新的位置参数 dest 和 metavar 行为能够正常工作,同时保持现有形式的兼容性。

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

评估

技术栈
python
领域
cli
Issue 类型
功能
难度
3/5
预计耗时
1-2 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

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