I am trying to configure argparse so that only the following argument combinations are valid:
--flagA --argument1 val1 --argument2 val2 --argument3 val3
--flagB --argument1 val1
So far, I have written the following piece of code however it doesn't do the trick as both --argument2 and --argument3 are optional:
required_args = arg_parser.add_argument_group()
required_args.add_argument('--argument1', required=True)
# Optional arguments
optional_args = arg_parser.add_argument_group()
optional_args.add_argument('--argument2', required=False)
optional_args.add_argument('--argument3', required=False)
# Flags
flag_group = arg_parser.add_mutually_exclusive_group(required=True)
flag_group.add_argument('--flagA', dest='flag', action='store_const', const="flagA")
flag_group.add_argument('--flagB', dest='flag', action='store_const', const="flagB")
args = vars(arg_parser.parse_args())
With this setting, --flagA --argument1 val1 is also but it shouldn't be.
I know that I can process the Namespace generated after calling .parse_args() and check whether --argument2 and --argument3 are provided when --flagA is passed however I am looking for a more natural way to achieve this.
Essentially, the definition should look like the one below:
[-h] --argument1 ARGUMENT1 (--flagA --argument2 ARGUMENT2 --argument3 ARGUMENT3 | --flagB)
argparse. It's a simplexor. If that doesn't work for you, use the post-parsing testing. There's nothing 'natural' about trying to useargparsefor everything.