Subcommands#

Unions over nested types (classes or dataclasses) are populated using subcommands.

For configuring subcommands beyond what can be expressed with type annotations, see tyro.conf.subcommand().

 1from __future__ import annotations
 2
 3import dataclasses
 4
 5import tyro
 6
 7
 8@dataclasses.dataclass(frozen=True)
 9class Checkout:
10    """Checkout a branch."""
11
12    branch: str
13
14
15@dataclasses.dataclass(frozen=True)
16class Commit:
17    """Commit changes."""
18
19    message: str
20    all: bool = False
21
22
23def main(cmd: Checkout | Commit) -> None:
24    print(cmd)
25
26
27if __name__ == "__main__":
28    # Note that we can also pass `Checkout | Command` directly into
29    # `tyro.cli()`; this is understood by tyro and pyright, but unfortunately not by
30    # mypy.
31    tyro.cli(main)

python 02_nesting/02_subcommands.py --help
usage: 02_subcommands.py [-h] {cmd:checkout,cmd:commit}

╭─ options ─────────────────────────────────────────╮
│ -h, --help        show this help message and exit │
╰───────────────────────────────────────────────────╯
╭─ subcommands ─────────────────────────────────────╮
│ {cmd:checkout,cmd:commit}                         │
│     cmd:checkout  Checkout a branch.              │
│     cmd:commit    Commit changes.                 │
╰───────────────────────────────────────────────────╯

python 02_nesting/02_subcommands.py cmd:commit --help
usage: 02_subcommands.py cmd:commit [-h] --cmd.message STR
                                    [--cmd.all | --cmd.no-all]

Commit changes.

╭─ options ───────────────────────────────────────────────╮
│ -h, --help              show this help message and exit │
╰─────────────────────────────────────────────────────────╯
╭─ cmd options ───────────────────────────────────────────╮
│ --cmd.message STR       (required)                      │
│ --cmd.all, --cmd.no-all                                 │
│                         (default: False)                │
╰─────────────────────────────────────────────────────────╯

python 02_nesting/02_subcommands.py cmd:commit --cmd.message hello --cmd.all
Commit(message='hello', all=True)

python 02_nesting/02_subcommands.py cmd:checkout --help
usage: 02_subcommands.py cmd:checkout [-h] --cmd.branch STR

Checkout a branch.

╭─ options ───────────────────────────────────────────────╮
│ -h, --help              show this help message and exit │
╰─────────────────────────────────────────────────────────╯
╭─ cmd options ───────────────────────────────────────────╮
│ --cmd.branch STR        (required)                      │
╰─────────────────────────────────────────────────────────╯

python 02_nesting/02_subcommands.py cmd:checkout --cmd.branch main
Checkout(branch='main')