I have a set of arguments that can logically be separated in 2 groups:
- Actions:
A1
,A2
,A3
, etc. - Informations:
I1
,I2
,I3
, etc.
At least one of these arguments is required for the program to start, but "information" args can be used with "action" args. So
- At least one in Actions or Informations is required
- All Actions are mutually exclusive
I can't find how to do it using argparse. I know about add_mutually_exclusive_group
and its required
argument, but I can't use it on "Actions" because it's not actually required. Of course, I could add a condition after argparse to manually check my rules, but it seems like an hack. Can argparse do this?
Edit: Sorry, here are some examples.
# Should pass
--A1
--I1
--A1 --I2
--A2 --I1 --I2
# Shouldn't pass
--A1 --A2
--A1 --A2 --I1
mutually_exclusive_group
is a simplexor
logic test. You could define 2 separate groups, but it does not provide any means of working across/between the groups.I have worked on a patch to allow more complex logic and nested groups. The testing logic isn't that bad, but designing a good user interface is tricky, as is creating a meaningful
usage
line. So that enhancement probably will never see production.Testing arguments after parsing is perfectly good. It only becomes tricky if you can't distinguish between attributes with default values and ones the usage gave you - so the default default
None
is best.argparse
is primarily a parser, figuring out what the user wants. Whether they want something legit (beyond the simplest cases) is a different issue.Im i missing something or do you just want:
output:
PS. I dont really suggest this "unlimited"
-I#
approach.. but here is an example of it.There's nothing hacky about verifying arguments after they've been parsed. Just collect them all in a single set, then confirm that it is not empty and contains at most one action.