Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forbid two conflicting options

Is there a way to specify to Python's ArgumentParser that two optional flags are conflicting?

arg_parser.add_argument('-c', '--clean', action='store_true')
arg_parser.add_argument('-d', '--dirty', action='store_true')

I want the user to be able to specify either none of those, or only one.

Is it achievable without further conditions?

like image 337
Gilad Naaman Avatar asked Apr 30 '16 08:04

Gilad Naaman


1 Answers

How about adding a mutually exclusive group:

group = arg_parser.add_mutually_exclusive_group()
group.add_argument('-c', '--clean', action='store_true')
group.add_argument('-d', '--dirty', action='store_true')

with this I get the following behaviour:

>>> arg_parser.parse_args(['--clean']) 
Namespace(clean=True, dirty=False)
>>> arg_parser.parse_args(['--dirty']) 
Namespace(clean=False, dirty=True)
>>> arg_parser.parse_args(['--dirty','--clean']) 
usage: PROG [-h] [-c | -d] PROG: error: argument -c/--clean: not allowed with argument -d/--dirty
like image 172
sietschie Avatar answered Nov 11 '22 18:11

sietschie