Subcommands from Functions#
tyro.extras.subcommand_cli_from_dict()
provides a shorthand that generates a
subcommand CLI from a dictionary.
For an input like:
tyro.extras.subcommand_cli_from_dict(
{
"checkout": checkout,
"commit": commit,
}
)
This is internally accomplished by generating and calling:
from typing import Annotated, Any, Union
import tyro
tyro.cli(
Union[
Annotated[
Any,
tyro.conf.subcommand(name="checkout", constructor=checkout),
],
Annotated[
Any,
tyro.conf.subcommand(name="commit", constructor=commit),
],
]
)
1import tyro
2
3
4def checkout(branch: str) -> None:
5 """Check out a branch."""
6 print(f"{branch=}")
7
8
9def commit(message: str, all: bool = False) -> None:
10 """Make a commit."""
11 print(f"{message=} {all=}")
12
13
14if __name__ == "__main__":
15 tyro.extras.subcommand_cli_from_dict(
16 {
17 "checkout": checkout,
18 "commit": commit,
19 }
20 )
python 02_nesting/05_subcommands_func.py --help
usage: 05_subcommands_func.py [-h] {checkout,commit} ╭─ options ───────────────────────────────────────────────╮ │ -h, --help show this help message and exit │ ╰─────────────────────────────────────────────────────────╯ ╭─ subcommands ───────────────────────────────────────────╮ │ {checkout,commit} │ │ checkout Check out a branch. │ │ commit Make a commit. │ ╰─────────────────────────────────────────────────────────╯
python 02_nesting/05_subcommands_func.py commit --help
usage: 05_subcommands_func.py commit [-h] --message STR [--all | --no-all] Make a commit. ╭─ options ──────────────────────────────────────────────╮ │ -h, --help show this help message and exit │ │ --message STR (required) │ │ --all, --no-all (default: False) │ ╰────────────────────────────────────────────────────────╯
python 02_nesting/05_subcommands_func.py commit --message hello --all
message='hello' all=True
python 02_nesting/05_subcommands_func.py checkout --help
usage: 05_subcommands_func.py checkout [-h] --branch STR Check out a branch. ╭─ options ───────────────────────────────────────────╮ │ -h, --help show this help message and exit │ │ --branch STR (required) │ ╰─────────────────────────────────────────────────────╯
python 02_nesting/05_subcommands_func.py checkout --branch main
branch='main'