Sub topic 15
Sharing options with parent parsers
This chapter assumes you can build a parser with add_argument, you know what store_true does, and you have written a tool with subcommands using add_subparsers and set_defaults(func=...). Parent parsers solve one problem: several parsers need the same options, and copying the add_argument calls into each one invites drift.
The problem: repeated options
Suppose every subcommand of a todo tool accepts --verbose and --config. Without sharing, you write the same two add_argument calls once per subcommand. Later someone changes the help text in one place and forgets the others, and todo add --help and todo list --help disagree.
The parents argument of ArgumentParser fixes this. You define the shared options once on a small parser, then pass that parser to every parser that needs them.
Building a parent parser
A parent parser is an ordinary ArgumentParser that you never call parse_args on. Its only job is to hold argument definitions. Create it with add_help=False.
import argparse
import sys
def common_options():
common = argparse.ArgumentParser(add_help=False)
common.add_argument("-v", "--verbose", action="store_true",
help="print extra information to stderr")
common.add_argument("--config", default="todo.toml", metavar="FILE",
help="path to the config file (default: %(default)s)")
return common
def cmd_add(args):
if args.verbose:
print(f"using config {args.config}", file=sys.stderr)
print(f"adding {args.item}")
return 0
def cmd_list(args):
if args.verbose:
print(f"using config {args.config}", file=sys.stderr)
print("listing", "all" if args.all else "open", "items")
return 0
def build_parser():
parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", parents=[common_options()], help="add an item")
add.add_argument("item")
add.set_defaults(func=cmd_add)
ls = sub.add_parser("list", parents=[common_options()], help="list items")
ls.add_argument("--all", action="store_true")
ls.set_defaults(func=cmd_list)
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
return args.func(args)
if __name__ == "__main__":
raise SystemExit(main())sub.add_parser forwards its keyword arguments to the ArgumentParser constructor, so parents=[...] works there exactly as it does on a top-level parser. Both of these now work:
$ python todo.py add milk --verbose
using config todo.toml
adding milk
$ python todo.py list --config work.toml --all
listing all itemsBoth subcommands accept -v, --verbose and --config. args.verbose and args.config exist on the result whichever subcommand ran.
What the diagram shows
The shared definitions flow into each child at construction time. Each child then adds its own arguments.
Why the parent needs add_help=False
Every ArgumentParser adds -h/--help by default. If the parent keeps its own help option and the child adds one too, the child ends up with two definitions of -h. The constructor then fails:
import argparse
parent = argparse.ArgumentParser() # add_help defaults to True
child = argparse.ArgumentParser(parents=[parent])This raises argparse.ArgumentError: argument -h/--help: conflicting option string: -h, --help at the moment you build the child. The error appears as soon as the parser is constructed, so you will see it the first time you run the program. The fix is always add_help=False on the parent. The child keeps its own help option, and the help text lists the inherited options alongside its own.
How inheritance works internally
When you build a child, argparse walks the parent's registered actions and adds each one to the child. It copies the parent's argument groups and mutually exclusive groups too. These facts follow from that process, and each can cause a bug.
- The copy happens once, at construction. Arguments you add to the parent after creating the child do not appear on the child. Finish the parent before you use it.
- Action objects are shared, not duplicated. The child's list of actions holds the same
Actionobjects as the parent's. Code that changes an action in place can therefore affect every parser built from that parent. - Parser-level settings are not inherited.
prog,description,epilog,formatter_classandallow_abbrevbelong to the parser you construct. Set them on the child. Only argument definitions travel. - Order matters. Options are the same wherever they are defined, but positional arguments are matched in the order they were registered. Parent positionals come first. If a parent defines a positional, every child parses it before its own.
The second point is why the example calls common_options() once per subcommand instead of sharing a single module-level parent. A function that builds a fresh parent each time gives every child its own Action objects. Calling child.set_defaults(verbose=True) on one child changes the default on the shared action, and a sibling child would then see the new default. A factory function makes that mistake impossible.
Parent parsers and global options
Parent parsers put options after the subcommand name. That is not the same as a global option on the top-level parser:
| Where the option is defined | Valid command line | Typical use |
|---|---|---|
| Top-level parser | `todo --verbose add milk` | Settings that apply to the whole tool |
| Parent shared by subparsers | `todo add milk --verbose` | Options repeated per subcommand |
| Both | Either position, but the results can be confusing | Avoid |
With the example above, todo --verbose add milk fails with an unrecognized-arguments error. The top-level parser has no --verbose. If you want --verbose in front, add it to the top-level parser instead. Do not define the same dest at both levels. The two parsers fill the same attribute of the result, and which value wins depends on the order of parsing and the defaults, which is hard to reason about. Choose one level per option.
If users must be able to write the option in both positions, a common approach is to give the top-level option a distinct dest, such as global_verbose, and combine the two values in main:
verbose = args.global_verbose or args.verboseMost tools avoid that extra complexity and pick one position.
Using several parents
parents takes a list, so you can compose small pieces:
import argparse
output = argparse.ArgumentParser(add_help=False)
output.add_argument("--format", choices=["text", "json"], default="text")
selection = argparse.ArgumentParser(add_help=False)
selection.add_argument("--limit", type=int, default=10)
report = argparse.ArgumentParser(prog="report", parents=[output, selection])
report.add_argument("name")
args = report.parse_args(["--format", "json", "sales"])
print(args.format, args.limit, args.name)This prints json 10 sales. Keep each parent small and focused, such as output options or selection options, so that a command pulls in only the groups it needs. If two parents define the same option string, you get the same conflict error as with -h. You can pass conflict_handler="resolve" to the child so that the latest definition replaces the earlier one. Treat that as a last resort, because silently replacing an option hides a real design clash.
Common errors
- Forgetting
add_help=Falseon the parent. This gives the "conflicting option string" error at construction. - Adding to the parent after building the child. The new option is missing from the child, and no error tells you so. Parse a command line that uses the option in a test.
- Sharing one parent object and mutating a child's defaults. Use a factory function instead.
- Expecting
descriptionorprogto be inherited. Set them on each child. - Expecting parent options before the subcommand. They are accepted only after the subcommand name.
When a parent is not worth it
A parent parser pays off when at least two parsers share two or more options. For a single shared flag, a helper function that takes a parser and calls add_argument on it is just as clear, and it works on parsers that already exist:
def add_verbose(parser):
parser.add_argument("-v", "--verbose", action="store_true")That helper can add the flag to a parser at any point, and it has none of the construction-time rules above. Reach for parents when you want to define a whole group of options, including argument groups, as one reusable unit.
Exercise
A teammate writes common = argparse.ArgumentParser() with a --dry-run flag and passes it as parents=[common] to a subparser. The program crashes when the parser is built. What is the cause and the fix? After the fix, todo add milk --dry-run works, but todo --dry-run add milk does not. Why?
Show answer
The parent was created with the default add_help=True, so it has -h/--help, and the child adds its own -h/--help. The conflict raises ArgumentError: conflicting option string. The fix is argparse.ArgumentParser(add_help=False) for the parent. The second form fails because a parent shared by subparsers puts its options on each subcommand parser, so they are accepted only after the subcommand name. The top-level parser has no --dry-run. To accept it before the subcommand, define it on the top-level parser.
Exercise
You build a child parser from a parent, then call parent.add_argument("--timeout", type=int). Does child.parse_args(["--timeout", "5"]) work? Why or why not?
Show answer
No. It fails with an unrecognized-arguments error. Argparse copies the parent's actions into the child when the child is constructed, so arguments added to the parent later are not seen by the child. Add --timeout to the parent before creating the child.