[Python] Why argparse treats unknown arg as a known arg in case unknown arg name is part of a...

Discussão em 'Python' iniciado por Stack, Novembro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a Python project that uses argparse. I noticed an unwanted behavior of argparse when parsing some unknown arguments.

    I use both known and unknown arguments. I have a parameter --list-installed. Now, if I pass the --list parameter, it is treated as known, while it should be unknown.

    See this code:

    import argparse

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument("--list-installed", action="store_true")

    def parse_options(options: list[str]) -> None:
    args, unknown_args = parser.parse_known_args(options)
    print("input options:", options)
    print(" args:", args)
    print(" unknown_args:", unknown_args)
    print()

    parse_options(["kcalc"])
    """
    input options: ['kcalc']
    args: Namespace(list_installed=False)
    unknown_args: ['kcalc']
    """

    parse_options(["kcalc", "--list-installed"])
    """
    input options: ['kcalc', '--list-installed']
    args: Namespace(list_installed=True)
    unknown_args: ['kcalc']
    """

    parse_options(["kcalc", "--list2"]) # <- The "--list2" is treated as unknown arg (this is expected).
    """
    input options: ['kcalc', '--list2']
    args: Namespace(list_installed=False)
    unknown_args: ['kcalc', '--list2']
    """

    parse_options(["kcalc", "--list"]) # <- Why "--list" is treated as "--list-installed"? It must be in unknown_args.
    """
    input options: ['kcalc', '--list']
    args: Namespace(list_installed=True)
    unknown_args: ['kcalc']
    """

    parse_options(["kcalc", "--list-"]) # <- Seems, this too. Why argparse parses the beginning of the arg name instead of exact match?
    """
    input options: ['kcalc', '--list-']
    args: Namespace(list_installed=True)
    unknown_args: ['kcalc']
    """

    parse_options(["kcalc", "--list-i"]) # <- Yeah, this too.
    """
    input options: ['kcalc', '--list-i']
    args: Namespace(list_installed=True)
    unknown_args: ['kcalc']
    """


    As can be seen, when my argument name begins with the name of a known argument, it suddenly becomes known.

    Is there a way to prevent this behavior?

    Tested with Python 3.13.7 on Arch Linux.

    Continue reading...

Compartilhe esta Página