I realise this is a lot like Setting default option in Python of two mutually exclusive options using the argparse module although from a different perspective (and the answers given there don't seem to help).
Code block (parser is an instance of argparse.ArgumentParser):
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument("--show", action="store_true",
dest="show", default=True)
mutex_group.add_argument("--insert", action="store_true",
dest="insert")
opts = parser.parse_args()
If neither --show
or --insert
are specified I want to default to --show
(hence default=True
) but if --insert
is used then opts.show
is still set true (because of the default), despite being part of a mutually exclusive block.
The current code checks that none of the other options have been set when testing whether opt.show
is True, i.e.:
if opts.show and not opts.insert:
do_something()
elif opts.insert:
do_something_else()
but this doesn't scale (what happens when you add --delete
to the mutually exclusive group, etc.) so I'm looking for a better way of causing every other variable to make opts.show
false while still having it as the default.
Reading the argparse docs, I think a custom action would be the way to go but can't see how to access the other members of the mutually exclusive group from within that (the theory being I could iterate over them, and flip the default if any of the rest were set). The other option would be to reverse the if conditions, but that seems unclean (if the default changes, the order of the if statements would have to change also).