Sitelet https://github.com/python/cpython/issues/99735
Skip to content

Handle no arguments when using sub-commands in argparse #99735

Description

@ppaez

Documentation

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

Activity

  1. added
    docsDocumentation in the Doc dir
    on Nov 23, 2022
  2. changed the title [-]Handle no arguments when using sub-commands[/-] [+]Handle no arguments when using sub-commands in argparse[/+] on Nov 23, 2022
  3. hpaulj commented on Dec 8, 2022

    @hpaulj

    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.

  4. ppaez commented on Jan 10, 2023

    @ppaez
    ContributorAuthor

    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.

  5. added a commit that references this issue on Feb 19, 2023
  6. added 4 commits that reference this issue on Feb 19, 2023
  7. added a commit that references this issue on Feb 20, 2023
  8. erlend-aasland commented on Feb 21, 2023

    @erlend-aasland
    Contributor

    Can we close this issue?

  9. added
    pendingThe issue will be closed if no feedback is provided
    on Feb 21, 2023
  10. hauntsaninja commented on Feb 21, 2023

    @hauntsaninja
    Contributor

    Yes we can! The backports had a hiccup, but they're all done now

  11. removed
    pendingThe issue will be closed if no feedback is provided
    on Feb 21, 2023
  12. moved this from Doc issues to Done in Argparse issueson Feb 21, 2023
  13. added a commit that references this issue on Feb 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dir

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions