Back to results for “Set”
Python › Command-Line Interfaces (argparse)

How do you implement mutually exclusive arguments, where the user must choose EXACTLY ONE of a set of flags?

Advanced

Answer

add_mutually_exclusive_group() creates a group where argparse automatically raises an error if the user provides MORE THAN ONE of the group's arguments together; pass 'required=True' to the group to also enforce that AT LEAST ONE must be provided.
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--verbose", action="store_true")
group.add_argument("--quiet", action="store_true")
# python script.py --verbose --quiet
# error: argument --quiet: not allowed with argument --verbose
Real-world example Enforcing that a CLI tool's output mode is EXACTLY one of --verbose, --quiet, or --normal, never a combination.

Common follow-ups: Can a mutually exclusive group contain MORE than two arguments?