New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
argparse should preserve argument ordering in Namespace #83239
Comments
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.
# 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: |
Hmm, I was going to suggest switching to types.SimpleNamespace, but In writing up that issue, I considered that a sorted repr can be Anyway, I agree with your conclusion. :) |
FWIW, I've also opened issue bpo-39076 about subclassing types.SimpleNamespace. |
This patch changes the super class, _AttributeHolder. ArgumentParser and Actions also inherit from this, though they have their own _get_kwargs methods, and so aren't affected by the sort and its removal. I just had occasion on stackoverflow to discuss the order in which attributes are added. A poster wanted to preserve the sys.argv order. Most attributes are added as defaults at the start of parsing - via a loop through parser._actions. Predefining the namespace, SUPPRESS defaults, parser.set_defaults may alter this default order. Anyways removing the sort makes sense, and the proposed change phrase "in the order attributes were added" is sufficiently general. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: