Being able to validate the list items using choices=servers
below is nice.
servers = [ "ApaServer", "BananServer", "GulServer", "SolServer", "RymdServer", "SkeppServer", "HavsServer", "SovServer" ]
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--only', nargs='*', choices=servers, help='Space separated list of case sensitive server names to process')
Is it possible to force an item in the list to be unique, so that no duplicates are allowed?
Here's an excerpt from some code that I use for a similar purpose:
This is similar in spirit to jcollado's reply, with a modest improvement: multiple options can be specified, with comma separated values, and they are deduped (via set) across all options.
For example:
Note that there are two -g args. BRCA2 is specified twice in the first, but appears only once. BRCA1 is specified in the first and second -g opts, but also appears only once.
Modifying Michel's answer:
Much shorter.
The way to properly discard duplicates using
argparse
would be to create your ownargparse.Action
class that takes care of usingset
as suggestted by other answers:Example output:
I don't think, that you can enforce this with
argparse
, but I also don't see any reason to do so. Just document inhelp
that duplicates are ignored. If the user passes duplicate arguments to--only
, just let her do so, and ignore the duplicate argument when processing the option arguments (e.g. by turing the list into aset()
before processing).