Sub topic 15
Sharing options with parent parsers
This chapter assumes you can build a subcommand tool with add_subparsers and set_defaults, as in the previous chapter. Here you will remove the duplication that appears when several subcommands need the same options.
The duplication problem
Suppose every subcommand of a todo tool accepts --verbose and --config. You could call add_argument on each subparser, but the copies drift apart over time. One gets a different help string, and another misses a new option.
A parent parser solves this. You declare the shared options once, then pass the parser to parents=[...] when you create each child. The child copies every argument from its parents.
Building a parent parser
import argparse
def build_common():
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.json",
help="path to the data file (default: %(default)s)")
return common
def build_parser():
common = build_common()
parser = argparse.ArgumentParser(prog="todo")
sub = parser.add_subparsers(dest="command", required=True)
add = sub.add_parser("add", parents=[common], help="add an item")
add.add_argument("item")
ls = sub.add_parser("list", parents=[common], help="list items")
ls.add_argument("--all", action="store_true")
return parser
args = build_parser().parse_args(["add", "--verbose", "milk"])
print(args.command, args.verbose, args.config, args.item)This prints add True todo.json milk. Both subcommands now accept -v and --config, and each one also keeps its own arguments.
Why `add_help=False` matters
Every ArgumentParser registers -h/--help by default. If the parent and the child both do this, the child fails when you create it:
argparse.ArgumentError: argument -h/--help: conflicting option strings: -h, --helpSet add_help=False on any parser that exists only to be a parent. The child keeps its own help option, so todo add -h still works and lists the inherited options.
Behavior to know about
- Position matters. The inherited options belong to the subparser, so they must come after the subcommand.
todo add --verbose milkworks.todo --verbose add milkfails witherror: unrecognized arguments: --verbose. To accept an option in both places, add it to the main parser too. Use a differentdestfor each, or give the main-parser copydefault=argparse.SUPPRESS. Otherwise one default can overwrite the other value. - Copy at creation time. A child copies its parents' arguments when it is created. Arguments you add to the parent afterward do not reach existing children.
- Conflicts are errors. If a child declares an option string that a parent already defines, argparse raises the same "conflicting option strings" error. Use
conflict_handler="resolve"only if you want the child's definition to replace the parent's. - Several parents work.
parents=[common, output_opts]combines them. The same conflict rules apply between parents.
Exercise
You add parents=[common] to a new subparser, and creating it raises "conflicting option strings: -h, --help". What is the cause and the fix?
Show answer
The parent parser was created with the default add_help=True, so both the parent and the child define -h/--help. Create the parent with argparse.ArgumentParser(add_help=False).
Exercise
Given the todo parser above, why does todo --config prod.json list fail, and how do you run it correctly?
Show answer
--config is defined on the list subparser, not on the main parser, so the main parser does not recognize it. Put it after the subcommand: todo list --config prod.json.