X Tutup
The Wayback Machine - https://web.archive.org/web/20250610154042/https://github.com/python/cpython/issues/101915
Skip to content

ArgumentParser returns wrong values when the argument name is a particular substring of the know argument  #101915

Closed as not planned
@ftesser

Description

@ftesser

Bug report

Step to reproduce the bug:

  1. create a parser with just one know argument name containing an underscore (e.g: param_a);
  2. parse a argument string that contains an unknown argument name, but that starts with the same string (e.g: param=wrong_value);
  3. the parser assign the value of this unknown argument to the know argument (e.g: param_a=wrong_value: see CASE 2. in the code below).

Moreover using both the know argument and the unknown result also in a wrong assignment (see CASE 3. below).

from argparse import ArgumentParser

main_parser = ArgumentParser()
# create a parser and add just one argument param_a
main_parser.add_argument('--param_a', type=str, required=False)
print('CASE 1. parse the string --param_a=correct_value -> OK')
options = main_parser.parse_known_args(['--param_a=correct_value'])[0]
print(options)
print('CASE 2. parse --param=wrong_value (argument name that starts with the same substring of the know argument name) -> KO')
options = main_parser.parse_known_args(['--param=wrong_value'])[0]
print(options)
print('CASE 3. join 1. and 2. -> KO')
options = main_parser.parse_known_args(['--param_a=correct_value', '--param=wrong_value'])[0]
print(options)

The output of the previous snippet of code is:

CASE 1. parse the string --param_a=correct_value -> OK
Namespace(param_a='correct_value')
CASE 2. parse --param=wrong_value (argument name that starts with the same substring of the know argument name) -> KO
Namespace(param_a='wrong_value')
CASE 3. join 1. and 2. -> KO
Namespace(param_a='wrong_value')

Your environment

  • CPython versions tested on: Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
  • Operating system and architecture: Linux Ubuntu 22.04.1 LTS - x86_64 x86_64

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-bugAn unexpected behavior, bug, or error

    Projects

    Status

    Doc issues

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      X Tutup