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).
It occurs to me that perhaps 'store_const'
would be a more appropriate action (with all arguments pointing to the same destination).
import argparse
parser = argparse.ArgumentParser()
mutex_group = parser.add_mutually_exclusive_group()
mutex_group.add_argument("--show", action="store_const",
dest="mutex", const="show")
mutex_group.add_argument("--insert", action="store_const",
dest="mutex", const="insert")
mutex_group.add_argument('--delete', action="store_const",
dest="mutex", const="delete")
parser.set_defaults(mutex='show')
args = parser.parse_args()
print(args)
Now you can use args.mutex
to figure out which action to perform.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With