GeezerVison is showing github.com — Handle no arguments when using sub-commands in argparse · Issue #99735 · python/cpython
Handle no arguments when using sub-commands in argparse #99735DescriptionDocumentation
The example that shows the use of sub-commands and set_defaults to dispatch a function for each sub-command, fails when there are no command line arguments:
AttributeError: 'Namespace' object has no attribute 'func'
A pull request is provided that adds one line to handle that case and an explanation in the documentation.
Linked PRs
Activitychanged the title [-]Handle no arguments when using sub-commands[/-] [+]Handle no arguments when using sub-commands in argparse[/+] on Nov 23, 2022hpaulj commented on Dec 8, 2022 Originally subparsers were required, so this issue did not come up. Because of a patching oversight, they are now optional, and we had to add the required parameter. I think this example would be better handled with a
subparsers = parser.add_subparsers(required=True)
Then we wouldn't have to define a func for the no-subparser case. Your patch works, but I think it adds too much to the text and example, detracting from the essence of what set_defaults adds.
Whether we use set_defaults or not, the Namespace will have different attributes depending on what subparser (or none) the user invokes. The post parsing code has to handle that issue in one way or the other. ppaez commented on Jan 10, 2023 ContributorAuthor More actions I hadn't used the required=True parameter before. It is mentioned in the reference, but I didn't consider it. I also was not aware of those changes (bpo-9253 and bpo-26510), thanks for explaining them.
PR #100927 has been created with only that change. erlend-aasland commented on Feb 21, 2023 hauntsaninja commented on Feb 21, 2023 Yes we can! The backports had a hiccup, but they're all done now Reacted by Erlend E. Aasland
MetadataMetadataStatusShow more project fields
DevelopmentNo branches or pull requestsIssue actions
|