A new feature request - parser add_mutually_exclusive_group - add a default value

Hi,

Please look at this Stack Overflow post:

Is there a way to add a default to parser add_mutually_exclusive_group groups - a value that will be set by default? In this case I want test-default-languages=True to be set as a default.

Thanks,
Uri.

What you are asking for is a little different from a default value. If you had a default value, then the mutually-exclusive group would complain whenever you supplied a second value, and you’d have no way to turn the default off. The SO suggestion to just use choices is a good idea: it allows for a default, it’s mutually exclusive by nature, and it’s simpler to code with.

If you want to preserve the flags as they are, one way to do that is to point them all at the same variable. You could set a default value for that variable as well. But really, this is just writing up a version of choices the hard way, and making your CLI a little bit worse in the process :wink:

parser = argparse.ArgumentParser()
group = parser.add_argument_group('language options')
language_group = group.add_mutually_exclusive_group()
language_group.add_argument(
    "--test-all-languages",
    action="store_const", const="all", dest="languages",
)
language_group.add_argument(
    "--test-default-languages",
    action="store_const", const="default", dest="languages",
)
language_group.add_argument(
    "--test-only-english",
    action="store_const", const="english", dest="languages",
)
parser.set_defaults(languages="all")  # explicitly setting a default for languages

Now I have

parser.parse_args([])  # Namespace(languages='default')
parser.parse_args(["--test-all-languages"])  # Namespace(languages='all')
2 Likes

Hi James, thanks for your answer. I understand your point, but I prefer to keep the CLI interface as it is now. I was not aware of the option of store_const. I have made the changes now, you can see my commit on Updated tests. · speedy-net/speedy-net@5c24fd3 · GitHub. It takes much less variables and less code in the model. I’m waiting for it to run on GitHub to see if it works. Thanks!

1 Like