4

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

1
  • 3
    You can't. You need to accept in any string and then do 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. Commented Feb 8, 2018 at 14:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.