Skip to content

/Lib/argparse.py incorrect argument parser #105804

@Tony10401

Description

@Tony10401

Bug report

The parser allows multiple options for an optional argument in a subcommand, if you add 2 for example: -n | --name, and then you call it with a single "-" -name "test_name" it will not throw an error nor parse the value correctly, but it will parse it as if you passed -n with 'ame' value (see code example below).

Your environment

$ python --version
Python 3.9.6


$ sysname
x86-64_linux_4.12_ImageSLES12SP5

Code example:

I copied this code from argparse documentation and just added -n|--name to show the behavior

import argparse


def foo(args, leftovers):
    print(args, leftovers)


# create the top-level parser
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(required=True)

# create the parser for the "foo" command
parser_foo = subparsers.add_parser('foo')
parser_foo.add_argument('-n', '--name', type=str, default=1)
parser_foo.add_argument('y', type=float)
parser_foo.set_defaults(func=foo)


# parse the args and call whatever function was selected
args, leftovers = parser.parse_known_args()
args.func(args, leftovers)

And then if we run this code we will see that it is not parsing the arguments correctly:

$ python test.py foo 2.0 -name 1
Namespace(name='ame', y=2.0, func=<function foo at 0x2aaaac0b2c10>) ['1']

Metadata

Metadata

Assignees

No one assigned

    Labels

    pendingThe issue will be closed if no feedback is providedtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions