Skip to content

argparser's parse_known_args parses incorrectly if an unhandled arg is a prefix of a handled arg #127808

@nathan-az

Description

@nathan-az

Bug report

Bug description:

from argparse import ArgumentParser


args = [f'--argname_full', "foo", f'--argname', 'bar']

parser = ArgumentParser()
parser.add_argument(args[0], type=str, default=None)

parsed_args = parser.parse_known_args(args)
print(parsed_args)

# prints:
# (Namespace(argname_full='bar'), [])

I'm unsure whether this is a bug or an unfortunate side effect of having to handle shorthand argument names. Note that not only is the arg value not the expected one (foo), but the "middle" args are completely lost in the tuple.

I came across this issue by having automatically injected args suffixed with date and another with datetime, and our library only expecting the datetime one (then having it assigned the wrong value). This can be handled by renaming args or adding the arg to the parser, but it seems reasonable that this could cause relatively silent errors in other cases.

Apologies if this is documented or expected behaviour but I was unable to find other examples.

CPython versions tested on:

3.11

Operating systems tested on:

Linux, macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Doc issues

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions