:memo: Add docs for callbacks and one or multiple commands
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 Sebastián Ramírez · parent 13819bf · Browse files · 8 files·+372 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
8 files+372 added−12 removed
- other:+372 added−12 removed
Provenance
- Commit
56bb257- Tree
40f2615- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
Sebastián Ramírez <tiangolo@gmail.com>- Parent
13819bf
8 files changed+372 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>