python / python/cpython

Add ability to retrieve choices from `argparse.ArgumentParser`

Aperta
#125,363 17 commenti 0 reazioni 1 assegnatario Vedi su GitHub

@cohml ci sta già lavorando.

Dal 13/10/2024.

stdlib type-feature
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.