Skip to content

argparse: subparser is required even with required=False #103520

Description

@pony1k

Bug report

When adding a positional argument with nargs='+' and a subparsers after this, the subparsers is required even though it shouldn't be.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('foo', nargs='+')
subparsers = parser.add_subparsers(required=False)
sub1 = subparsers.add_parser('sub1')
sub1.add_argument('arg1')
sub2 = subparsers.add_parser('sub2')
sub2.add_argument('arg2')

parser.parse_args(['a','b','c'])
# usage: arg_parse_bug_minimal.py [-h] foo [foo ...] {sub1,sub2} ...
# arg_parse_bug_minimal.py: error: invalid choice: 'c' (choose from 'sub1', 'sub2')

In the above example, I would expect foo to consume all remaining arguments. In ArgumentParser._get_nargs_pattern I found this:

        # allow one argument followed by any number of options or arguments
        elif nargs == PARSER:
            nargs_pattern = '(-*A[-AO]*)'

The comment sais allow one argument, but the pattern actually requires one.

Your environment

  • CPython versions tested on: python 3.10
  • Operating system and architecture: OpenSuse Tumbleweed x86_64

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Fields

    No fields configured for issues without a type.

    Projects

    Status
    Doc issues

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions