pythonargparse

Exclusive group of arguments with optional values


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?


Solution

  • This seems to be a long known issue, which has been already recently (Python 3.13.1) fixed:

    Arguments with the value identical to the default value (e.g. booleans, small integers, empty or 1-character strings) are no longer considered "not present".