[Python] Exclusive group of arguments with optional values

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

  1. Stack

    Stack Membro Participativo

    The following code

    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument('--foo', nargs='?')
    parsed_args = parser.parse_args()


    creates an optional argument with an optional value. It means that --foo 123 stores 123, --foo stores None, leaving the argument altogether stores None too.

    I now create a mutually exclusive group of two such arguments:

    from argparse import ArgumentParser

    parser = ArgumentParser()
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--foo', nargs='?')
    group.add_argument('--bar', nargs='?')
    parsed_args = parser.parse_args()


    As expected, --foo 123 --bar 456 results in error argument --bar: not allowed with argument --foo. But running --foo --bar finishes without errors. Tested with Python 3.13. Is it a bug in Python or just my misunderstanding of the concept?

    Continue reading...

Compartilhe esta Página