Liam Deacon
Liam Deacon

Reputation: 894

How to include regex choices in python ArgumentParser.add_argument()?

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()

Upvotes: 4

Views: 2385

Answers (1)

The Stupid Engineer
The Stupid Engineer

Reputation: 402

I was looking at a similar issue and settled on using type for validation instead.

This allows you to use a callable to perform validation instead. So instead of using choices, use type to specify a callable that does your regex match in there instead.

If you want to retain choices in a container somewhere then you could do that too. Alternatively you could define a custom container which validates input if you must use choices only.

Upvotes: 3

Related Questions