python / python/cpython

Add ability to retrieve choices from `argparse.ArgumentParser`

Aberta
#125,363 17 comentários 0 reações 1 responsável Ver no GitHub

@cohml já está trabalhando nisso.

Desde 13/10/2024.

stdlib type-feature
Linguagem predominante
Python
Estrelas
77.2k
Forks
36k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

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

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Avaliação

Esta issue ainda não foi avaliada.

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.