Sub topic 11
Argument groups and mutually exclusive options
This chapter assumes you can build a parser with positional arguments, options and flags, and that you know main(argv) returns an exit code. It covers two tools for larger interfaces. Argument groups organize the help output. Mutually exclusive groups reject invalid combinations of options.
Two different jobs
The two group types are easy to confuse because both come from the parser and both hold arguments.
| Feature | Created with | What it changes | Affects parsing? |
|---|---|---|---|
| Argument group | `add_argument_group(title, description)` | Help layout: a titled section | No |
| Mutually exclusive group | `add_mutually_exclusive_group(required=False)` | Which combinations are accepted | Yes |
An argument group never rejects input. A mutually exclusive group never changes how help sections look, except that its members appear in the usage line joined by |.
Argument groups: organizing help
By default, --help shows two sections: "positional arguments" and "options". With a dozen options, this list becomes hard to scan. A group gives related options their own heading.
import argparse
parser = argparse.ArgumentParser(
prog="backup", description="Copy a directory to a destination."
)
parser.add_argument("source")
parser.add_argument("dest")
compression = parser.add_argument_group(
"compression", "Control how the archive is compressed."
)
compression.add_argument("--level", type=int, default=6,
help="compression level (default: %(default)s)")
compression.add_argument("--algorithm", choices=["gzip", "xz"], default="gzip",
help="compression algorithm (default: %(default)s)")
output = parser.add_argument_group("output")
output.add_argument("-v", "--verbose", action="store_true",
help="print each file as it is copied")
args = parser.parse_args(["src", "dst", "--level", "9"])
print(args.level, args.algorithm, args.verbose)
parser.print_help()The first print shows 9 gzip False. Group membership does not change the result. args.level is a plain attribute on the namespace, with no args.compression.level. In the help output, the new section looks like this (abridged):
compression:
Control how the archive is compressed.
--level LEVEL compression level (default: 6)
--algorithm {gzip,xz}
compression algorithm (default: gzip)The description is optional. The title is also optional (add_argument_group() accepts None), but an untitled group prints as a bare block, which is rarely what you want.
Notes on argument groups
- You can add arguments to a group in any order relative to the parser's own
add_argumentcalls. The usage line still lists every option in the order it was added. - Groups are a presentation tool, so don't use them to model behavior. If
--levelonly makes sense with a compressed format, check that after parsing (see below). - Putting a group inside another argument group is deprecated since Python 3.11. Keep groups flat.
Mutually exclusive groups: rejecting combinations
Some options contradict each other: --quiet and --verbose, or --save FILE and --stdout. Instead of checking this by hand, declare it.
import argparse
parser = argparse.ArgumentParser(prog="fetch")
parser.add_argument("url")
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("--save", metavar="FILE", help="write the result to FILE")
mode.add_argument("--stdout", action="store_true", help="print the result")
for argv in (["http://x", "--stdout"],
["http://x", "--stdout", "--save", "a.txt"],
["http://x"]):
try:
print(parser.parse_args(argv))
except SystemExit as exc:
print("exit status", exc.code)The three calls behave differently:
--stdoutalone succeeds and prints a namespace withsave=None, stdout=True.- Both options give the error
fetch: error: argument --save: not allowed with argument --stdout. Argparse writes it to stderr along with the usage line, then exits with status 2. - Neither option gives
fetch: error: one of the arguments --save --stdout is required, and the exit status is again 2.
With required=True, the usage line changes to (--save FILE | --stdout), with round brackets. Without it, it is [--save FILE | --stdout], with square brackets. The bracket style tells readers whether a choice is mandatory.
Sharing one destination
A common pattern is to let several exclusive flags set a single value, so later code reads one attribute instead of testing each flag.
import argparse
parser = argparse.ArgumentParser(prog="build")
level = parser.add_mutually_exclusive_group()
level.add_argument("-q", "--quiet", dest="level",
action="store_const", const="quiet")
level.add_argument("-v", "--verbose", dest="level",
action="store_const", const="verbose")
parser.set_defaults(level="normal")
print(parser.parse_args([]).level)
print(parser.parse_args(["-q"]).level)This prints normal, then quiet. Setting the default once with set_defaults avoids repeating it on each flag.
Rules and gotchas
Members must be optional
A member of a mutually exclusive group cannot be a required option. A positional argument can be a member only if it is optional, which means nargs="?" or nargs="*". Argparse raises ValueError when you build the parser, not when a user runs it, so you find the mistake in development.
import argparse
parser = argparse.ArgumentParser(prog="open")
group = parser.add_mutually_exclusive_group()
group.add_argument("path", nargs="?")
group.add_argument("--recent", action="store_true")
print(parser.parse_args(["notes.txt"]))
print(parser.parse_args(["--recent"]))Here required=True on the group, not on the members, expresses "exactly one of these".
Use `default=None` for members
Argparse decides that an option "was used" by comparing the parsed value to the option's default. An option that is given a value identical to its default can slip past the exclusivity check in some cases. Give group members default=None, or use store_true and store_const actions, whose defaults differ from what the user supplies. Then choose real defaults after parsing, or with set_defaults as shown above.
Abbreviations count
Argparse accepts unambiguous prefixes by default, so --std is treated as --stdout. The exclusivity check still applies to the abbreviated form. If you do not want prefix matching, pass allow_abbrev=False to ArgumentParser.
Groups inside subparsers
Each subparser has its own groups. A mutually exclusive group created on the top-level parser does not constrain options of a subcommand, and the reverse also holds. Define the group on the parser that owns the options.
Placing an exclusive group in a titled section
A mutually exclusive group has no title of its own. To show it under a heading, create it from an argument group.
import argparse
parser = argparse.ArgumentParser(prog="fetch")
target = parser.add_argument_group("target")
choice = target.add_mutually_exclusive_group(required=True)
choice.add_argument("--save", metavar="FILE")
choice.add_argument("--stdout", action="store_true")
parser.print_usage()The usage line is usage: fetch [-h] (--save FILE | --stdout), and the help output lists both options under target:.
Rules the library cannot express
Argparse only supports "at most one" and "exactly one". Other relationships, such as "--user requires --password" or "at least one of these two", need a check after parsing. Call parser.error(message) so the failure looks the same as any other usage error: a usage line, a message on stderr, and exit status 2.
import argparse
import sys
def build_parser():
parser = argparse.ArgumentParser(prog="login")
parser.add_argument("--user")
parser.add_argument("--password")
return parser
def main(argv=None):
parser = build_parser()
args = parser.parse_args(argv)
if args.user and not args.password:
parser.error("--user requires --password")
print(f"logging in as {args.user or 'anonymous'}", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())Running python login.py --user ada prints the usage line and login: error: --user requires --password, then exits with 2. Keeping the parser in build_parser and the check in main means a test can call main(["--user", "ada"]) and catch SystemExit.
Choosing between the tools
- Use an argument group when help has more than about eight options and they fall into clear themes.
- Use a mutually exclusive group when two options cannot both be meaningful, or when exactly one of several must be chosen.
- Use a post-parse check with
parser.errorfor any dependency between options. - If several modes each take different options, consider subcommands instead. A
--save/--stdoutchoice is a good group, butexportandimportwith their own options are better as subcommands.
Exercise
A tool takes --json and --csv output flags, and the user must choose exactly one. It also takes --sep, which makes sense only with --csv. How would you build the parser so that a bare run, --json --csv, and --json --sep ";" are all rejected with exit status 2 and a clear message?
Show answer
Put --json and --csv (both action="store_true") in parser.add_mutually_exclusive_group(required=True). A bare run gives "one of the arguments --json --csv is required", and passing both gives "not allowed with argument". Give --sep default=None as a normal option. After parse_args, check if args.sep is not None and not args.csv: parser.error("--sep requires --csv"). Argparse cannot express this dependency, so the check must be done manually. parser.error prints the usage line and exits with status 2.