✨ Add support for extending typer apps without passing a name, add commands to the top level (#1037)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Patrick Arminio · committed by GitHub · parent 3af0a84 · Browse files · 15 files·+469 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
- Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Diff stats
15 files+469 added−6 removed
- tests:+269 added−0 removed
- other:+200 added−6 removed
Provenance
- Commit
2681205- Tree
3c3d122- Author
Patrick Arminio <patrick.arminio@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
3af0a84
15 files changed+469 added−6 removed
added:docs/tutorial/one-file-per-command.md+144 added
1+# One File Per Command2+3+When your CLI application grows, you can split it into multiple files and modules. This pattern helps maintain a clean and organized code structure. ✨4+5+This tutorial will show you how to use `add_typer` to create sub commands and organize your commands in multiple files.6+7+We will create a simple CLI with the following commands:8+9+- `version`10+- `users add NAME`11+- `users delete NAME`12+13+## CLI structure14+15+Here is the structure we'll be working with:16+17+```text18+mycli/19+├── __init__.py20+├── main.py21+├── users/22+│ ├── __init__.py23+│ ├── add.py24+│ └── delete.py25+└── version.py26+```27+28+`mycli` will be our <abbr title="a directory with an __init__.py file, it can be imported">package</abbr>, and it will contain the following modules:29+30+- `main.py`: The main <abbr title="a Python file that can be imported">module</abbr> that will import the `version` and `users` modules.31+- `version.py`: A <abbr title="a Python file that can be imported">module</abbr> that will contain the `version` command.32+- `users/`: A <abbr title="another directory with an __init__.py file, it can also be imported">package</abbr> (inside of our `mycli` package) that will contain the `add` and `delete` commands.33+34+## Implementation35+36+Let's start implementing our CLI! 🚀37+38+We'll create the `version` module, the `main` module, and the `users` package.39+40+### Version Module (`version.py`)41+42+Let's start by creating the `version` module. This module will contain the `version` command.43+44+{* docs_src/one_file_per_command/version.py *}45+46+In this file we are creating a new Typer app instance for the `version` command.47+48+This is not required in single-file applications, but in the case of multi-file applications it will allow us to include this command in the main application using `app.add_typer()`.49+50+Let's see that next!51+52+### Main Module (`main.py`)53+54+The main module will be the entry point of the application. It will import the version module and the users module.55+56+/// tip57+58+We'll see how to implement the users module in the next section.59+60+///61+62+{* docs_src/one_file_per_command/main.py hl[8,9] *}63+64+In this module, we import the `version` and `users` modules and add them to the main app using `app.add_typer()`.65+66+For the `users` module, we specify the name as `"users"` to group the commands under the `users` sub-command.67+68+Notice that we didn't add a name for the `version_app` Typer app. Because of this, Typer will add the commands (just one in this case) declared in the `version_app` directly at the top level. So, there will be a top-level `version` sub-command.69+70+But for `users`, we add a name `"users"`, this way those commands will be under the sub-command `users` instead of at the top level. So, there will be a `users add` and `users delete` sub-sub-commands. 😅71+72+/// tip73+74+If you want a command to group the included commands in a sub-app, add a name.75+76+If you want to include the commands from a sub-app directly at the top level, don't add a name, or set it to `None`. 🤓77+78+///79+80+Let's now create the `users` module with the `add` and `delete` commands.81+82+### Users Add Command (`users/add.py`)83+84+{* docs_src/one_file_per_command/users/add.py *}85+86+Like the `version` module, we create a new Typer app instance for the `users/add` command. This allows us to include the `add` command in the users app.87+88+### Users Delete Command (`users/delete.py`)89+90+{* docs_src/one_file_per_command/users/delete.py *}91+92+And once again, we create a new Typer app instance for the `users/delete` command. This allows us to include the `delete` command in the users app.93+94+### Users' app (`users/__init__.py`)95+96+Finally, we need to create an `__init__.py` file in the `users` directory to define the `users` app.97+98+{* docs_src/one_file_per_command/users/__init__.py *}99+100+Similarly to the `version` module, we create a new `Typer` app instance for the `users` module. This allows us to include the `add` and `delete` commands in the users app.101+102+## Running the Application103+104+Now we are ready to run the application! 😎105+106+To run the application, you can execute it as a Python module:107+108+<div class="termy">109+110+```console111+$ python -m mycli.main version112+113+My CLI Version 1.0114+115+$ python -m mycli.main users add Camila116+117+Adding user: Camila118+```119+120+</div>121+122+And if you built a package and installed your app, you can then use the `mycli` command:123+124+<div class="termy">125+126+```console127+$ mycli version128+129+My CLI Version 1.0130+131+$ mycli users add Camila132+133+Adding user: Camila134+```135+136+</div>137+138+## Callbacks139+140+Have in mind that if you include a sub-app with `app.add_typer()` **without a name**, the commands will be added to the top level, so **only the top level callback** (if there's any) will be used, the one declared in the main app.141+142+If you **want to use a callback** for a sub-app, you need to include the sub-app **with a name**, which creates a sub-command grouping the commands in that sub-app. 🤓143+144+In the example above, if the `users` sub-app had a callback, it would be used. But if the `version` sub-app had a callback, it would not be used, because the `version` sub-app was included without a name.added:docs_src/one_file_per_command/users/__init__.py+9 added
1+import typer2+3+from .add import app as add_app4+from .delete import app as delete_app5+6+app = typer.Typer()7+8+app.add_typer(add_app)9+app.add_typer(delete_app)added:docs_src/one_file_per_command/users/add.py+8 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def add(name: str):8+ print(f"Adding user: {name}")added:docs_src/one_file_per_command/users/delete.py+8 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def delete(name: str):8+ print(f"Deleting user: {name}")added:docs_src/one_file_per_command/__init__.py
added:docs_src/one_file_per_command/main.py+13 added
1+import typer2+3+from .users import app as users_app4+from .version import app as version_app5+6+app = typer.Typer()7+8+app.add_typer(version_app)9+app.add_typer(users_app, name="users")10+11+12+if __name__ == "__main__":13+ app()added:docs_src/one_file_per_command/version.py+8 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def version():8+ print("My CLI Version 1.0")added:tests/assets/cli/extended_app_cli.py+31 added
1+import typer2+3+sub_sub_app = typer.Typer()4+5+6+@sub_sub_app.command()7+def sub_sub_command():8+ typer.echo("sub_sub_command")9+10+11+sub_app = typer.Typer()12+sub_app.add_typer(sub_sub_app, name="sub")13+14+15+@sub_app.command()16+def hello():17+ typer.echo("hello there")18+19+20+@sub_app.command()21+def bye():22+ typer.echo("bye bye")23+24+25+cli = typer.Typer()26+cli.add_typer(sub_app)27+28+29+@cli.command()30+def top():31+ typer.echo("top")added:tests/assets/cli/extended_empty_app_cli.py+15 added
1+import typer2+3+cli = typer.Typer()4+sub_app = typer.Typer()5+cli.add_typer(sub_app)6+7+8+@sub_app.command()9+def hello():10+ typer.echo("hello there")11+12+13+@sub_app.command()14+def bye():15+ typer.echo("bye bye")added:tests/test_cli/test_extending_app.py+120 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/extended_app_cli.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "top" in result.stdout22+ assert "hello" in result.stdout23+ assert "sub" in result.stdout24+25+26+def test_script_top():27+ result = subprocess.run(28+ [29+ sys.executable,30+ "-m",31+ "coverage",32+ "run",33+ "-m",34+ "typer",35+ "tests/assets/cli/extended_app_cli.py",36+ "run",37+ "top",38+ ],39+ capture_output=True,40+ encoding="utf-8",41+ )42+ assert "top" in result.stdout43+44+45+def test_script_hello():46+ result = subprocess.run(47+ [48+ sys.executable,49+ "-m",50+ "coverage",51+ "run",52+ "-m",53+ "typer",54+ "tests/assets/cli/extended_app_cli.py",55+ "run",56+ "hello",57+ ],58+ capture_output=True,59+ encoding="utf-8",60+ )61+ assert "hello there" in result.stdout62+63+64+def test_script_bye():65+ result = subprocess.run(66+ [67+ sys.executable,68+ "-m",69+ "coverage",70+ "run",71+ "-m",72+ "typer",73+ "tests/assets/cli/extended_app_cli.py",74+ "run",75+ "bye",76+ ],77+ capture_output=True,78+ encoding="utf-8",79+ )80+ assert "bye" in result.stdout81+82+83+def test_script_sub_command_help():84+ result = subprocess.run(85+ [86+ sys.executable,87+ "-m",88+ "coverage",89+ "run",90+ "-m",91+ "typer",92+ "tests/assets/cli/extended_app_cli.py",93+ "run",94+ "sub",95+ "--help",96+ ],97+ capture_output=True,98+ encoding="utf-8",99+ )100+ assert "sub-sub-command" in result.stdout101+102+103+def test_script_sub_sub_command():104+ result = subprocess.run(105+ [106+ sys.executable,107+ "-m",108+ "coverage",109+ "run",110+ "-m",111+ "typer",112+ "tests/assets/cli/extended_app_cli.py",113+ "run",114+ "sub",115+ "sub-sub-command",116+ ],117+ capture_output=True,118+ encoding="utf-8",119+ )120+ assert "sub_sub_command" in result.stdoutadded:tests/test_cli/test_extending_empty_app.py+59 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/extended_empty_app_cli.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "hello" in result.stdout22+23+24+def test_script_hello():25+ result = subprocess.run(26+ [27+ sys.executable,28+ "-m",29+ "coverage",30+ "run",31+ "-m",32+ "typer",33+ "tests/assets/cli/extended_empty_app_cli.py",34+ "run",35+ "hello",36+ ],37+ capture_output=True,38+ encoding="utf-8",39+ )40+ assert "hello there" in result.stdout41+42+43+def test_script_bye():44+ result = subprocess.run(45+ [46+ sys.executable,47+ "-m",48+ "coverage",49+ "run",50+ "-m",51+ "typer",52+ "tests/assets/cli/extended_empty_app_cli.py",53+ "run",54+ "bye",55+ ],56+ capture_output=True,57+ encoding="utf-8",58+ )59+ assert "bye" in result.stdoutadded:tests/test_tutorial/test_one_file_per_command/__init__.py
added:tests/test_tutorial/test_one_file_per_command/test_tutorial.py+44 added
1+from typer.testing import CliRunner2+3+from docs_src.one_file_per_command import main as mod4+5+runner = CliRunner()6+7+8+def test_help():9+ result = runner.invoke(mod.app, ["--help"])10+11+ assert result.exit_code == 012+13+ assert "version" in result.output14+ assert "users" in result.output15+16+17+def test_version():18+ result = runner.invoke(mod.app, ["version"])19+20+ assert result.exit_code == 021+ assert "My CLI Version 1.0" in result.output22+23+24+def test_users_help():25+ result = runner.invoke(mod.app, ["users", "--help"])26+27+ assert result.exit_code == 028+29+ assert "add" in result.output30+ assert "delete" in result.output31+32+33+def test_add_user():34+ result = runner.invoke(mod.app, ["users", "add", "Camila"])35+36+ assert result.exit_code == 037+ assert "Adding user: Camila" in result.output38+39+40+def test_delete_user():41+ result = runner.invoke(mod.app, ["users", "delete", "Camila"])42+43+ assert result.exit_code == 044+ assert "Deleting user: Camila" in result.outputmodified:typer/main.py+9 added-6 removed
491 unmodified lines492 rich_markup_mode=rich_markup_mode,493 )494 if sub_group.name:495 commands[sub_group.name] = sub_group496+ else:496- elif sub_group.callback:497- import warnings497+ if sub_group.callback:498+ import warnings499 499- warnings.warn(500- "The 'callback' parameter is not supported by Typer when using `add_typer` without a name",501- stacklevel=5,502- )500+ warnings.warn(501+ "The 'callback' parameter is not supported by Typer when using `add_typer` without a name",502+ stacklevel=5,503+ )504+ for sub_command_name, sub_command in sub_group.commands.items():505+ commands[sub_command_name] = sub_command506 solved_info = solve_typer_info_defaults(group_info)507 (508 params,509 convertors,630 unmodified linesmodified:mkdocs.yml+1 added
132 unmodified lines133 - tutorial/testing.md134 - tutorial/using-click.md135 - tutorial/package.md136 - tutorial/exceptions.md137+ - tutorial/one-file-per-command.md138 - tutorial/typer-command.md139 - Resources:140 - resources/index.md141 - help-typer.md97 unmodified lines