I'm looking for a Pythonic way to validate arguments when their validation logically depends on the value(s) parsed from other argument(s).
Here's a simple example:
parser.add_argument(
'--animal',
choices=['raccoon', 'giraffe', 'snake'],
default='raccoon',
)
parser.add_argument(
'--with-shoes',
action='store_true',
)
In this case, parsing this command should cause an error:
my_script.py --animal snake --with-shoes
Adding a mutually exclusive group doesn't seem to help here, as the other combos are OK:
my_script.py --animal raccoon --with-shoes
my_script.py --animal raccoon
my_script.py --animal snake
my_script.py --animal giraffe --with-shoes
my_script.py --animal giraffe
The validation error should ideally not be tied to --animal
argument nor to --with-shoes
argument, since the interface can not tell you which value needs to change here. Each value is valid, yet they can't be used in combination.
We can do this with post-processing the args
namespace, but I'm looking for a solution which would cause the parser.parse_args()
call to fail, i.e. we actually fail during argument parsing, not afterwards.