Python argparse Color and Suggestions

Python 3.14 improves argparse command-line interfaces with colored help output and optional suggestions for mistyped choices and subcommands.

Enable Error Suggestions

Example:

import argparse

parser = argparse.ArgumentParser(
    suggest_on_error=True
)

parser.add_argument(
    "--action",
    choices=["debug", "dryrun"]
)

parser.parse_args()

Save the example as cli.py, then run:

Example:

python cli.py --action debugg

The error reports the invalid choice and suggests debug. Use python cli.py --help to view help.

Color Help Output

Python 3.14 can print argparse help using ANSI colors when the terminal supports them.

Example:

import argparse

parser = argparse.ArgumentParser(
    description="Process files",
    color=True
)

parser.add_argument("filename")

parser.parse_args()

Disable Color

Example:

parser = argparse.ArgumentParser(
    color=False
)

Disabling color is useful for plain-text logs, snapshot tests, or environments where escape sequences should not appear.

Color Depends on the Environment

When color is enabled, the final behavior can depend on terminal support and environment variables. Applications that redirect output to files should test how their deployment handles colored error and help messages.

Use Suggestions with String Choices

Choice suggestions require string choices; they do not correct arbitrary unknown option names. Add the following argument before parse_args() in the same script.

Example:

parser.add_argument(
    "--format",
    choices=["json", "yaml", "text"]
)
Option Purpose
suggest_on_error Suggest close valid choices after a typo
color Control ANSI-colored help output

Suggestions improve usability but do not change argument validation. Invalid input is still rejected.

Conclusion

Python 3.14 makes argparse-generated CLIs friendlier with typo suggestions and color. These options can improve developer tools without changing the core parsing model.



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram