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.
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.
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.
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.
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.
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.
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
typeconversion happens beforechoicescan make errors look surprising. - Assuming
choicesis case-insensitive leads to rejected input unless you normalize it. - Using
choicesfor 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
choicesto restrict anargparseoption to a known set of values. - The parser validates input immediately and shows a helpful error on invalid values.
- '
choicesworks 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.

