Sub topic 11
Argument groups and mutually exclusive options
This chapter assumes you can build an ArgumentParser, add options and flags with add_argument, and read the resulting Namespace. It covers two tools for organizing options: argument groups, which affect only the help text, and mutually exclusive groups, which affect validation.
Argument groups organize help output
A tool with many options produces a long, flat help screen. add_argument_group collects related options under a heading of your choice. Grouping changes only how --help is displayed. It has no effect on parsing, and the options still end up as plain attributes on the namespace.
import argparse
parser = argparse.ArgumentParser(prog="export")
parser.add_argument("source")
fmt = parser.add_argument_group("output format", "Control how data is written.")
fmt.add_argument("--format", choices=["csv", "json"], default="csv")
fmt.add_argument("--indent", type=int, default=2)
net = parser.add_argument_group("network")
net.add_argument("--timeout", type=float, default=10.0)
args = parser.parse_args(["data.db", "--format", "json"])
print(args.format, args.indent, args.timeout)Running export --help lists --format and --indent under "output format" and --timeout under "network". Without groups, argparse files options under the default headings "positional arguments" and "options".
Mutually exclusive groups validate combinations
Some options cannot be used together, such as --quiet and --verbose. add_mutually_exclusive_group makes argparse reject any command line that uses more than one member of the group.
import argparse
parser = argparse.ArgumentParser(prog="serve")
group = parser.add_mutually_exclusive_group()
group.add_argument("--quiet", action="store_true")
group.add_argument("--verbose", action="store_true")
print(parser.parse_args(["--quiet"]))
parser.parse_args(["--quiet", "--verbose"])The first call succeeds. The second prints a usage message and an error similar to argument --verbose: not allowed with argument --quiet, then exits with status 2, like any other parsing error.
To force the user to choose one member, pass required=True when you create the group:
group = parser.add_mutually_exclusive_group(required=True)Now omitting every member of the group is also an error.
How the two kinds of group relate
Common errors and limits
- Positional arguments in an exclusive group. A positional can belong to a mutually exclusive group only if it is optional, for example with
nargs="?". Otherwise argparse raises aValueErrorwhile you build the parser. - Required members. Individual members of a mutually exclusive group cannot be marked
required=True. Setrequiredon the group instead. - Defaults do not count as use. Only options the user actually types trigger the conflict check. A member with a default value does not conflict with another member.
- Nesting. Mutually exclusive groups cannot be nested, and
add_argument_groupcannot be called on one. In older Python versions, nesting was accepted silently but did nothing. Python 3.11 deprecated it, and 3.14 removed it. - Exclusive groups in help. An exclusive group has no title of its own. To give it a heading, create an argument group first and call
add_mutually_exclusive_groupon that group.
import argparse
parser = argparse.ArgumentParser(prog="serve")
logging_opts = parser.add_argument_group("logging")
exclusive = logging_opts.add_mutually_exclusive_group()
exclusive.add_argument("--quiet", action="store_true")
exclusive.add_argument("--verbose", action="store_true")This combination gives you a "logging" heading in the help and also enforces that only one of the two options is used.
Exercise
You add --json and --csv flags to a mutually exclusive group created with required=True. What happens if the user runs the tool with neither flag, and what exit status does argparse use?
Show answer
argparse prints the usage text and an error saying one of the arguments --json --csv is required, then exits with status 2. With required=False (the default), omitting both flags is allowed.