Skip to content
Myr

✨ 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

15 files+469 added−6 removed

added:docs/tutorial/one-file-per-command.md+144 added
1# One File Per Command23When your CLI application grows, you can split it into multiple files and modules. This pattern helps maintain a clean and organized code structure. ✨45This tutorial will show you how to use `add_typer` to create sub commands and organize your commands in multiple files.67We will create a simple CLI with the following commands:89- `version`10- `users add NAME`11- `users delete NAME`1213## CLI structure1415Here is the structure we'll be working with:1617```text18mycli/19├── __init__.py20├── main.py21├── users/22│ ├── __init__.py23│ ├── add.py24│ └── delete.py25└── version.py26```2728`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:2930- `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.3334## Implementation3536Let's start implementing our CLI! 🚀3738We'll create the `version` module, the `main` module, and the `users` package.3940### Version Module (`version.py`)4142Let's start by creating the `version` module. This module will contain the `version` command.4344{* docs_src/one_file_per_command/version.py *}4546In this file we are creating a new Typer app instance for the `version` command.4748This 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()`.4950Let's see that next!5152### Main Module (`main.py`)5354The main module will be the entry point of the application. It will import the version module and the users module.5556/// tip5758We'll see how to implement the users module in the next section.5960///6162{* docs_src/one_file_per_command/main.py hl[8,9] *}6364In this module, we import the `version` and `users` modules and add them to the main app using `app.add_typer()`.6566For the `users` module, we specify the name as `"users"` to group the commands under the `users` sub-command.6768Notice 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.6970But 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. 😅7172/// tip7374If you want a command to group the included commands in a sub-app, add a name.7576If 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`. 🤓7778///7980Let's now create the `users` module with the `add` and `delete` commands.8182### Users Add Command (`users/add.py`)8384{* docs_src/one_file_per_command/users/add.py *}8586Like 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.8788### Users Delete Command (`users/delete.py`)8990{* docs_src/one_file_per_command/users/delete.py *}9192And 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.9394### Users' app (`users/__init__.py`)9596Finally, we need to create an `__init__.py` file in the `users` directory to define the `users` app.9798{* docs_src/one_file_per_command/users/__init__.py *}99100Similarly 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.101102## Running the Application103104Now we are ready to run the application! 😎105106To run the application, you can execute it as a Python module:107108<div class="termy">109110```console111$ python -m mycli.main version112113My CLI Version 1.0114115$ python -m mycli.main users add Camila116117Adding user: Camila118```119120</div>121122And if you built a package and installed your app, you can then use the `mycli` command:123124<div class="termy">125126```console127$ mycli version128129My CLI Version 1.0130131$ mycli users add Camila132133Adding user: Camila134```135136</div>137138## Callbacks139140Have 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.141142If 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. 🤓143144In 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
1import typer23from .add import app as add_app4from .delete import app as delete_app56app = typer.Typer()78app.add_typer(add_app)9app.add_typer(delete_app)
added:docs_src/one_file_per_command/users/add.py+8 added
1import typer23app = typer.Typer()456@app.command()7def add(name: str):8 print(f"Adding user: {name}")
added:docs_src/one_file_per_command/users/delete.py+8 added
1import typer23app = typer.Typer()456@app.command()7def 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
1import typer23from .users import app as users_app4from .version import app as version_app56app = typer.Typer()78app.add_typer(version_app)9app.add_typer(users_app, name="users")101112if __name__ == "__main__":13 app()
added:docs_src/one_file_per_command/version.py+8 added
1import typer23app = typer.Typer()456@app.command()7def version():8 print("My CLI Version 1.0")
added:tests/assets/cli/extended_app_cli.py+31 added
1import typer23sub_sub_app = typer.Typer()456@sub_sub_app.command()7def sub_sub_command():8 typer.echo("sub_sub_command")91011sub_app = typer.Typer()12sub_app.add_typer(sub_sub_app, name="sub")131415@sub_app.command()16def hello():17 typer.echo("hello there")181920@sub_app.command()21def bye():22 typer.echo("bye bye")232425cli = typer.Typer()26cli.add_typer(sub_app)272829@cli.command()30def top():31 typer.echo("top")
added:tests/assets/cli/extended_empty_app_cli.py+15 added
1import typer23cli = typer.Typer()4sub_app = typer.Typer()5cli.add_typer(sub_app)678@sub_app.command()9def hello():10 typer.echo("hello there")111213@sub_app.command()14def bye():15 typer.echo("bye bye")
added:tests/test_cli/test_extending_app.py+120 added
1import subprocess2import sys345def 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.stdout242526def 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.stdout434445def 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.stdout626364def 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.stdout818283def 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.stdout101102103def 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.stdout
added:tests/test_cli/test_extending_empty_app.py+59 added
1import subprocess2import sys345def 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.stdout222324def 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.stdout414243def 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.stdout
added:tests/test_tutorial/test_one_file_per_command/__init__.py
added:tests/test_tutorial/test_one_file_per_command/test_tutorial.py+44 added
1from typer.testing import CliRunner23from docs_src.one_file_per_command import main as mod45runner = CliRunner()678def test_help():9 result = runner.invoke(mod.app, ["--help"])1011 assert result.exit_code == 01213 assert "version" in result.output14 assert "users" in result.output151617def test_version():18 result = runner.invoke(mod.app, ["version"])1920 assert result.exit_code == 021 assert "My CLI Version 1.0" in result.output222324def test_users_help():25 result = runner.invoke(mod.app, ["users", "--help"])2627 assert result.exit_code == 02829 assert "add" in result.output30 assert "delete" in result.output313233def test_add_user():34 result = runner.invoke(mod.app, ["users", "add", "Camila"])3536 assert result.exit_code == 037 assert "Adding user: Camila" in result.output383940def test_delete_user():41 result = runner.invoke(mod.app, ["users", "delete", "Camila"])4243 assert result.exit_code == 044 assert "Deleting user: Camila" in result.output
modified:typer/main.py+9 added-6 removed
491 unmodified lines
492 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 warnings499499 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 lines
modified:mkdocs.yml+1 added
132 unmodified lines
133 - 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.md
97 unmodified lines