How to restrict argument values using choice options in Python?

When building command-line applications in Python, you often need to restrict user input to specific valid values. Python's argparse module provides the choices parameter to limit argument values to predefined options, preventing invalid input and improving data validation.

Basic Argument Parser Without Restrictions

Let's start with a simple tennis Grand Slam title tracker that accepts any integer value ?

import argparse

def get_args():
    """Function to parse command line arguments"""
    parser = argparse.ArgumentParser(
        description='Tennis Grand Slam title tracker',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    
    # Adding argument for player titles
    parser.add_argument('titles',
                       metavar='titles',
                       type=int,
                       help='Grand Slam Titles')
    
    return parser.parse_args()

def main(titles):
    print(f"*** Player had won {titles} Grand Slam titles.")

if __name__ == '__main__':
    args = get_args()
    main(args.titles)

Running this program from the terminal shows it accepts any integer, including invalid values ?

$ python tennis.py 20
*** Player had won 20 Grand Slam titles.

$ python tennis.py -1
*** Player had won -1 Grand Slam titles.

$ python tennis.py 50
*** Player had won 50 Grand Slam titles.

The program accepts negative values and unrealistic numbers, which doesn't make sense for Grand Slam titles.

Using choices with Numeric Range

To restrict titles to realistic values (0-19), we can use the choices parameter with a range ?

import argparse

def get_args():
    """Function to parse command line arguments with restricted choices"""
    parser = argparse.ArgumentParser(
        description='Tennis Grand Slam title tracker with validation',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    
    # Adding argument with choices restriction
    parser.add_argument('titles',
                       metavar='titles',
                       type=int,
                       choices=range(0, 20),
                       help='Grand Slam Titles (0-19)')
    
    return parser.parse_args()

def main(titles):
    print(f"*** Player had won {titles} Grand Slam titles.")

if __name__ == '__main__':
    args = get_args()
    main(args.titles)

Now the program validates input and shows helpful error messages ?

$ python tennis.py 10
*** Player had won 10 Grand Slam titles.

$ python tennis.py 30
usage: tennis.py [-h] titles
tennis.py: error: argument titles: invalid choice: 30 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

$ python tennis.py -1
usage: tennis.py [-h] titles
tennis.py: error: argument titles: invalid choice: -1 (choose from 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

Using choices with String Values

You can also restrict string arguments to specific values. Here's an example with both player names and titles ?

import argparse

def get_args():
    """Function to parse arguments with string and numeric choices"""
    parser = argparse.ArgumentParser(
        description='Tennis player statistics tracker',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    
    # String choices for player names
    parser.add_argument('player',
                       metavar='player',
                       type=str,
                       choices=['federer', 'nadal', 'djokovic'],
                       help='Tennis player name')
    
    # Numeric choices for titles
    parser.add_argument('titles',
                       metavar='titles',
                       type=int,
                       choices=range(0, 25),
                       help='Grand Slam Titles (0-24)')
    
    return parser.parse_args()

def main(player, titles):
    print(f"*** {player.title()} had won {titles} Grand Slam titles.")

if __name__ == '__main__':
    args = get_args()
    main(args.player, args.titles)

The program now validates both player names and title counts ?

$ python tennis.py djokovic 23
*** Djokovic had won 23 Grand Slam titles.

$ python tennis.py murray 5
usage: tennis.py [-h] player titles
tennis.py: error: argument player: invalid choice: 'murray' (choose from 'federer', 'nadal', 'djokovic')

$ python tennis.py federer 25
usage: tennis.py [-h] player titles
tennis.py: error: argument titles: invalid choice: 25 (choose from 0, 1, 2, 3, ..., 24)

Key Benefits of Using choices

Benefits of argparse choices Parameter Input Validation Prevents invalid values automatically Clear Error Messages Shows valid options to users Help Generation Automatically updates help text Code Quality Reduces validation boilerplate code User Experience Consistent interface and feedback

Common Choice Options

Choice Type Example Use Case
List of strings ['red', 'green', 'blue'] Color selection, categories
Range of numbers range(1, 101) Percentages, scores
Set of values {10, 20, 50, 100} Fixed denominations

Conclusion

The choices parameter in argparse provides robust input validation with minimal code. It automatically generates helpful error messages and improves user experience by clearly showing valid options.

Updated on: 2026-03-25T12:04:58+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements