[New-bugs-announce] [issue39058] argparse should preserve argument ordering in Namespace

Raymond Hettinger report at bugs.python.org
Sun Dec 15 17:16:04 EST 2019

New submission from Raymond Hettinger <raymond.hettinger at gmail.com>:

Currently, Namespace() objects sort the attributes in the __repr__.  This is annoying because argument order matters and because everywhere else in the module we preserve order (i.e. users see help in the order that arguments are added).

Note, the docs do not promise that Namespace is displayed with a sort.  This is likely just an artifact of older dictionaries having arbitrary or randomised ordering.

>>> from argparse import ArgumentParser
>>> parser = ArgumentParser()
>>> _ = parser.add_argument('source')
>>> _ = parser.add_argument('destination')

# Order matters to the user inputing the arguments 
# (source must go first and destination must go last
>>> args = parser.parse_args(['input.txt', 'output.txt'])

# Order is preserved internally
>>> vars(args)
{'source': 'input.txt', 'destination': 'output.txt'}

# Despite this, the Namespace() repr alphabetizes the output
>>> args
Namespace(destination='output.txt', source='input.txt')

# Order is preserved in help()
>>> parser.parse_args(['-h'])       
usage: [-h] source destination

positional arguments:

optional arguments:
  -h, --help   show this help message and exit

components: Library (Lib)
messages: 358455
nosy: rhettinger
priority: normal
severity: normal
status: open
title: argparse should preserve argument ordering in Namespace
type: enhancement
versions: Python 3.9

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list