Sub topic 12
Building tools with subcommands
This chapter assumes you can build a parser with positional arguments and options, and that you structure programs around main(argv). Tools like git commit and pip install use subcommands: a first word that selects an action, each with its own arguments.
How subparsers work
parser.add_subparsers() creates a special action on the main parser. Each call to add_parser() on it returns a full ArgumentParser for one subcommand. The main parser reads arguments up to the subcommand name, then hands the remaining arguments to that subcommand's parser.
A complete example
Each subcommand gets its own arguments. The set_defaults(func=...) call stores the handler function in the result, so main can dispatch with one call and needs no chain of if statements.
import argparse
def cmd_add(args):
print(f"adding {args.item}")
return 0
def cmd_list(args):
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", help="add an item")
add.add_argument("item")
add.set_defaults(func=cmd_add)
ls = sub.add_parser("list", 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())Running python todo.py add milk prints adding milk. Running python todo.py list --all prints listing all items. Running python todo.py --help lists both subcommands with their help text. Running python todo.py list --help shows only the options of list.
Details that matter
dest="command"stores the chosen subcommand name inargs.command. It also gives the error message a readable name.required=Truemakes a missing subcommand a usage error. Since Python 3.7 subparsers are optional by default. Without this argument,todoalone would parse successfully andargs.funcwould raiseAttributeError.help=onadd_parseris the one-line description shown in the main help. Usedescription=as well if the subcommand's own help needs more text.- Option position matters. Options defined on the main parser must come before the subcommand name. Options defined on a subparser must come after it.
Dispatching without `set_defaults`
You can also branch on args.command:
if args.command == "add":
return cmd_add(args)
return cmd_list(args)This works for two commands. The func approach scales better because adding a subcommand touches only the parser-building code, and a forgotten branch cannot silently fall through to the wrong handler.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `AttributeError: 'Namespace' object has no attribute 'func'` | No subcommand given and `required=True` missing | Add `required=True` |
| `unrecognized arguments: --all` | Option placed before the subcommand, or defined on a different parser | Put it after `list`, or define it on the right parser |
| Handler sees `None` for a shared option | Same option name defined on both main and subparser | Use different `dest` names or define it once |
Exercise
In the todo tool, you add a done subcommand with a positional item. What three things must you do in build_parser, and what does main need to change?
Show answer
Call sub.add_parser("done", help="mark an item done"), call add_argument("item") on the returned parser, and call set_defaults(func=cmd_done) on it, with a cmd_done(args) function defined that returns an exit code. main needs no change, because it already calls args.func(args).
Exercise
What happens when a user runs todo with no arguments if you leave out required=True, and why?
Show answer
Parsing succeeds because subparsers are optional by default since Python 3.7. The namespace has no func attribute, so args.func(args) raises AttributeError instead of showing a usage error.