python - Is there a way to get the argument of argparse in the order in which they were defined? -


i'd print options of program , grouped readability. when accessing arguments via vars(args), order random.

argparse parses list of arguments in sys.argv[1:] (sys.argv[0] used prog value in usage).

args=parser.parse_args() returns argparse.namespace object. vars(args) returns dictionary based on object (args.__dict__). keys of dictionary unordered. print(args) uses dictionary order.

the parser keeps record of seen-actions own bookkeeping purposes. not exposed user, , unordered set. can imagine defining custom action subclass recorded order in instances used.


it possible retrieve arguments in order in defined when creating parser. that's because parser has _actions list of actions. it's not part of public api, basic attribute , unlikely every disappear.

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 message , exit   --bar bar   --baz baz 

the usage , listings show arguments in order defined, except positionals , 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, '***')) action in parser._actions] out[631]: [('help', '***'), ('foo', 'foobar'), ('bar', 'one'), ('baz', none)] 

here iterate on _actions list, dest each action, , fetch value args namespace. have fetched vars(args) dictionary well.

i had give getattr default ***, because help action not appear in namespace. have filtered sort of action out of display.


Comments