af3ld af3ld - 2 months ago 8
Python Question

Accessing the choices passed to argument in argparser?

Is it possible to access the tuple of choices passed to an argument? If so, how do I go about it

for example if I have

parser = argparse.ArgumentParser(description='choose location')
parser.add_argument(
"--location",
choices=('here', 'there', 'anywhere')
)
args = parser.parse_args()


can I access the tuple
('here', 'there', 'anywhere')
?

Answer

It turns out that parser.add_argument actually returns the associated Action. You can pick the choices off of that:

>>> import argparse
>>> parser = argparse.ArgumentParser(description='choose location')
>>> action = parser.add_argument(
...     "--location",
...     choices=('here', 'there', 'anywhere')
... )
>>> action.choices
('here', 'there', 'anywhere')

Note that (AFAIK) this isn't documented anywhere and may be considered an "implementation detail" and therefore subject to change without notice, etc. etc.

There also isn't any publicly accessible way to get at the actions stored on an ArgumentParser after they've been added. I believe that they are available as parser._actions if you're willing to go mucking about with implementation details (and assume any risks involved with that)...


Your best bet is to probably create a constant for the location choices and then use that in your code:

LOCATION_CHOICES = ('here', 'there', 'anywhere')

parser = argparse.ArgumentParser(description='choose location')
parser.add_argument(
    "--location",
    choices=LOCATION_CHOICES
)
args = parser.parse_args()

# Use LOCATION_CHOICES down here...