Is there a way to get the argument of argparse in the order in which they were defined?
<p>I'd like to print all options of the program and they are grouped for readability. However when accessing the arguments via <code>vars(args)</code>, the order is random.</p>

<p><code>argparse</code> parses the list of arguments in <code>sys.argv[1:]</code> (<code>sys.argv[0]</code> is used as the <code>prog</code> value in <code>usage</code>).</p>

<p><code>args=parser.parser_args()</code> returns a <code>argparse.Namespace</code> object.  <code>vars(args)</code> returns a dictionary based on this object (<code>args.__dict__</code>).  Keys of a dictionary are unordered.  <code>print(args)</code> also uses this dictionary order.</p>

<p>The parser keeps a record of seen-actions for its own bookkeeping purposes.  But it is not exposed to the user, and is an unordered <code>set</code>.  I can imagine defining an custom <code>Action</code> subclass that recorded the order in which its instances were used.</p>

<p>====================</p>

<p>It is possible to retrieve arguments in the order in which they were defined when creating the parser.  That's because the <code>parser</code> has a <code>_actions</code> list of all the <code>Actions</code>.  It's not part of the public API, but a basic attribute and unlikely to every disappear.</p>

<p>To illustrate:</p>

<pre><code>In [622]: parser=argparse.ArgumentParser()
In [623]: parser.add_argument('foo')
In [624]: parser.add_argument('--bar')
In [625]: parser.add_argument('--baz')

In [626]: parser.print_help()
usage: ipython3 [-h] [--bar BAR] [--baz BAZ] foo

positional arguments:
  foo

optional arguments:
  -h, --help  show this help message and exit
  --bar BAR
  --baz BAZ
</code></pre>

<p>The usage and help listings show the arguments in the order that they are defined, except that <code>positionals</code> and <code>optionals</code> are separated.</p>

<pre><code>In [627]: args=parser.parse_args(['--bar','one','foobar'])
In [628]: args
Out[628]: Namespace(bar='one', baz=None, foo='foobar')
In [629]: vars(args)
Out[629]: {'bar': 'one', 'baz': None, 'foo': 'foobar'}

In [631]: [(action.dest, getattr(args,action.dest, '***')) for action in parser._actions]
Out[631]: [('help', '***'), ('foo', 'foobar'), ('bar', 'one'), ('baz', None)]
</code></pre>

<p>Here I iterate on the <code>_actions</code> list, get the <code>dest</code> for each <code>Action</code>, and fetch that value from the <code>args</code> namespace.  I could have fetched it from the <code>vars(args)</code> dictionary just as well.</p>

<p>I had to give <code>getattr</code> a default <code>***</code>, because the <code>help</code> action does not appear in the namespace.  I could have filtered that sort of action out of the display.</p>

python argparse