argparse
python
command-line-arguments
argument-parsing
programming

Allowing specific values for an Argparse argument

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

If a command-line option should accept only a known set of values, argparse already has the feature you want. The choices parameter lets the parser validate input early and produce a clear error message instead of forcing you to write manual if checks after parsing.

The Basic choices Pattern

The simplest form is a list of allowed values.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument(
5    "--mode",
6    choices=["dev", "test", "prod"],
7    required=True,
8)
9
10args = parser.parse_args()
11print(args.mode)

If the user runs --mode staging, argparse prints an error and the help text automatically. That is usually better than accepting invalid input and failing later.

choices Works with Types Too

Type conversion happens before choice validation. That makes choices useful for numbers as well as strings.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument(
5    "--retries",
6    type=int,
7    choices=[1, 3, 5],
8    default=3,
9)
10
11args = parser.parse_args()
12print(args.retries)

If the user provides --retries 2, the parser rejects it because 2 is not one of the allowed integers.

Use Helpful Text Around Restricted Values

Because choices appears in the generated help output, it improves discoverability with almost no extra work.

python
1import argparse
2
3parser = argparse.ArgumentParser(description="Run the deployment tool.")
4parser.add_argument(
5    "--region",
6    choices=["us", "eu", "apac"],
7    help="Target deployment region",
8)
9
10parser.print_help()

A good description and help string make the allowed set much easier for users to understand.

When You Need More Than choices

choices is perfect for a fixed allowed set. If the valid values depend on business rules, files on disk, or database content, use a custom validation function after parsing or a custom type function that raises argparse.ArgumentTypeError.

python
1import argparse
2
3
4def positive_even(value):
5    number = int(value)
6    if number <= 0 or number % 2 != 0:
7        raise argparse.ArgumentTypeError("value must be a positive even integer")
8    return number
9
10
11parser = argparse.ArgumentParser()
12parser.add_argument("--batch-size", type=positive_even, required=True)
13args = parser.parse_args()
14print(args.batch_size)

That pattern is better when the rule is more expressive than a short static list.

Case Sensitivity and User Experience

choices is case-sensitive unless you normalize input yourself. If you want case-insensitive behavior, convert the value in a custom type or action before choice validation.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument(
5    "--format",
6    type=str.lower,
7    choices=["json", "yaml"],
8)

Now JSON, Json, and json all resolve to the same accepted value.

Positional Arguments Can Use choices Too

This feature is not limited to optional flags. It works just as well for positional arguments, which is useful for commands that should accept a fixed mode or action name.

python
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument("action", choices=["start", "stop", "status"])
5args = parser.parse_args()
6print(args.action)

That keeps the CLI contract explicit and lets argparse generate the right usage string automatically.

Common Pitfalls

  • Reimplementing manual validation after parsing is usually unnecessary for fixed value sets.
  • Forgetting that type conversion happens before choices can make errors look surprising.
  • Assuming choices is case-insensitive leads to rejected input unless you normalize it.
  • Using choices for highly dynamic validation can make the CLI design awkward.
  • Hiding valid options from the help text makes the parser feel harder to use than it really is.

Summary

  • Use choices to restrict an argparse option to a known set of values.
  • The parser validates input immediately and shows a helpful error on invalid values.
  • 'choices works with converted types such as integers, not just strings.'
  • Use custom validators when the rule is more complex than a fixed list.
  • Normalize case explicitly if you want case-insensitive command-line input.

Course illustration
Course illustration

All Rights Reserved.