Allowing specific values for an Argparse argument


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:

                    help='Special testing value')

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

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

Asked By: Moshe



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

                    choices=['a', 'b', 'c'],
                    help='Special testing value')

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

See the docs for more details.

Answered By: Moshe
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.