liveBook · Manning

Choices

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

An argparse choices option restricts an argument's value to a specified collection of allowed values.

Use argparse's choices option to restrict an argument to a defined collection of allowed values. argparse validates the input before program processing continues. section 8.3.1 section 8.6

Restricting a vowel argument

A vowel-substitution program can accept only lowercase vowels by declaring choices=list('aeiou'). This produces the same list as ['a', 'e', 'i', 'o', 'u']; an assertion can verify the equivalence. section 8.3.1

parser.add_argument('-v',
                   '--vowel',
                   help='The vowel to substitute'',
                   metavar='str',
                   type=str,
                   default='a',
                   choices=list('aeiou'))

The argument declaration shows choices alongside type, default, and metavar settings. section 8.3.1

The same validation approach handles Tic-Tac-Toe options such as player and cell, alongside checks that require both options or neither. section 21.2.1

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines choices with lists or list(str), but stops short of implementation internals.
Examples
Demonstrates allowed vowels and Tic-Tac-Toe player and cell arguments.
What it assumes
Assumes basic Python strings and lists while demonstrating argparse argument definition from validation needs.
What you can do after
Apply it via argparse to reject command-line values outside a defined collection.
How it connects
Connects argparse validation with command-line arguments, defaults, type conversion, and regular expressions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.