Accessing the choices passed to argument in argparser?
<p>Is it possible to access the tuple of choices passed to an argument? If so, how do I go about it</p>

<p>for example if I have </p>

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

<p>can I access the tuple <code>('here', 'there', 'anywhere')</code>?</p>

<p>It turns out that <code>parser.add_argument</code> actually returns the associated <code>Action</code>.  You can pick the choices off of that:</p>

<pre><code>&gt;&gt;&gt; import argparse
&gt;&gt;&gt; parser = argparse.ArgumentParser(description='choose location')
&gt;&gt;&gt; action = parser.add_argument(
...     "--location",
...     choices=('here', 'there', 'anywhere')
... )
&gt;&gt;&gt; action.choices
('here', 'there', 'anywhere')
</code></pre>

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

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

<hr>

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

<pre><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...
</code></pre>

python argparse