How would I go about including regex expressions in the choices kwarg for Python's ArgumentParser.add_argument() method?
For example, lets say I wish to create my own custom mount program:
# file: my_mount.py
from argparse import ArgumentParser
# some simple choices to help illustrate
option_choices = {'ro|rw', 'user=.*', 'do=[a-z]{1,10}', 'allow_other'}
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('-s', '--share', dest='share')
parser.add_argument('-m', '--mount-point', dest='mnt_pt')
parser.add_argument('-o', dest='options', action='append',
choices=option_choices,
help='Options for mounting - see choices '
'expressions set for valid options')
args, _ = parser.parse_known_args()
# do some fancy stuff to do with mounting filesystems...
With the idea that I could filter out valid options based on a simple set of regular expressions, especially as hand-coding in all possibilities is a chore e.g. {'do=nothing', 'do=something', 'do=anything'...}, but also handily retain the choices list when invoking python my_mount.py -h. My initial thoughts were to have a custom action, but this doesn't seem compatible with when specifying choices in add_argument()
assert any(re.match(expr, opt) is not None for expr in option_choices for opt in args.options)or similar. Just add'accepts: {}'.format(option_choices)to the help argument of--options. You don't need to rely on ArgParses automatic checks.