Allowing specific values for an Argparse argument

PythonArgparse

Python Problem Overview


Is it possible to require that an argparse argument be one of a few preset values?

My current approach would be to examine the argument manually and if it's not one of the allowed values call print_help() and exit.

Here's the current implementation:

...
parser.add_argument('--val',
                    help='Special testing value')

args = parser.parse_args(sys.argv[1:])
if args.val not in ['a', 'b', 'c']:
    parser.print_help()
    sys.exit(1)

It's not that this is particularly difficult, but rather that it appears to be messy.

Python Solutions


Solution 1 - Python

An argparse argument can be limited to specific values with the choices parameter:

...
parser.add_argument('--val',
                    choices=['a', 'b', 'c'],
                    help='Special testing value')

args = parser.parse_args(sys.argv[1:])

See the docs for more details.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMosheView Question on Stackoverflow
Solution 1 - PythonMosheView Answer on Stackoverflow