Python › Command-Line Interfaces (argparse)
How do you restrict an argument's accepted values using the 'choices' parameter?
IntermediateAnswer
Pass 'choices=[...]' to restrict the argument to a specific set of allowed values — argparse automatically validates the input against this list and prints a helpful error message listing the valid choices if the user provides something else.
parser.add_argument("--log-level", choices=["debug", "info", "warning", "error"], default="info")
args = parser.parse_args(["--log-level", "invalid"])
# error: argument --log-level: invalid choice: 'invalid' (choose from 'debug', 'info', 'warning', 'error')Real-world example Restricting a --log-level or --format flag to a specific, known set of valid string values.