Set the default value to false if a different mutually exclusive argument is true

I understand that this is very similar to Setting the default option in Python from two mutually exclusive options using the argparse module , although from a different perspective (and the answers given do not seem to help).

Code block (the 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 , I want to use --show by default (hence default=True ), but if --insert used, then opts.show is still set to true (due to default values) even though they are part of a mutually exclusive block.

The current code checks that none of the other options were set when checking if opt.show True, opt.show .:

 if opts.show and not opts.insert: do_something() elif opts.insert: do_something_else() 

but it doesn't scale (what happens when you add --delete to a mutually exclusive group, etc.), so I'm looking for the best way to make every other variable make opts.show false, while still having it by default.

Reading argparse docs, I think the user action will be a way, but cannot see how to access other members of a mutually exclusive group from the inside (a theory in which I could iterate over them and flip by default if any of the others were set). Another option is to cancel the if conditions, but this seems unclean (if the default changes and the order of the if statements changes).

+8
python arguments command-line-arguments argparse
source share
1 answer

It seems 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 take.

+19
source share

All Articles