Make two CLI modes mutually exclusive
Two switches that select incompatible behavior should not be accepted together. add_mutually_exclusive_group(required=True) creates a group that requires one member and prohibits more than one member in the same parse. In this example, --summary and --detail store different constants in the shared mode destination. Parsing each synthetic invocation produces a clear, canonical mode string, and the assertions check the expected result before it is printed.
The group enforces argument presence and mutual exclusion; it does not implement either reporting mode. It also does not establish that every possible future option is compatible with both modes. Add follow-up validation where options interact in more detailed ways. For an interface where the mode has subcommands with their own positional arguments, argparse subparsers may express the command shape more naturally than flags. This example intentionally avoids invalid invocations because argparse normally writes an error and exits for them, which is not useful as deterministic successful-program output.
Mutually exclusive groups are part of standard-library argparse, available since Python 3.2. The official documentation describes their one-member constraint and required=True behavior.
AI assistance disclosure: this article was drafted with AI assistance and should be checked in its target CLI context.
import argparse
parser = argparse.ArgumentParser(prog="view-report")
modes = parser.add_mutually_exclusive_group(required=True)
modes.add_argument("--summary", dest="mode", action="store_const", const="summary")
modes.add_argument("--detail", dest="mode", action="store_const", const="detail")
summary_args = parser.parse_args(["--summary"])
detail_args = parser.parse_args(["--detail"])
assert summary_args.mode == "summary"
assert detail_args.mode == "detail"
print(f"first={summary_args.mode}")
print(f"second={detail_args.mode}")
first=summary
second=detail
Comments
Post a Comment