Skip to main content

How to Limit a Command-Line Option to Certain Values in Python with argparse choices

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

Some options only make sense with a few values: a size that is small, medium or large, or a mode that is fast or safe. argparse can check that for you with choices, so your code never sees anything else. This guide shows it on Python 3.15.2.

Syntax​

Syntax
parser.add_argument(<option>, choices=<allowed values>, default=<value>)
PartWhat it means
<option>The option's name, such as "--size"
choices=<allowed values>A list or tuple of the only values the option accepts
default=<value>Optional. The value used when the option is left out. Make it one of the choices

Python's argparse documentation says that when the command line is parsed, "argument values will be checked, and an error message will be displayed if the argument was not one of the acceptable values". It accepts "Any sequence", so a list and a tuple both work.

The Example​

A tiny coffee-order script takes a --size option that can only be small, medium or large, with medium when it's left out.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

coffee.py
import argparse

parser = argparse.ArgumentParser(prog="coffee")
parser.add_argument("--size", choices=["small", "medium", "large"], default="medium")
args = parser.parse_args()

print(f"Size: {args.size}")

The coffee.py script in a macOS-style code window: an ArgumentParser named coffee with a --size option whose choices are small, medium and large and whose default is medium, then a print of the chosen size.

prog="coffee" is the name argparse shows in its messages. args.size holds the value that was given, or the default.

Step 2: Run It with an Allowed Value and Without One​

Terminal
uv run python coffee.py --size large
Output
Using CPython 3.15.2 interpreter at: /Library/Frameworks/Python.framework/Versions/3.15/bin/python3.15
Creating virtual environment at: .venv
Built python-basics @ file:///Users/you/source/python-basics
Installed 1 package in 2ms
Size: large
Terminal
uv run python coffee.py
Output
Size: medium

The terminal after the two runs: Size: large for --size large, then Size: medium when the option is left out.

The first run was the first in this project, so uv also printed what it set up before the script's own line. --size large is in the list, so the script got it. Without --size, it got the default, medium. The commands work unchanged in PowerShell.

Step 3: Give It a Value That Isn't Allowed​

Terminal
uv run python coffee.py --size huge
Output
usage: coffee [-h] [--size {small,medium,large}]
coffee: error: argument --size: invalid choice: 'huge' (choose from 'small', 'medium', 'large')

The terminal after uv run python coffee.py --size huge: the usage line, then coffee: error: argument --size: invalid choice: huge, choose from small, medium, large.

argparse stopped before the print() line ran: the usage line shows the allowed values in braces, and the error names the value it refused and the ones it accepts. The script ended with exit status 2, which echo $? printed as 2 right after this run.

Python 3.15 also guesses what you meant. A typo gave:

Terminal
uv run python coffee.py --size larg
Output
usage: coffee [-h] [--size {small,medium,large}]
coffee: error: argument --size: invalid choice: 'larg', maybe you meant 'large'? (choose from 'small', 'medium', 'large')

The documentation lists this as the suggest_on_error setting of ArgumentParser, added in Python 3.14, and "Changed in version 3.15: suggest_on_error default changed to True."

Step 4: Read the Help​

Terminal
uv run python coffee.py --help
Output
usage: coffee [-h] [--size {small,medium,large}]

options:
-h, --help show this help message and exit
--size {small,medium,large}

The terminal after uv run python coffee.py --help: the usage line and the options list, where --size shows its choices small, medium and large in braces.

The help shows the choices with no extra work. Add a help= text to the option to explain them.

Common Mistakes​

MistakeWhat happensDo this instead
A default that isn't one of the choices, such as default="tiny"argparse doesn't check the default: the script ran and printed Size: tinyPick the default from the choices
type=int with text choices, choices=["1", "2"]--level 1 failed with the puzzling invalid choice: '1' (choose from '1', '2'): the value is checked after type turns it into the number 1, which isn't the text "1"Use choices of the same type: choices=[1, 2] with type=int

FAQ​

Can I use a tuple instead of a list?​

Yes. The documentation says "Any sequence can be passed as the choices value, so list objects, tuple objects, and custom sequences are all supported."

Does it work for positional arguments too?​

Yes. The documentation's own example is a positional move argument with choices=['rock', 'paper', 'scissors'].

Can I turn the "maybe you meant" suggestion off?​

Yes: with argparse.ArgumentParser(prog="coffee", suggest_on_error=False), --size larg gave the error without the maybe you meant 'large'? part.

Conclusion​

choices=["small", "medium", "large"] let --size large through, used medium when the option was left out, and stopped --size huge with an error that lists the allowed values and exit status 2. The help showed the choices on its own.

Additional Resources​