python / python/cpython

Add ability to retrieve choices from `argparse.ArgumentParser`

未關閉
#125,363 17 則留言 0 個 reaction 已指派 1 人 在 GitHub 檢視

@cohml 已經在處理了。

開始於 2024年10月13日。

stdlib type-feature
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Feature or enhancement

Proposal:

argparse.ArgumentParser provides a get_default method (source) for retrieving an argument's default value:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("foo", default="bar")
parser.get_default("foo")  # 'bar'

However, there is currently no way to analogously retrieve the set of choices users can choose from:

parser.add_argument("foo", choices=["bar", "baz"])

So I propose adding a get_choices method, following the structure of get_default, which provides this ability:

# argparse.py

...

class _ActionsContainer(object):

    ...

    def get_choices(self, dest):
        for action in self._actions:
            if action.dest == dest:
                return action.choices

This should yield the following behavior:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("foo", choices=["bar", "baz"])
parser.add_argument("ham")
parser.get_choices("foo")  # ['bar', 'baz']
parser.get_choices("ham")  # None

Note that get_default also returns None when called on an argument where no default has been set:

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> _ = parser.add_argument("foo")
>>> print(parser.get_default("foo"))
None

Here's a demonstration of this proposal in action by extending argparse.ArgumentParser:

>>> import argparse
>>> class ExtendedArgumentParser(argparse.ArgumentParser):
...     def get_choices(self, dest):
...         for action in self._actions:
...             if action.dest == dest:
...                 return action.choices
...
>>> parser = ExtendedArgumentParser()
>>> _ = parser.add_argument("foo", choices=["bar", "baz"])
>>> _ = parser.add_argument("ham")
>>> print(parser.get_choices("foo"))
['bar', 'baz']
>>> print(parser.get_choices("ham"))
None
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 編號。

評估

這個 Issue 還沒有評估資料。

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。