I have a program, for which a argument can take values from a defined list. Every value can only be passed once. At least one value must be chosen. If no values are chosen, the default is that all values were chosen. The following code exhibits the desired behavior.
import argparse
############################# Argument parsing
all_targets = ["bar", "baz", "buzz"]
p = argparse.ArgumentParser()
p.add_argument(
"--targets", default=all_targets, choices=all_targets, nargs="+",
)
args = p.parse_args()
targets = args.targets
if len(targets) > len(set(targets)):
raise ValueError("You may only foo every target once!")
############################## Actual program
for target in targets:
print(f"You just foo'ed the {target}!")
However, now I am dealing with argument validation after parsing, which seems like a anti-pattern, since argparse typically do type validation etc in the parsing step.
Can I get the same behavior as above from the ArgumentParser
instead of making post-checks on the arguments?