:memo: Add docs for Callbacks and One or Multiple commands, with docs, tests, bug fixes.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parents 13819bf, 6ccdbb8 · Browse files · 17 files·+585 added−12 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+585 added−12 removed
- tests:+212 added−0 removed
- other:+373 added−12 removed
Provenance
- Commit
439fb06- Tree
d7379d7- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
13819bf- Parent 2
6ccdbb8
17 files changed+585 added−12 removed
added:docs/src/commands/callback/tutorial001.py+36 added
1+import typer2+3+app = typer.Typer()4+state = {"verbose": False}5+6+7+@app.command()8+def create(username: str):9+ if state["verbose"]:10+ typer.echo("About to create a user")11+ typer.echo(f"Creating user: {username}")12+ if state["verbose"]:13+ typer.echo("Just created a user")14+15+16+@app.command()17+def delete(username: str):18+ if state["verbose"]:19+ typer.echo("About to delete a user")20+ typer.echo(f"Deleting user: {username}")21+ if state["verbose"]:22+ typer.echo("Just deleted a user")23+24+25+@app.callback()26+def main(verbose: bool = False):27+ """28+ Manage users in the awesome CLI app.29+ """30+ if verbose:31+ typer.echo("Will write verbose output")32+ state["verbose"] = True33+34+35+if __name__ == "__main__":36+ app()added:docs/src/commands/callback/tutorial002.py+17 added
1+import typer2+3+4+def callback():5+ typer.echo("Running a command")6+7+8+app = typer.Typer(callback=callback)9+10+11+@app.command()12+def create(name: str):13+ typer.echo(f"Creating user: {name}")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/commands/callback/tutorial003.py+22 added
1+import typer2+3+4+def callback():5+ typer.echo("Running a command")6+7+8+app = typer.Typer(callback=callback)9+10+11+@app.callback()12+def new_callback():13+ typer.echo("Override callback, running a command")14+15+16+@app.command()17+def create(name: str):18+ typer.echo(f"Creating user: {name}")19+20+21+if __name__ == "__main__":22+ app()added:docs/src/commands/callback/tutorial004.py+23 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.callback()7+def callback():8+ """9+ Manage users CLI app.10+11+ Use it with the create command.12+ 13+ A new user with the given NAME will be created.14+ """15+16+17+@app.command()18+def create(name: str):19+ typer.echo(f"Creating user: {name}")20+21+22+if __name__ == "__main__":23+ app()added:docs/src/commands/one_or_multiple/tutorial001.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create():8+ typer.echo("Creating user: Hiro Hamada")9+10+11+@app.callback()12+def callback():13+ pass14+15+16+if __name__ == "__main__":17+ app()added:docs/src/commands/one_or_multiple/tutorial002.py+21 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create():8+ typer.echo("Creating user: Hiro Hamada")9+10+11+@app.callback()12+def callback():13+ """14+ Creates a single user Hiro Hamada.15+16+ In the next version it will create 5 users more.17+ """18+19+20+if __name__ == "__main__":21+ app()added:docs/tutorial/commands/callback.md+164 added
1+When you create an `app = typer.Typer()` it works as a group of commands.2+3+And you can create multiple commands with it.4+5+Each of those commands can have their own *CLI parameters*.6+7+But as those *CLI parameters* are handled by each of those commands, they don't allow us to create *CLI parameters* for the main CLI application itself.8+9+But we can use `@app.callback()` for that.10+11+It's very similar to `@app.command()`, but it declares the *CLI parameters* for the main CLI application (before the commands):12+13+```Python hl_lines="25 26 27 28 29 30 31 32"14+{!./src/commands/callback/tutorial001.py!}15+```16+17+Here we create a `callback` with a `--verbose` *CLI option*.18+19+!!! tip20+ After getting the `--verbose` flag, we modify a global `state`, and we use it in the other commands.21+22+ There are other ways to achieve the same, but this will suffice for this example.23+24+And as we added a docstring to the callback function, by default it will be extracted and used as the help text.25+26+Check it:27+28+<div class="termy">29+30+```console31+// Check the help32+$ python main.py --help33+34+// Notice the main help text, extracted from the callback function: "Manage users in the awesome CLI app."35+Usage: main.py [OPTIONS] COMMAND [ARGS]...36+37+ Manage users in the awesome CLI app.38+39+Options:40+ --verbose / --no-verbose41+ --install-completion Install completion for the current shell.42+ --show-completion Show completion for the current shell, to copy it or customize the installation.43+ --help Show this message and exit.44+45+Commands:46+ create47+ delete48+49+// Check the new top level CLI option --verbose50+51+// Try it normally52+$ python main.py create Camila53+54+Creating user: Camila55+56+// And now with --verbose57+$ python main.py --verbose create Camila58+59+Will write verbose output60+About to create a user61+Creating user: Camila62+Just created a user63+64+// Notice that --verbose belongs to the callback, it has to go before create or delete ⛔️65+$ python main.py create --verbose Camila66+67+Usage: main.py create [OPTIONS] USERNAME68+Try "main.py create --help" for help.69+70+Error: no such option: --verbose71+```72+73+</div>74+75+## Adding a callback on creation76+77+It's also possible to add a callback when creating the `typer.Typer()` app:78+79+```Python hl_lines="4 5 8"80+{!./src/commands/callback/tutorial002.py!}81+```82+83+That achieves the same as with `@app.callback()`.84+85+Check it:86+87+<div class="termy">88+89+```console90+$ python main.py create Camila91+92+Running a command93+Creating user: Camila94+```95+96+</div>97+98+## Overriding a callback99+100+If you added a callback when creating the `typer.Typer()` app, it's possible to override it with `@app.callback()`:101+102+```Python hl_lines="11 12 13"103+{!./src/commands/callback/tutorial003.py!}104+```105+106+Now `new_callback()` will be the one used.107+108+Check it:109+110+<div class="termy">111+112+```console113+$ python main.py create Camila114+115+// Notice that the message is the one from new_callback()116+Override callback, running a command117+Creating user: Camila118+```119+120+</div>121+122+## Adding a callback only for documentation123+124+You can also add a callback just to add the documentation in the docstring.125+126+It can be convenient especially if you have several lines of text, as the indentation will be automatically handled for you:127+128+```Python hl_lines="8 9 10 11 12 13 14 15 16"129+{!./src/commands/callback/tutorial004.py!}130+```131+132+Now the callback will be used mainly to extract the docstring for the help text.133+134+Check it:135+136+<div class="termy">137+138+```console139+$ python main.py --help140+141+// Notice all the help text extracted from the callback docstring142+Usage: main.py [OPTIONS] COMMAND [ARGS]...143+144+ Manage users CLI app.145+146+ Use it with the create command.147+148+ A new user with the given NAME will be created.149+150+Options:151+ --install-completion Install completion for the current shell.152+ --show-completion Show completion for the current shell, to copy it or customize the installation.153+ --help Show this message and exit.154+155+Commands:156+ create157+158+// And it just works as normally159+$ python main.py create Camila160+161+Creating user: Camila162+```163+164+</div>modified:docs/tutorial/commands/one-or-multiple.md+72 added-12 removed
12344567831 unmodified lines4041424344444546474825 unmodified lines747576777879787981828380818582838485878889868791888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151You might have noticed that if you create a single command, as in the first example:
```Python hl_lines="3 6 12"{!./src/commands/tutorial001.py!}{!./src/commands/index/tutorial001.py!}```
**Typer** is smart enough to create a CLI application with that single function as the main CLI application, not as a command/subcommand:
31 unmodified lines
But if you add multiple commands, **Typer** will create one *CLI command* for each one of them:
```Python hl_lines="6 11"{!./src/commands/tutorial002.py!}{!./src/commands/index/tutorial002.py!}```
Here we have 2 commands `create` and `delete`:
25 unmodified lines```
</div>
!!! tip This is **Typer**'s behavior by default, but you could still create a CLI application with one single command, like:## One command and one callback
``` $ python main.py main ```If you want to create a CLI app with one single command but you still want it to be a command/subcommand you can just add a callback:
instead of just:```Python hl_lines="11 12 13"{!./src/commands/one_or_multiple/tutorial001.py!}```
``` $ python main.py ```And now your CLI program will have a single command.
You will learn more about this in the section about application Callbacks.Check it:
<div class="termy">
```console// Check the help$ python main.py --help
// Notice the single command createUsage: main.py [OPTIONS] COMMAND [ARGS]...
Options: --install-completion Install completion for the current shell. --show-completion Show completion for the current shell, to copy it or customize the installation. --help Show this message and exit.
Commands: create
// Try it$ python main.py create
Creating user: Hiro Hamada```
</div>
## Using the callback to document
Now that you are using a callback just to have a single command, you might as well use it to add documentation for your app:
```Python hl_lines="11 12 13 14 15 16 17"{!./src/commands/one_or_multiple/tutorial002.py!}```
And now the docstring from the callback will be used as the help text:
<div class="termy">
```console$ python main.py --help
// Notice the help text from the docstringUsage: main.py [OPTIONS] COMMAND [ARGS]...
Creates a single user Hiro Hamada.
In the next version it will create 5 users more.
Options: --install-completion Install completion for the current shell. --show-completion Show completion for the current shell, to copy it or customize the installation. --help Show this message and exit.
Commands: create
// And it still works the same, the callback does nothing$ python main.py create
Creating user: Hiro Hamada```
</div>added:tests/test_tutorial/test_commands/test_callback/__init__.py
added:tests/test_tutorial/test_commands/test_callback/test_tutorial001.py+61 added
1+import subprocess2+from commands.callback import tutorial001 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_help():12+ result = runner.invoke(app, ["--help"])13+ assert result.exit_code == 014+ assert "Manage users in the awesome CLI app." in result.output15+ assert "--verbose / --no-verbose" in result.output16+17+18+def test_create():19+ result = runner.invoke(app, ["create", "Camila"])20+ assert result.exit_code == 021+ assert "Creating user: Camila" in result.output22+23+24+def test_create_verbose():25+ result = runner.invoke(app, ["--verbose", "create", "Camila"])26+ assert result.exit_code == 027+ assert "Will write verbose output" in result.output28+ assert "About to create a user" in result.output29+ assert "Creating user: Camila" in result.output30+ assert "Just created a user" in result.output31+32+33+def test_delete():34+ result = runner.invoke(app, ["delete", "Camila"])35+ assert result.exit_code == 036+ assert "Deleting user: Camila" in result.output37+38+39+def test_delete_verbose():40+ result = runner.invoke(app, ["--verbose", "delete", "Camila"])41+ assert result.exit_code == 042+ assert "Will write verbose output" in result.output43+ assert "About to delete a user" in result.output44+ assert "Deleting user: Camila" in result.output45+ assert "Just deleted a user" in result.output46+47+48+def test_wrong_verbose():49+ result = runner.invoke(app, ["delete", "--verbose", "Camila"])50+ assert result.exit_code != 051+ assert "Error: no such option: --verbose" in result.output52+53+54+def test_script():55+ result = subprocess.run(56+ ["coverage", "run", mod.__file__, "--help"],57+ stdout=subprocess.PIPE,58+ stderr=subprocess.PIPE,59+ encoding="utf-8",60+ )61+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_callback/test_tutorial002.py+25 added
1+import subprocess2+from commands.callback import tutorial002 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_app():12+ result = runner.invoke(app, ["create", "Camila"])13+ assert result.exit_code == 014+ assert "Running a command" in result.output15+ assert "Creating user: Camila" in result.output16+17+18+def test_script():19+ result = subprocess.run(20+ ["coverage", "run", mod.__file__, "--help"],21+ stdout=subprocess.PIPE,22+ stderr=subprocess.PIPE,23+ encoding="utf-8",24+ )25+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_callback/test_tutorial003.py+30 added
1+import subprocess2+from commands.callback import tutorial003 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_app():12+ result = runner.invoke(app, ["create", "Camila"])13+ assert result.exit_code == 014+ assert "Override callback, running a command" in result.output15+ assert "Running a command" not in result.output16+ assert "Creating user: Camila" in result.output17+18+19+def test_for_coverage():20+ mod.callback()21+22+23+def test_script():24+ result = subprocess.run(25+ ["coverage", "run", mod.__file__, "--help"],26+ stdout=subprocess.PIPE,27+ stderr=subprocess.PIPE,28+ encoding="utf-8",29+ )30+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_callback/test_tutorial004.py+32 added
1+import subprocess2+from commands.callback import tutorial004 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_help():12+ result = runner.invoke(app, ["--help"])13+ assert result.exit_code == 014+ assert "Manage users CLI app." in result.output15+ assert "Use it with the create command." in result.output16+ assert "A new user with the given NAME will be created." in result.output17+18+19+def test_app():20+ result = runner.invoke(app, ["create", "Camila"])21+ assert result.exit_code == 022+ assert "Creating user: Camila" in result.output23+24+25+def test_script():26+ result = subprocess.run(27+ ["coverage", "run", mod.__file__, "--help"],28+ stdout=subprocess.PIPE,29+ stderr=subprocess.PIPE,30+ encoding="utf-8",31+ )32+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_one_or_multiple/__init__.py
added:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial001.py+31 added
1+import subprocess2+from commands.one_or_multiple import tutorial001 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_help():12+ result = runner.invoke(app, ["--help"])13+ assert result.exit_code == 014+ assert "Commands:" in result.output15+ assert "create" in result.output16+17+18+def test_command():19+ result = runner.invoke(app, ["create"])20+ assert result.exit_code == 021+ assert "Creating user: Hiro Hamada" in result.output22+23+24+def test_script():25+ result = subprocess.run(26+ ["coverage", "run", mod.__file__, "--help"],27+ stdout=subprocess.PIPE,28+ stderr=subprocess.PIPE,29+ encoding="utf-8",30+ )31+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_commands/test_one_or_multiple/test_tutorial002.py+33 added
1+import subprocess2+from commands.one_or_multiple import tutorial002 as mod3+4+from typer.testing import CliRunner5+6+app = mod.app7+8+runner = CliRunner()9+10+11+def test_help():12+ result = runner.invoke(app, ["--help"])13+ assert result.exit_code == 014+ assert "Creates a single user Hiro Hamada." in result.output15+ assert "In the next version it will create 5 users more." in result.output16+ assert "Commands:" in result.output17+ assert "create" in result.output18+19+20+def test_command():21+ result = runner.invoke(app, ["create"])22+ assert result.exit_code == 023+ assert "Creating user: Hiro Hamada" in result.output24+25+26+def test_script():27+ result = subprocess.run(28+ ["coverage", "run", mod.__file__, "--help"],29+ stdout=subprocess.PIPE,30+ stderr=subprocess.PIPE,31+ encoding="utf-8",32+ )33+ assert "Usage" in result.stdoutmodified:typer/main.py+1 added
224 unmodified lines225 click_completion.init()226 click_install_param, click_show_param = get_install_completion_arguments()227 if (228 typer_instance.registered_callback229+ or typer_instance.info.callback230 or typer_instance.registered_groups231 or len(typer_instance.registered_commands) > 1232 ):233 # Create a Group500 unmodified lines