Enable CLI Typo Suggestions with suggest_on_error in Python 3.14

Enable CLI Typo Suggestions with suggest_on_error in Python 3.14

Command line tools are one of the ways for users to interact with Python programs. Minor typing errors, like incorrect option values or mistyped sub-commands, can lead to confusing error messages and a poor user experience.

Since Python 3.14, the argparse module provides an optional suggest_on_error parameter for ArgumentParser. When this parameter is enabled, the parser can offer suggestions for argument choices and sub-parser names if the user makes a typo. This enhancement improves error messages by pointing out likely intended inputs instead of only reporting that something went wrong.

To activate this behavior, pass suggest_on_error=True when creating the ArgumentParser instance:

import argparse

parser = argparse.ArgumentParser(suggest_on_error=True)

parser.add_argument('--format', choices=['json', 'yaml', 'xml'])

subparsers = parser.add_subparsers(dest='cmd', required=True)
subparsers.add_parser('start')
subparsers.add_parser('stop')

parser.parse_args()

If a user provides an invalid value for an argument with predefined choices, argparse will now offer a suggestion when possible.

python main.py --format yml start

Without suggestions enabled, the error looks like this:

usage: main.py [-h] [--format {json,yaml,xml}] {start,stop} ...
main.py: error: argument --format: invalid choice: 'yml' (choose from json, yaml, xml)

With suggest_on_error=True, the parser adds a helpful hint:

usage: main.py [-h] [--format {json,yaml,xml}] {start,stop} ...
main.py: error: argument --format: invalid choice: 'yml', maybe you meant 'yaml'? (choose from json, yaml, xml)

The same improvement applies to sub-commands defined via sub-parsers.

python main.py --format yaml stat

Standard error output:

usage: main.py [-h] [--format {json,yaml,xml}] {start,stop} ...
main.py: error: argument cmd: invalid choice: 'stat' (choose from start, stop)

With suggestions enabled:

usage: main.py [-h] [--format {json,yaml,xml}] {start,stop} ...
main.py: error: argument cmd: invalid choice: 'stat', maybe you meant 'start'? (choose from start, stop)

Leave a Comment

Cancel reply

Your email address will not be published.