Is there a way to get the argparse arguments in the order they were defined?

I would like to print all the parameters of the program and they are grouped for readability. However, when accessing the arguments through the vars(args)

order, it is random.

0


source to share


1 answer


argparse

parses the argument list in sys.argv[1:]

( sys.argv[0]

used as a value prog

in usage

).

args=parser.parse_args()

returns an object argparse.Namespace

. vars(args)

returns a dictionary based on this object ( args.__dict__

). Dictionary keys are out of order. print(args)

also uses this dictionary order.

The analyzer keeps a record of noticed actions for its own accounts. But it is not presented to the user and is out of order set

. I can imagine how to define a custom subclass Action

that recorded the order in which its instances were used.


You can get the arguments in the order in which they were defined when the parser was created. This is because it parser

has a _actions

list of everyone Actions

. This is not part of the public API, but a basic attribute and not likely to go away.

To illustrate:



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

      

The lists and the use of an imaging arguments in the order in which they are defined, except that positionals

and optionals

separated.

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)]

      

Here I iterate over the list _actions

, get dest

for each Action

and fetch that value from the namespace args

. I could get it from a dictionary as well vars(args)

.

I had to specify getattr

the default ***

because the action is help

not visible in the namespace. I could filter this action from the display.

+2


source







All Articles