:sparkles: Add docs for subcommands, examples, 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 d12d00e, be3f329 · Browse files · 53 files·+2542 added−36 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
53 files+2542 added−36 removed
- tests:+745 added−0 removed
- other:+1797 added−36 removed
Provenance
- Commit
13819bf- Tree
038808c- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
d12d00e- Parent 2
be3f329
53 files changed+2542 added−36 removed
added:docs/src/subcommands/callback_override/tutorial001.py+20 added
1+import typer2+3+app = typer.Typer()4+5+users_app = typer.Typer()6+app.add_typer(users_app, name="users")7+8+9+@users_app.callback()10+def users_callback():11+ typer.echo("Running a users command")12+13+14+@users_app.command()15+def create(name: str):16+ typer.echo(f"Creating user: {name}")17+18+19+if __name__ == "__main__":20+ app()added:docs/src/subcommands/callback_override/tutorial002.py+20 added
1+import typer2+3+app = typer.Typer()4+5+6+def users_callback():7+ typer.echo("Running a users command")8+9+10+users_app = typer.Typer(callback=users_callback)11+app.add_typer(users_app, name="users")12+13+14+@users_app.command()15+def create(name: str):16+ typer.echo(f"Creating user: {name}")17+18+19+if __name__ == "__main__":20+ app()added:docs/src/subcommands/callback_override/tutorial003.py+25 added
1+import typer2+3+app = typer.Typer()4+5+6+def default_callback():7+ typer.echo("Running a users command")8+9+10+users_app = typer.Typer(callback=default_callback)11+app.add_typer(users_app, name="users")12+13+14+@users_app.callback()15+def user_callback():16+ typer.echo("Callback override, running users command")17+18+19+@users_app.command()20+def create(name: str):21+ typer.echo(f"Creating user: {name}")22+23+24+if __name__ == "__main__":25+ app()added:docs/src/subcommands/callback_override/tutorial004.py+31 added
1+import typer2+3+app = typer.Typer()4+5+6+def default_callback():7+ typer.echo("Running a users command")8+9+10+users_app = typer.Typer(callback=default_callback)11+12+13+def callback_for_add_typer():14+ typer.echo("I have the high land! Running users command")15+16+17+app.add_typer(users_app, name="users", callback=callback_for_add_typer)18+19+20+@users_app.callback()21+def user_callback():22+ typer.echo("Callback override, running users command")23+24+25+@users_app.command()26+def create(name: str):27+ typer.echo(f"Creating user: {name}")28+29+30+if __name__ == "__main__":31+ app()added:docs/src/subcommands/name_help/tutorial001.py+15 added
1+import typer2+3+app = typer.Typer()4+5+users_app = typer.Typer()6+app.add_typer(users_app, name="users", help="Manage users in the app.")7+8+9+@users_app.command()10+def create(name: str):11+ typer.echo(f"Creating user: {name}")12+13+14+if __name__ == "__main__":15+ app()added:docs/src/subcommands/name_help/tutorial002.py+22 added
1+import typer2+3+app = typer.Typer()4+5+users_app = typer.Typer()6+app.add_typer(users_app)7+8+9+@users_app.callback()10+def users():11+ """12+ Manage users in the app.13+ """14+15+16+@users_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/subcommands/name_help/tutorial003.py+22 added
1+import typer2+3+app = typer.Typer()4+5+6+def users():7+ """8+ Manage users in the app.9+ """10+11+12+users_app = typer.Typer(callback=users)13+app.add_typer(users_app)14+15+16+@users_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/subcommands/name_help/tutorial004.py+29 added
1+import typer2+3+app = typer.Typer()4+5+6+def old_callback():7+ """8+ Old callback help.9+ """10+11+12+users_app = typer.Typer(callback=old_callback)13+app.add_typer(users_app)14+15+16+@users_app.callback()17+def users():18+ """19+ Manage users in the app.20+ """21+22+23+@users_app.command()24+def create(name: str):25+ typer.echo(f"Creating user: {name}")26+27+28+if __name__ == "__main__":29+ app()added:docs/src/subcommands/name_help/tutorial005.py+37 added
1+import typer2+3+app = typer.Typer()4+5+6+def old_callback():7+ """8+ Old callback help.9+ """10+11+12+users_app = typer.Typer(callback=old_callback)13+14+15+def new_users():16+ """17+ I have the highland! Create some users.18+ """19+20+21+app.add_typer(users_app, callback=new_users)22+23+24+@users_app.callback()25+def users():26+ """27+ Manage users in the app.28+ """29+30+31+@users_app.command()32+def create(name: str):33+ typer.echo(f"Creating user: {name}")34+35+36+if __name__ == "__main__":37+ app()added:docs/src/subcommands/name_help/tutorial006.py+37 added
1+import typer2+3+app = typer.Typer()4+5+6+def old_callback():7+ """8+ Old callback help.9+ """10+11+12+users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")13+14+15+def new_users():16+ """17+ I have the highland! Create some users.18+ """19+20+21+app.add_typer(users_app, callback=new_users)22+23+24+@users_app.callback()25+def users():26+ """27+ Manage users in the app.28+ """29+30+31+@users_app.command()32+def create(name: str):33+ typer.echo(f"Creating user: {name}")34+35+36+if __name__ == "__main__":37+ app()added:docs/src/subcommands/name_help/tutorial007.py+37 added
1+import typer2+3+app = typer.Typer()4+5+6+def old_callback():7+ """8+ Old callback help.9+ """10+11+12+users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")13+14+15+def new_users():16+ """17+ I have the highland! Create some users.18+ """19+20+21+app.add_typer(users_app, callback=new_users)22+23+24+@users_app.callback("call-users", help="Help from callback for users.")25+def users():26+ """27+ Manage users in the app.28+ """29+30+31+@users_app.command()32+def create(name: str):33+ typer.echo(f"Creating user: {name}")34+35+36+if __name__ == "__main__":37+ app()added:docs/src/subcommands/name_help/tutorial008.py+42 added
1+import typer2+3+app = typer.Typer()4+5+6+def old_callback():7+ """8+ Old callback help.9+ """10+11+12+users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")13+14+15+def new_users():16+ """17+ I have the highland! Create some users.18+ """19+20+21+app.add_typer(22+ users_app,23+ callback=new_users,24+ name="cake-sith-users",25+ help="Unlimited powder! Eh, users.",26+)27+28+29+@users_app.callback("call-users", help="Help from callback for users.")30+def users():31+ """32+ Manage users in the app.33+ """34+35+36+@users_app.command()37+def create(name: str):38+ typer.echo(f"Creating user: {name}")39+40+41+if __name__ == "__main__":42+ app()added:docs/src/subcommands/tutorial001/items.py+22 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(item: str):8+ typer.echo(f"Creating item: {item}")9+10+11+@app.command()12+def delete(item: str):13+ typer.echo(f"Deleting item: {item}")14+15+16+@app.command()17+def sell(item: str):18+ typer.echo(f"Selling item: {item}")19+20+21+if __name__ == "__main__":22+ app()added:docs/src/subcommands/tutorial001/main.py+11 added
1+import typer2+3+import items4+import users5+6+app = typer.Typer()7+app.add_typer(users.app, name="users")8+app.add_typer(items.app, name="items")9+10+if __name__ == "__main__":11+ app()added:docs/src/subcommands/tutorial001/users.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(user_name: str):8+ typer.echo(f"Creating user: {user_name}")9+10+11+@app.command()12+def delete(user_name: str):13+ typer.echo(f"Deleting user: {user_name}")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/subcommands/tutorial002/main.py+36 added
1+import typer2+3+app = typer.Typer()4+items_app = typer.Typer()5+app.add_typer(items_app, name="items")6+users_app = typer.Typer()7+app.add_typer(users_app, name="users")8+9+10+@items_app.command("create")11+def items_create(item: str):12+ typer.echo(f"Creating item: {item}")13+14+15+@items_app.command("delete")16+def items_delete(item: str):17+ typer.echo(f"Deleting item: {item}")18+19+20+@items_app.command("sell")21+def items_sell(item: str):22+ typer.echo(f"Selling item: {item}")23+24+25+@users_app.command("create")26+def users_create(user_name: str):27+ typer.echo(f"Creating user: {user_name}")28+29+30+@users_app.command("delete")31+def users_delete(user_name: str):32+ typer.echo(f"Deleting user: {user_name}")33+34+35+if __name__ == "__main__":36+ app()added:docs/src/subcommands/tutorial003/items.py+22 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(item: str):8+ typer.echo(f"Creating item: {item}")9+10+11+@app.command()12+def delete(item: str):13+ typer.echo(f"Deleting item: {item}")14+15+16+@app.command()17+def sell(item: str):18+ typer.echo(f"Selling item: {item}")19+20+21+if __name__ == "__main__":22+ app()added:docs/src/subcommands/tutorial003/lands.py+11 added
1+import typer2+3+import reigns4+import towns5+6+app = typer.Typer()7+app.add_typer(reigns.app, name="reigns")8+app.add_typer(towns.app, name="towns")9+10+if __name__ == "__main__":11+ app()added:docs/src/subcommands/tutorial003/main.py+13 added
1+import typer2+3+import items4+import lands5+import users6+7+app = typer.Typer()8+app.add_typer(users.app, name="users")9+app.add_typer(items.app, name="items")10+app.add_typer(lands.app, name="lands")11+12+if __name__ == "__main__":13+ app()added:docs/src/subcommands/tutorial003/reigns.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def conquer(name: str):8+ typer.echo(f"Conquering reign: {name}")9+10+11+@app.command()12+def destroy(name: str):13+ typer.echo(f"Destroying reign: {name}")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/subcommands/tutorial003/towns.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def found(name: str):8+ typer.echo(f"Founding town: {name}")9+10+11+@app.command()12+def burn(name: str):13+ typer.echo(f"Burning town: {name}")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/subcommands/tutorial003/users.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(user_name: str):8+ typer.echo(f"Creating user: {user_name}")9+10+11+@app.command()12+def delete(user_name: str):13+ typer.echo(f"Deleting user: {user_name}")14+15+16+if __name__ == "__main__":17+ app()added:docs/tutorial/subcommands/add-typer.md+169 added
1+We'll start with the core idea.2+3+To add a `typer.Typer()` app inside of another.4+5+## Manage items6+7+Let's imagine that you are creating a *CLI program* to manage items in some distant land.8+9+It could be in an `items.py` file with this:10+11+```Python hl_lines=""12+{!./src/subcommands/tutorial001/items.py!}13+```14+15+And you would use it like:16+17+<div class="termy">18+19+```console20+$ python items.py create Wand21+22+Creating item: Wand23+```24+25+</div>26+27+## Manage users28+29+But then you realize that you also have to manage users from your *CLI app*.30+31+It could be a file `users.py` with something like:32+33+```Python hl_lines=""34+{!./src/subcommands/tutorial001/users.py!}35+```36+37+And you would use it like:38+39+<div class="termy">40+41+```console42+$ python users.py create Camila43+44+Creating user: Camila45+```46+47+</div>48+49+## Put them together50+51+Both parts are similar. In fact, `items.py` and `users.py` both have commands `create` and `delete`.52+53+But we need them to be part of the same *CLI program*.54+55+In this case, as with `git remote`, we can put them together as subcommands in another `typer.Typer()` *CLI program*.56+57+Now create a `main.py` with:58+59+```Python hl_lines="3 4 7 8"60+{!./src/subcommands/tutorial001/main.py!}61+```62+63+Here's what we do in `main.py`:64+65+* Import the other Python modules (the files `users.py` and `items.py`).66+* Create the main `typer.Typer()` application.67+* Use `app.add_typer()` to include the `app` from `items.py` and `users.py`, each of those 2 was also created with `typer.Typer()`.68+* Define a `name` with the command that will be used for each of these "sub-Typers" to group their own commands.69+70+And now your *CLI program* has 2 commands:71+72+* `users`: with all of the commands (subcommands) in the `app` from `users.py`.73+* `items` with all the commands (subcommands) in the `app` from `items.py`.74+75+Check it:76+77+<div class="termy">78+79+```console80+// Check the help81+$ python main.py --help82+83+Usage: main.py [OPTIONS] COMMAND [ARGS]...84+85+Options:86+ --install-completion Install completion for the current shell.87+ --show-completion Show completion for the current shell, to copy it or customize the installation.88+ --help Show this message and exit.89+90+Commands:91+ items92+ users93+```94+95+</div>96+97+Now you have a *CLI program* with commands `items` and `users`, and they in turn have their own commands (subcommands).98+99+Let's check the `items` command:100+101+<div class="termy">102+103+```console104+// Check the help for items105+$ python main.py items --help106+107+// It shows its own commands (subcommands): create, delete, sell108+Usage: main.py items [OPTIONS] COMMAND [ARGS]...109+110+Options:111+ --help Show this message and exit.112+113+Commands:114+ create115+ delete116+ sell117+118+// Try it119+$ python main.py items create Wand120+121+Creating item: Wand122+123+$ python main.py items sell Vase124+125+Selling item: Vase126+```127+128+</div>129+130+!!! tip131+ Notice that we are still calling `$ python main.py` but now we are using the command `items`.132+133+And now check the command `users`, with all its subcommands:134+135+<div class="termy">136+137+```console138+$ python main.py users --help139+140+Usage: main.py users [OPTIONS] COMMAND [ARGS]...141+142+Options:143+ --help Show this message and exit.144+145+Commands:146+ create147+ delete148+149+// Try it150+$ python main.py users create Camila151+152+Creating user: Camila153+```154+155+</div>156+157+## Recap158+159+That's the core idea.160+161+You can just create `typer.Typer()` apps and add them inside one another.162+163+And you can do that with any levels of commands that you want.164+165+Do you need sub-sub-sub-subcommands? Go ahead, create all the `typer.Typer()`s you need and put them together with `app.add_typer()`.166+167+In the next sections we'll update this with more features, but you already have the core idea.168+169+This way, in the same spirit of Click, **Typer** applications are composable, each `typer.Typer()` can be a *CLI app* by itself, but it can also be added as a command group to another Typer app.added:docs/tutorial/subcommands/callback-override.md+104 added
1+When creating a **Typer** app you can define a callback function, it always executes and defines the *CLI arguments* and *CLI options* that go before a command.2+3+When adding a Typer app inside of another, the sub-Typer can also have its own callback.4+5+It can handle any *CLI parameters* that go before its own commands and execute any extra code:6+7+```Python hl_lines="9 10 11"8+{!./src/subcommands/callback_override/tutorial001.py!}9+```10+11+In this case it doesn't define any *CLI parameters*, it just writes a message.12+13+Check it:14+15+<div class="termy">16+17+```console18+$ python main.py users create Camila19+20+// Notice the first message is not created by the command function but by the callback21+Running a users command22+Creating user: Camila23+```24+25+</div>26+27+## Add a callback on creation28+29+It's also possible to add a callback when creating the `typer.Typer()` app that will be added to another Typer app:30+31+```Python hl_lines="6 7 10"32+{!./src/subcommands/callback_override/tutorial002.py!}33+```34+35+This achieves exactly the same as above, it's just another place to add the callback.36+37+Check it:38+39+<div class="termy">40+41+```console42+$ python main.py users create Camila43+44+Running a users command45+Creating user: Camila46+```47+48+</div>49+50+## Overriding the callback on creation51+52+If a callback was added when creating the `typer.Typer()` app, it's possible to override it with a new one using `@app.callback()`.53+54+This is the same information you saw on the section about <a href="https://typer.tiangolo.com/tutorial/commands/callback/" target="_blank">Commands - Typer Callback</a>, and it applies the same for sub-Typer apps:55+56+```Python hl_lines="6 7 10 14 15 16"57+{!./src/subcommands/callback_override/tutorial003.py!}58+```59+60+Here we had defined a callback when creating the `typer.Typer()` sub-app, but then we override it with a new callback with the function `user_callback()`.61+62+As `@app.callback()` takes precedence over `typer.Typer(callback=some_function)`, now our CLI app will use this new callback.63+64+Check it:65+66+<div class="termy">67+68+```console69+$ python main.py users create Camila70+71+// Notice the message from the new callback72+Callback override, running users command73+Creating user: Camila74+```75+76+</div>77+78+## Overriding the callback when adding a sub-Typer79+80+Lastly, you can override the callback defined anywhere else when adding a sub-Typer with `app.add_typer()` using the `callback` parameter.81+82+This has the highest priority:83+84+```Python hl_lines="13 14 17"85+{!./src/subcommands/callback_override/tutorial004.py!}86+```87+88+Notice that the precedence goes to `app.add_typer()` and is not affected by the order of execution. There's another callback defined below, but the one from `app.add_typer()` wins.89+90+Now when you use the CLI program it will use the new callback function `callback_for_add_typer()`.91+92+Check it:93+94+<div class="termy">95+96+```console97+$ python users create Camila98+99+// Notice the message from the callback added in add_typer()100+I have the high land! Running users command101+Creating user: Camila102+```103+104+</div>added:docs/tutorial/subcommands/index.md+39 added
1+You read before how to create a program with <a href="https://typer.tiangolo.com/tutorial/commands/" target="_blank">Commands</a>.2+3+Now we'll see how to create a *CLI program* with commands that have their own subcommands. Also known as command groups.4+5+For example, the *CLI program* `git` has a command `remote`.6+7+But `git remote`, in turn, has its own subcommands, like `add`:8+9+<div class="termy">10+11+```console12+// git remote alone shows the current remote repositories13+$ git remote14+15+origin16+17+// Use -v to make it verbose and show more info18+$ git remote -v19+20+origin git@github.com:yourusername/typer.git (fetch)21+origin git@github.com:yourusername/typer.git (push)22+23+// git remote add takes 2 CLI arguments, a name and URL24+$ git remote add upstream https://github.com/tiangolo/typer.git25+26+// Doesn't output anything, but now you have another remote repository called upstream27+28+// Now check again29+$ git remote -v30+31+origin git@github.com:yourusername/typer.git (fetch)32+origin git@github.com:yourusername/typer.git (push)33+upstream https://github.com/tiangolo/typer.git (fetch)34+upstream https://github.com/tiangolo/typer.git (push)35+```36+37+</div>38+39+In the next sections we'll see how to create subcommands like these.added:docs/tutorial/subcommands/name-and-help.md+463 added
1+When adding a Typer app to another we have seen how to set the `name` to use for the command.2+3+For example to set the command to `users`:4+5+```Python6+app.add_typer(users.app, name="users")7+```8+9+## Add a help text10+11+We can also set the `help` while adding a Typer:12+13+```Python hl_lines="6"14+{!./src/subcommands/name_help/tutorial001.py!}15+```16+17+And then we get that help text for that command in the *CLI program*:18+19+<div class="termy">20+21+```console22+// Check the main help23+$ python main.py --help24+25+Usage: main.py [OPTIONS] COMMAND [ARGS]...26+27+Options:28+ --install-completion Install completion for the current shell.29+ --show-completion Show completion for the current shell, to copy it or customize the installation.30+ --help Show this message and exit.31+32+Commands:33+ users Manage users in the app.34+35+// Check the help for the users command36+$ python main.py users --help37+38+Usage: main.py users [OPTIONS] COMMAND [ARGS]...39+40+ Manage users in the app.41+42+Options:43+ --help Show this message and exit.44+45+Commands:46+ create47+```48+49+</div>50+51+We can set the `name` and `help` in several places, each one taking precedence over the other, overriding the previous value.52+53+Let's see those locations.54+55+!!! tip56+ There are other attributes that can be set in that same way in the same places we'll see next.57+58+ But those are documented later in another section.59+60+## Inferring name and help from callback61+62+### Inferring a command's name and help63+64+When you create a command with `@app.command()`, by default, it generates the name from the function name.65+66+And by default, the help text is extracted from the function's docstring.67+68+For example:69+70+```Python71+@app.command()72+def create(item: str):73+ """74+ Create an item.75+ """76+ typer.echo(f"Creating item: {item}")77+```78+79+...will create a command `create` with a help text of `Create an item`.80+81+### Inferring name and help from `@app.callback()`82+83+The same way, if you define a callback in a `typer.Typer()`, the help text is extracted from the callback function's docstring.84+85+And if that Typer app is added to another Typer app, the default name of the command is generated from the name of the callback function.86+87+Here's an example:88+89+```Python hl_lines="6 9 10 11 12 13"90+{!./src/subcommands/name_help/tutorial002.py!}91+```92+93+Notice that now we added the sub-Typer without specifying a `name` nor a `help`.94+95+They are now inferred from the callback function.96+97+The command name will be the same callback function's name: `users`.98+99+And the help text for that `users` command will be the callback function's docstring: `Manage users in the app.`.100+101+Check it:102+103+<div class="termy">104+105+```console106+// Check the main help107+$ python main.py --help108+109+// Notice the command name "users" and the help text "Manage users in the app."110+Usage: main.py [OPTIONS] COMMAND [ARGS]...111+112+Options:113+ --install-completion Install completion for the current shell.114+ --show-completion Show completion for the current shell, to copy it or customize the installation.115+ --help Show this message and exit.116+117+Commands:118+ users Manage users in the app.119+120+// Check the help for the users command121+$ python main.py users --help122+123+// Notice the main description: "Manage users in the app."124+Usage: main.py users [OPTIONS] COMMAND [ARGS]...125+126+ Manage users in the app.127+128+Options:129+ --help Show this message and exit.130+131+Commands:132+ create133+```134+135+</div>136+137+### Name and help from callback parameter in `typer.Typer()`138+139+If you pass a `callback` parameter while creating a `typer.Typer(callback=some_function)` it will be used to infer the name and help text.140+141+This has the lowest priority, we'll see later what has a higher priority and can override it.142+143+Check the code:144+145+```Python hl_lines="6 7 8 9 12"146+{!./src/subcommands/name_help/tutorial003.py!}147+```148+149+This achieves exactly the same as the previous example.150+151+Check it:152+153+<div class="termy">154+155+```console156+// Check the main help157+$ python main.py --help158+159+// Notice the command name "users" and the help text "Manage users in the app."160+Usage: main.py [OPTIONS] COMMAND [ARGS]...161+162+Options:163+ --install-completion Install completion for the current shell.164+ --show-completion Show completion for the current shell, to copy it or customize the installation.165+ --help Show this message and exit.166+167+Commands:168+ users Manage users in the app.169+170+// Check the help for the users command171+$ python main.py users --help172+173+// Notice the main description: "Manage users in the app."174+Usage: main.py users [OPTIONS] COMMAND [ARGS]...175+176+ Manage users in the app.177+178+Options:179+ --help Show this message and exit.180+181+Commands:182+ create183+```184+185+</div>186+187+### Override a callback set in `typer.Typer()` with `@app.callback()`188+189+The same as with normal **Typer** apps, if you pass a `callback` to `typer.Typer(callback=some_function)` and then override it with `@app.callback()`, the name and help text will be inferred from the new callback:190+191+```Python hl_lines="16 17 18 19 20"192+{!./src/subcommands/name_help/tutorial004.py!}193+```194+195+Now the name of the command will be `users` instead of `old-callback`, and the help text will be `Manage users in the app.` instead of `Old callback help.`.196+197+Check it:198+199+<div class="termy">200+201+```console202+// Check the main help203+$ python main.py --help204+205+// Notice the command name "users" and the help text "Manage users in the app."206+Usage: main.py [OPTIONS] COMMAND [ARGS]...207+208+Options:209+ --install-completion Install completion for the current shell.210+ --show-completion Show completion for the current shell, to copy it or customize the installation.211+ --help Show this message and exit.212+213+Commands:214+ users Manage users in the app.215+216+// Check the help for the users command217+$ python main.py users --help218+219+// Notice the main description: "Manage users in the app."220+Usage: main.py users [OPTIONS] COMMAND [ARGS]...221+222+ Manage users in the app.223+224+Options:225+ --help Show this message and exit.226+227+Commands:228+ create229+```230+231+</div>232+233+### Infer name and help from callback in `app.add_typer()`234+235+If you override the callback in `app.add_typer()` when including a sub-app, the name and help will be inferred from this callback function.236+237+This takes precedence over inferring the name and help from a callback set in `@sub_app.callback()` and `typer.Typer(callback=sub_app_callback)`.238+239+Check the code:240+241+```Python hl_lines="15 16 17 18 21"242+{!./src/subcommands/name_help/tutorial005.py!}243+```244+245+Now the command will be `new-users` instead of `users`. And the help text will be `I have the highland! Create some users.` instead of the previous ones.246+247+Check it:248+249+<div class="termy">250+251+```console252+// Check the main help253+$ python main.py --help254+255+// Check the command new-users and its help text256+257+Usage: main.py [OPTIONS] COMMAND [ARGS]...258+259+Options:260+ --install-completion Install completion for the current shell.261+ --show-completion Show completion for the current shell, to copy it or customize the installation.262+ --help Show this message and exit.263+264+Commands:265+ new-users I have the highland! Create some users.266+267+// Now check the help for the new-users command268+$ python main.py new-users --help269+270+// Notice the help text271+Usage: main.py new-users [OPTIONS] COMMAND [ARGS]...272+273+ I have the highland! Create some users.274+275+Options:276+ --help Show this message and exit.277+278+Commands:279+ create280+```281+282+</div>283+284+### Enough inferring285+286+So, when inferring a name and help text, the precedence order from lowest priority to highest is:287+288+* `sub_app = typer.Typer(callback=some_function)`289+* `@sub_app.callback()`290+* `app.add_typer(sub_app, callback=new_function)`291+292+That's for inferring the name and help text from functions.293+294+But if you set the name and help text explicitly, that has a higher priority than these.295+296+## Set the name and help297+298+Let's now see the places where you can set the command name and help text, from lowest priority to highest.299+300+!!! tip301+ Setting the name and help text explicitly always has a higher precedence than inferring from a callback function.302+303+### Name and help in `typer.Typer()`304+305+You could have all the callbacks and overrides we defined before, but the name and help text was inferred from the function name and docstring.306+307+If you set it explicitly, that takes precedence over inferring.308+309+You can set it when creating a new `typer.Typer()`:310+311+```Python hl_lines="12"312+{!./src/subcommands/name_help/tutorial006.py!}313+```314+315+!!! info316+ The rest of the callbacks and overrides are there only to show you that they don't affect the name and help text when you set it explicitly.317+318+We set an explicit name `exp-users`, and an explicit help `Explicit help.`.319+320+So that will take precedence now.321+322+Check it:323+324+<div class="termy">325+326+```console327+// Check the main help328+$ python main.py --help329+330+// Notice the command name is exp-users and the help text is "Explicit help."331+Usage: main.py [OPTIONS] COMMAND [ARGS]...332+333+Options:334+ --install-completion Install completion for the current shell.335+ --show-completion Show completion for the current shell, to copy it or customize the installation.336+ --help Show this message and exit.337+338+Commands:339+ exp-users Explicit help.340+341+// Check the help for the exp-users command342+$ python main.py exp-users --help343+344+// Notice the main help text345+Usage: main.py exp-users [OPTIONS] COMMAND [ARGS]...346+347+ Explicit help.348+349+Options:350+ --help Show this message and exit.351+352+Commands:353+ create354+```355+356+</div>357+358+### Name and help in `@app.callback()`359+360+Any parameter that you use when creating a `typer.Typer()` app can be overridden in the parameters of `@app.callback()`.361+362+Continuing with the previous example, we now override the values in `@user_app.callback()`:363+364+```Python hl_lines="24"365+{!./src/subcommands/name_help/tutorial007.py!}366+```367+368+And now the command name will be `call-users` and the help text will be `Help from callback for users.`.369+370+Check it:371+372+<div class="termy">373+374+```console375+// Check the help376+$ python main.py --help377+378+// The command name now is call-users and the help text is "Help from callback for users.".379+Usage: main.py [OPTIONS] COMMAND [ARGS]...380+381+Options:382+ --install-completion Install completion for the current shell.383+ --show-completion Show completion for the current shell, to copy it or customize the installation.384+ --help Show this message and exit.385+386+Commands:387+ call-users Help from callback for users.388+389+// Check the call-users command help390+$ python main.py call-users --help391+392+// Notice the main help text393+Usage: main.py call-users [OPTIONS] COMMAND [ARGS]...394+395+ Help from callback for users.396+397+Options:398+ --help Show this message and exit.399+400+Commands:401+ create402+```403+404+</div>405+406+### Name and help in `app.add_typer()`407+408+And finally, with the highest priority, you can override all that by explicitly setting the `name` and `help` in `app.add_typer()`, just like we did on the first example above:409+410+```Python hl_lines="21"411+{!./src/subcommands/name_help/tutorial008.py!}412+```413+414+And now, with the highest priorities of them all, the command name will now be `cake-sith-users` and the help text will be `Unlimited powder! Eh, users.`.415+416+Check it:417+418+<div class="termy">419+420+```console421+// Check the help422+$ python main.py --help423+424+// Notice the command name cake-sith-users and the new help text "Unlimited powder! Eh, users."425+Usage: main.py [OPTIONS] COMMAND [ARGS]...426+427+Options:428+ --install-completion Install completion for the current shell.429+ --show-completion Show completion for the current shell, to copy it or customize the installation.430+ --help Show this message and exit.431+432+Commands:433+ cake-sith-users Unlimited powder! Eh, users.434+435+// And check the help for the command cake-sith-users436+$ python main.py cake-sith-users --help437+438+// Notice the main help text439+Usage: main.py cake-sith-users [OPTIONS] COMMAND [ARGS]...440+441+ Unlimited powder! Eh, users.442+443+Options:444+ --help Show this message and exit.445+446+Commands:447+ create448+```449+450+</div>451+452+## Recap453+454+The precedence to generate a command's name and help, from lowest priority to highest, is:455+456+* Implicitly inferred from `sub_app = typer.Typer(callback=some_function)`457+* Implicitly inferred from the callback function under `@sub_app.callback()`458+* Implicitly inferred from `app.add_typer(sub_app, callback=some_function)`459+* Explicitly set on `sub_app = typer.Typer(name="some-name", help="Some help.")`460+* Explicitly set on `@sub_app.callback("some-name", help="Some help.")`461+* Explicitly set on `app.add_typer(sub_app, name="some-name", help="Some help.")`462+463+So, `app.add_typer(sub_app, name="some-name", help="Some help.")` always wins.added:docs/tutorial/subcommands/nested-subcommands.md+295 added
1+We'll now see how these same ideas can be extended for deeply nested commands.2+3+Let's imagine that the same *CLI program* from the previous examples now needs to handle `lands`.4+5+But a land could be a `reign` or `town`.6+7+And each of those could have their own commands, like `create` and `delete`.8+9+## A CLI app for reigns10+11+Let's start with a file `reigns.py`:12+13+```Python hl_lines=""14+{!./src/subcommands/tutorial003/reigns.py!}15+```16+17+This is already a simple *CLI program* to manage reigns:18+19+<div class="termy">20+21+```console22+// Check the help23+$ python reigns.py --help24+25+Usage: reigns.py [OPTIONS] COMMAND [ARGS]...26+27+Options:28+ --install-completion Install completion for the current shell.29+ --show-completion Show completion for the current shell, to copy it or customize the installation.30+ --help Show this message and exit.31+32+Commands:33+ conquer34+ destroy35+36+// Try it37+$ python reigns.py conquer Cintra38+39+Conquering reign: Cintra40+41+$ python reigns.py destroy Mordor42+43+Destroying reign: Mordor44+```45+46+</div>47+48+## A CLI app for towns49+50+And now the equivalent for managing towns in `towns.py`:51+52+```Python hl_lines=""53+{!./src/subcommands/tutorial003/towns.py!}54+```55+56+With it, you can manage towns:57+58+<div class="termy">59+60+```console61+// Check the help62+$ python towns.py --help63+64+Usage: towns.py [OPTIONS] COMMAND [ARGS]...65+66+Options:67+ --install-completion Install completion for the current shell.68+ --show-completion Show completion for the current shell, to copy it or customize the installation.69+ --help Show this message and exit.70+71+Commands:72+ burn73+ found74+75+// Try it76+$ python towns.py found "New Asgard"77+78+Founding town: New Asgard79+80+$ python towns.py burn Vizima81+82+Burning town: Vizima83+```84+85+</div>86+87+## Manage the land in a CLI app88+89+Now let's put the `reigns` and `towns` together in the same *CLI program* in `lands.py`:90+91+```Python hl_lines=""92+{!./src/subcommands/tutorial003/lands.py!}93+```94+95+And now we have a single *CLI program* with a command (or command group) `reigns` that has its own commands. And another command `towns` with its own subcommands.96+97+Check it:98+99+<div class="termy">100+101+```console102+// Check the help103+$ python lands.py --help104+105+Usage: lands.py [OPTIONS] COMMAND [ARGS]...106+107+Options:108+ --install-completion Install completion for the current shell.109+ --show-completion Show completion for the current shell, to copy it or customize the installation.110+ --help Show this message and exit.111+112+Commands:113+ reigns114+ towns115+116+// We still have the help for reigns117+$ python lands.py reigns --help118+119+Usage: lands.py reigns [OPTIONS] COMMAND [ARGS]...120+121+Options:122+ --help Show this message and exit.123+124+Commands:125+ conquer126+ destroy127+128+// And the help for towns129+$ python lands.py towns --help130+131+Usage: lands.py towns [OPTIONS] COMMAND [ARGS]...132+133+Options:134+ --help Show this message and exit.135+136+Commands:137+ burn138+ found139+```140+141+</div>142+143+Now try it, manage the lands through the CLI:144+145+<div class="termy">146+147+```console148+// Try the reigns command149+$ python lands.py reigns conquer Gondor150+151+Conquering reign: Gondor152+153+$ python lands.py reigns destroy Nilfgaard154+155+Destroying reign: Nilfgaard156+157+// Try the towns command158+$ python lands.py towns found Springfield159+160+Founding town: Springfield161+162+$ python lands.py towns burn Atlantis163+164+Burning town: Atlantis165+```166+167+</div>168+169+## Deeply nested subcommands170+171+Now let's say that all these commands in the `lands.py` *CLI program* should be part of the previous *CLI program* we built in the first example.172+173+We want our *CLI program* to have these commands/command groups:174+175+* `users`:176+ * `create`177+ * `delete`178+* `items`:179+ * `create`180+ * `delete`181+ * `sell`182+* `lands`:183+ * `reigns`:184+ * `conquer`185+ * `destroy`186+ * `towns`:187+ * `found`188+ * `burn`189+190+This already is a quite deeply nested "tree" of commands/command groups.191+192+But to achieve that, we just have to add the `lands` **Typer** app to the same `main.py` file we already had:193+194+```Python hl_lines="4 10"195+{!./src/subcommands/tutorial003/main.py!}196+```197+198+And now we have everything in a single *CLI program*:199+200+<div class="termy">201+202+```console203+// Check the main help204+$ python main.py --help205+206+Usage: main.py [OPTIONS] COMMAND [ARGS]...207+208+Options:209+ --install-completion Install completion for the current shell.210+ --show-completion Show completion for the current shell, to copy it or customize the installation.211+ --help Show this message and exit.212+213+Commands:214+ items215+ lands216+ users217+218+// Try some users commands219+$ python main.py users create Camila220+221+Creating user: Camila222+223+// Now try some items commands224+$ python main.py items create Sword225+226+Creating item: Sword227+228+// And now some lands commands for reigns229+$ python main.py lands reigns conquer Gondor230+231+Conquering reign: Gondor232+233+// And for towns234+$ python main.py lands towns found Cartagena235+236+Founding town: Cartagena237+```238+239+</div>240+241+## Review the files242+243+Here are all the files if you want to review/copy them:244+245+`reigns.py`:246+247+```Python hl_lines=""248+{!./src/subcommands/tutorial003/reigns.py!}249+```250+251+`towns.py`:252+253+```Python hl_lines=""254+{!./src/subcommands/tutorial003/towns.py!}255+```256+257+`lands.py`:258+259+```Python hl_lines=""260+{!./src/subcommands/tutorial003/lands.py!}261+```262+263+`users.py`:264+265+```Python hl_lines=""266+{!./src/subcommands/tutorial003/users.py!}267+```268+269+`items.py`:270+271+```Python hl_lines=""272+{!./src/subcommands/tutorial003/items.py!}273+```274+275+`main.py`:276+277+```Python hl_lines=""278+{!./src/subcommands/tutorial003/main.py!}279+```280+281+!!! tip282+ All these files have an `if __name__ == "__main__"` block just to demonstrate how each of them can also be an independent *CLI app*.283+284+ But for your final application, only `main.py` would need it.285+286+## Recap287+288+That's it, you can just add **Typer** applications one inside another as much as you want and create complex *CLI programs* while writing simple code.289+290+You can probably achieve a simpler *CLI program* design that's easier to use than the example here. But if your requirements are complex, **Typer** helps you build your *CLI app* easily.291+292+!!! tip293+ Auto completion helps a lot, specially with complex programs.294+295+ Check the docs about adding auto completion to your *CLI apps*.added:docs/tutorial/subcommands/single-file.md+148 added
1+In some cases, it's possible that your application code needs to live on a single file.2+3+You can still use the same ideas:4+5+```Python hl_lines=""6+{!./src/subcommands/tutorial002/main.py!}7+```8+9+There are several things to notice here...10+11+## Apps at the top12+13+First, you can create `typer.Typer()` objects and add them to another one at the top.14+15+It doesn't have to be done after creating the subcommands:16+17+```Python hl_lines="4 5 6 7"18+{!./src/subcommands/tutorial002/main.py!}19+```20+21+You can add the commands (subcommands) to each `typer.Typer()` app later and it will still work.22+23+## Function names24+25+As you now have subcommands like `create` for `users` and for `items`, you can no longer call the functions with just the name, like `def create()`, because they would overwrite each other.26+27+So we use longer names:28+29+```Python hl_lines="11 16 21 26 31"30+{!./src/subcommands/tutorial002/main.py!}31+```32+33+## Command name34+35+We are naming the functions with longer names so that they don't overwrite each other.36+37+But we still want the subcommands to be `create`, `delete`, etc.38+39+To call them like:40+41+<div class="termy">42+43+```console44+// We want this ✔️45+$ python main.py items create46+```47+48+</div>49+50+instead of:51+52+<div class="termy">53+54+```console55+// We don't want this ⛔️56+$ python main.py items items-create57+```58+59+</div>60+61+So we pass the name we want to use for each subcommand as the function argument to the decorator:62+63+```Python hl_lines="10 15 20 25 30"64+{!./src/subcommands/tutorial002/main.py!}65+```66+67+## Check it68+69+It still works the same:70+71+72+<div class="termy">73+74+```console75+// Check the help76+$ python main.py --help77+78+Usage: main.py [OPTIONS] COMMAND [ARGS]...79+80+Options:81+ --install-completion Install completion for the current shell.82+ --show-completion Show completion for the current shell, to copy it or83+ customize the installation.84+ --help Show this message and exit.85+86+Commands:87+ items88+ users89+```90+91+</div>92+93+Check the `items` command:94+95+96+<div class="termy">97+98+```console99+// Check the help for items100+$ python main.py items --help101+102+// It shows its own commands (subcommands): create, delete, sell103+Usage: main.py items [OPTIONS] COMMAND [ARGS]...104+105+Options:106+ --help Show this message and exit.107+108+Commands:109+ create110+ delete111+ sell112+113+// Try it114+$ python main.py items create Wand115+116+Creating item: Wand117+118+$ python main.py items sell Vase119+120+Selling item: Vase121+```122+123+</div>124+125+And the same for the `users` command:126+127+128+<div class="termy">129+130+```console131+$ python main.py users --help132+133+Usage: main.py users [OPTIONS] COMMAND [ARGS]...134+135+Options:136+ --help Show this message and exit.137+138+Commands:139+ create140+ delete141+142+// Try it143+$ python main.py users create Camila144+145+Creating user: Camila146+```147+148+</div>added:scripts/test-files.sh+10 added
1+#!/usr/bin/env bash2+3+set -e4+set -x5+6+# Check README.md is up to date7+diff --brief docs/index.md README.md8+# Check copy paste errors in tutorials9+if grep -r --include "*.md" "Usage: tutorial" ./docs ; then echo "Incorrect console demo"; exit 1 ; fi10+if grep -r --include "*.md" "python tutorial" ./docs ; then echo "Incorrect console demo"; exit 1 ; fimodified:scripts/test.sh+4 added-3 removed
2 unmodified lines3 set -e4 set -x5 6 export PYTHONPATH=./docs/src7+# Use xdist-pytest --forked to ensure modified sys.path to import relative modules in examples keeps working7-pytest --cov=typer --cov=tests --cov=docs/src --cov-report=term-missing ${@}8+pytest --cov=typer --cov=tests --cov=docs/src --cov-report=term-missing -o console_output_style=progress --forked --numprocesses=auto ${@}9 bash ./scripts/lint.sh9-# Check README.md is up to date10-diff --brief docs/index.md README.md10+# Include tests for files11+bash ./scripts/test-files.shadded:tests/test_tutorial/test_subcommands/test_callback_override/__init__.py
added:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial001.py+26 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.callback_override import tutorial001 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_cli():13+ result = runner.invoke(app, ["users", "create", "Camila"])14+ assert result.exit_code == 015+ assert "Running a users command" in result.output16+ assert "Creating user: Camila" in result.output17+18+19+def test_script():20+ result = subprocess.run(21+ ["coverage", "run", mod.__file__, "--help"],22+ stdout=subprocess.PIPE,23+ stderr=subprocess.PIPE,24+ encoding="utf-8",25+ )26+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial002.py+26 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.callback_override import tutorial002 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_cli():13+ result = runner.invoke(app, ["users", "create", "Camila"])14+ assert result.exit_code == 015+ assert "Running a users command" in result.output16+ assert "Creating user: Camila" in result.output17+18+19+def test_script():20+ result = subprocess.run(21+ ["coverage", "run", mod.__file__, "--help"],22+ stdout=subprocess.PIPE,23+ stderr=subprocess.PIPE,24+ encoding="utf-8",25+ )26+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial003.py+31 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.callback_override import tutorial003 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_cli():13+ result = runner.invoke(app, ["users", "create", "Camila"])14+ assert result.exit_code == 015+ assert "Running a users command" not in result.output16+ assert "Callback override, running users command" in result.output17+ assert "Creating user: Camila" in result.output18+19+20+def test_for_coverage():21+ mod.default_callback()22+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_subcommands/test_callback_override/test_tutorial004.py+33 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.callback_override import tutorial004 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_cli():13+ result = runner.invoke(app, ["users", "create", "Camila"])14+ assert result.exit_code == 015+ assert "Running a users command" not in result.output16+ assert "Callback override, running users command" not in result.output17+ assert "I have the high land! Running users command" in result.output18+ assert "Creating user: Camila" in result.output19+20+21+def test_for_coverage():22+ mod.default_callback()23+ mod.user_callback()24+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.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/__init__.py
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial001.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial001 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "users" in result.output17+ assert "Manage users in the app." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["users", "--help"])22+ assert result.exit_code == 023+ assert "Manage users in the app." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial002.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial002 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "users" in result.output17+ assert "Manage users in the app." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["users", "--help"])22+ assert result.exit_code == 023+ assert "Manage users in the app." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial003.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial003 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "users" in result.output17+ assert "Manage users in the app." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["users", "--help"])22+ assert result.exit_code == 023+ assert "Manage users in the app." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial004.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial004 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "users" in result.output17+ assert "Manage users in the app." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["users", "--help"])22+ assert result.exit_code == 023+ assert "Manage users in the app." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial005.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial005 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "new-users" in result.output17+ assert "I have the highland! Create some users." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["new-users", "--help"])22+ assert result.exit_code == 023+ assert "I have the highland! Create some users." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["new-users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial006.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial006 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "exp-users" in result.output17+ assert "Explicit help." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["exp-users", "--help"])22+ assert result.exit_code == 023+ assert "Explicit help." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["exp-users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial007.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial007 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "call-users" in result.output17+ assert "Help from callback for users." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["call-users", "--help"])22+ assert result.exit_code == 023+ assert "Help from callback for users." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["call-users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial008.py+39 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.name_help import tutorial008 as mod6+7+runner = CliRunner()8+9+app = mod.app10+11+12+def test_help():13+ result = runner.invoke(app, ["--help"])14+ assert result.exit_code == 015+ assert "Commands:" in result.output16+ assert "cake-sith-users" in result.output17+ assert "Unlimited powder! Eh, users." in result.output18+19+20+def test_command_help():21+ result = runner.invoke(app, ["cake-sith-users", "--help"])22+ assert result.exit_code == 023+ assert "Unlimited powder! Eh, users." in result.output24+25+26+def test_command():27+ result = runner.invoke(app, ["cake-sith-users", "create", "Camila"])28+ assert result.exit_code == 029+ assert "Creating user: Camila" in result.output30+31+32+def test_script():33+ result = subprocess.run(34+ ["coverage", "run", mod.__file__, "--help"],35+ stdout=subprocess.PIPE,36+ stderr=subprocess.PIPE,37+ encoding="utf-8",38+ )39+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/__init__.py
added:tests/test_tutorial/test_subcommands/test_tutorial001.py+94 added
1+import subprocess2+3+import pytest4+from typer.testing import CliRunner5+6+from subcommands import tutorial0017+8+runner = CliRunner()9+10+11+@pytest.fixture()12+def mod(monkeypatch):13+ with monkeypatch.context() as m:14+ monkeypatch.syspath_prepend(list(tutorial001.__path__)[0])15+ from subcommands.tutorial001 import main16+17+ return main18+19+20+@pytest.fixture()21+def app(mod):22+ return mod.app23+24+25+def test_help(app):26+ result = runner.invoke(app, ["--help"])27+ assert result.exit_code == 028+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output29+ assert "Commands:" in result.output30+ assert "items" in result.output31+ assert "users" in result.output32+33+34+def test_help_items(app):35+ result = runner.invoke(app, ["items", "--help"])36+ assert result.exit_code == 037+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output38+ assert "Commands:" in result.output39+ assert "create" in result.output40+ assert "delete" in result.output41+ assert "sell" in result.output42+43+44+def test_items_create(app):45+ result = runner.invoke(app, ["items", "create", "Wand"])46+ assert result.exit_code == 047+ assert "Creating item: Wand" in result.output48+49+50+def test_items_sell(app):51+ result = runner.invoke(app, ["items", "sell", "Vase"])52+ assert result.exit_code == 053+ assert "Selling item: Vase" in result.output54+55+56+def test_items_delete(app):57+ result = runner.invoke(app, ["items", "delete", "Vase"])58+ assert result.exit_code == 059+ assert "Deleting item: Vase" in result.output60+61+62+def test_help_users(app):63+ result = runner.invoke(app, ["users", "--help"])64+ assert result.exit_code == 065+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output66+ assert "Commands:" in result.output67+ assert "create" in result.output68+ assert "delete" in result.output69+ assert "sell" not in result.output70+71+72+def test_users_create(app):73+ result = runner.invoke(app, ["users", "create", "Camila"])74+ assert result.exit_code == 075+ assert "Creating user: Camila" in result.output76+77+78+def test_users_delete(app):79+ result = runner.invoke(app, ["users", "delete", "Camila"])80+ assert result.exit_code == 081+ assert "Deleting user: Camila" in result.output82+83+84+def test_scripts(mod):85+ from subcommands.tutorial001 import items, users86+87+ for module in [mod, items, users]:88+ result = subprocess.run(89+ ["coverage", "run", module.__file__, "--help"],90+ stdout=subprocess.PIPE,91+ stderr=subprocess.PIPE,92+ encoding="utf-8",93+ )94+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_tutorial002.py+77 added
1+import subprocess2+3+from typer.testing import CliRunner4+5+from subcommands.tutorial002 import main as mod6+7+app = mod.app8+runner = CliRunner()9+10+11+def test_help():12+ result = runner.invoke(app, ["--help"])13+ assert result.exit_code == 014+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output15+ assert "Commands:" in result.output16+ assert "items" in result.output17+ assert "users" in result.output18+19+20+def test_help_items():21+ result = runner.invoke(app, ["items", "--help"])22+ assert result.exit_code == 023+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output24+ assert "Commands:" in result.output25+ assert "create" in result.output26+ assert "delete" in result.output27+ assert "sell" in result.output28+29+30+def test_items_create():31+ result = runner.invoke(app, ["items", "create", "Wand"])32+ assert result.exit_code == 033+ assert "Creating item: Wand" in result.output34+35+36+def test_items_sell():37+ result = runner.invoke(app, ["items", "sell", "Vase"])38+ assert result.exit_code == 039+ assert "Selling item: Vase" in result.output40+41+42+def test_items_delete():43+ result = runner.invoke(app, ["items", "delete", "Vase"])44+ assert result.exit_code == 045+ assert "Deleting item: Vase" in result.output46+47+48+def test_help_users():49+ result = runner.invoke(app, ["users", "--help"])50+ assert result.exit_code == 051+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output52+ assert "Commands:" in result.output53+ assert "create" in result.output54+ assert "delete" in result.output55+ assert "sell" not in result.output56+57+58+def test_users_create():59+ result = runner.invoke(app, ["users", "create", "Camila"])60+ assert result.exit_code == 061+ assert "Creating user: Camila" in result.output62+63+64+def test_users_delete():65+ result = runner.invoke(app, ["users", "delete", "Camila"])66+ assert result.exit_code == 067+ assert "Deleting user: Camila" in result.output68+69+70+def test_script():71+ result = subprocess.run(72+ ["coverage", "run", mod.__file__, "--help"],73+ stdout=subprocess.PIPE,74+ stderr=subprocess.PIPE,75+ encoding="utf-8",76+ )77+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_subcommands/test_tutorial003.py+146 added
1+import subprocess2+3+import pytest4+from typer.testing import CliRunner5+6+from subcommands import tutorial0037+8+runner = CliRunner()9+10+11+@pytest.fixture()12+def mod(monkeypatch):13+ with monkeypatch.context() as m:14+ m.syspath_prepend(list(tutorial003.__path__)[0])15+ from subcommands.tutorial003 import main16+17+ return main18+19+20+@pytest.fixture()21+def app(mod):22+ return mod.app23+24+25+def test_help(app):26+ result = runner.invoke(app, ["--help"])27+ assert result.exit_code == 028+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output29+ assert "Commands:" in result.output30+ assert "items" in result.output31+ assert "users" in result.output32+ assert "lands" in result.output33+34+35+def test_help_items(app):36+ result = runner.invoke(app, ["items", "--help"])37+ assert result.exit_code == 038+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output39+ assert "Commands:" in result.output40+ assert "create" in result.output41+ assert "delete" in result.output42+ assert "sell" in result.output43+44+45+def test_items_create(app):46+ result = runner.invoke(app, ["items", "create", "Wand"])47+ assert result.exit_code == 048+ assert "Creating item: Wand" in result.output49+50+51+def test_items_sell(app):52+ result = runner.invoke(app, ["items", "sell", "Vase"])53+ assert result.exit_code == 054+ assert "Selling item: Vase" in result.output55+56+57+def test_items_delete(app):58+ result = runner.invoke(app, ["items", "delete", "Vase"])59+ assert result.exit_code == 060+ assert "Deleting item: Vase" in result.output61+62+63+def test_help_users(app):64+ result = runner.invoke(app, ["users", "--help"])65+ assert result.exit_code == 066+ assert "[OPTIONS] COMMAND [ARGS]..." in result.output67+ assert "Commands:" in result.output68+ assert "create" in result.output69+ assert "delete" in result.output70+ assert "sell" not in result.output71+72+73+def test_users_create(app):74+ result = runner.invoke(app, ["users", "create", "Camila"])75+ assert result.exit_code == 076+ assert "Creating user: Camila" in result.output77+78+79+def test_users_delete(app):80+ result = runner.invoke(app, ["users", "delete", "Camila"])81+ assert result.exit_code == 082+ assert "Deleting user: Camila" in result.output83+84+85+def test_help_lands(app):86+ result = runner.invoke(app, ["lands", "--help"])87+ assert result.exit_code == 088+ assert "lands [OPTIONS] COMMAND [ARGS]..." in result.output89+ assert "Commands:" in result.output90+ assert "reigns" in result.output91+ assert "towns" in result.output92+93+94+def test_help_lands_reigns(app):95+ result = runner.invoke(app, ["lands", "reigns", "--help"])96+ assert result.exit_code == 097+ assert "lands reigns [OPTIONS] COMMAND [ARGS]..." in result.output98+ assert "Commands:" in result.output99+ assert "conquer" in result.output100+ assert "destroy" in result.output101+102+103+def test_lands_reigns_conquer(app):104+ result = runner.invoke(app, ["lands", "reigns", "conquer", "Gondor"])105+ assert result.exit_code == 0106+ assert "Conquering reign: Gondor" in result.output107+108+109+def test_lands_reigns_destroy(app):110+ result = runner.invoke(app, ["lands", "reigns", "destroy", "Mordor"])111+ assert result.exit_code == 0112+ assert "Destroying reign: Mordor" in result.output113+114+115+def test_help_lands_towns(app):116+ result = runner.invoke(app, ["lands", "towns", "--help"])117+ assert result.exit_code == 0118+ assert "lands towns [OPTIONS] COMMAND [ARGS]..." in result.output119+ assert "Commands:" in result.output120+ assert "burn" in result.output121+ assert "found" in result.output122+123+124+def test_lands_towns_found(app):125+ result = runner.invoke(app, ["lands", "towns", "found", "Cartagena"])126+ assert result.exit_code == 0127+ assert "Founding town: Cartagena" in result.output128+129+130+def test_lands_towns_burn(app):131+ result = runner.invoke(app, ["lands", "towns", "burn", "New Asgard"])132+ assert result.exit_code == 0133+ assert "Burning town: New Asgard" in result.output134+135+136+def test_scripts(mod):137+ from subcommands.tutorial003 import items, lands, reigns, towns, users138+139+ for module in [mod, items, lands, reigns, towns, users]:140+ result = subprocess.run(141+ ["coverage", "run", module.__file__, "--help"],142+ stdout=subprocess.PIPE,143+ stderr=subprocess.PIPE,144+ encoding="utf-8",145+ )146+ assert "Usage" in result.stdoutmodified:typer/__init__.py+7 added-13 removed
1 """Typer, build great CLIs. Easy to code. Based on Python type hints."""2 3 __version__ = "0.0.7"4 5-from click.exceptions import Abort, Exit # noqa6-from click.termui import ( # noqa5+from click.exceptions import Abort, Exit6+from click.termui import (7 clear,8 confirm,9 echo_via_pager,10 edit,6 unmodified lines17 secho,18 style,19 unstyle,20 )21-from click.utils import ( # noqa21+from click.utils import (22 echo,23 format_filename,24 get_app_dir,25 get_binary_stream,26 get_text_stream,27 open_file,28 )29 30-from . import colors # noqa31-from .main import Typer, run # noqa32-from .models import ( # noqa33- Context,34- FileBinaryRead,35- FileBinaryWrite,36- FileText,37- FileTextWrite,38-)39-from .params import Argument, Option # noqa30+from . import colors31+from .main import Typer, run32+from .models import Context, FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite33+from .params import Argument, Optionmodified:typer/main.py+29 added-18 removed
259 unmodified lines260 return None261 262 263 def solve_typer_info_help(typer_info: TyperInfo) -> str:264- # Priority 1a: Value was set in app.add_typer()264+ # Priority 1: Explicit value was set in app.add_typer()265 if not isinstance(typer_info.help, DefaultPlaceholder):266 return inspect.cleandoc(typer_info.help or "")267- # Priority 1b: Value was set in app.add_typer(), in callback docstring267+ # Priority 2: Explicit value was set in sub_app.callback()268+ try:269+ callback_help = typer_info.typer_instance.registered_callback.help270+ if not isinstance(callback_help, DefaultPlaceholder):271+ return inspect.cleandoc(callback_help or "")272+ except AttributeError:273+ pass274+ # Priority 3: Explicit value was set in sub_app = typer.Typer()275+ try:276+ instance_help = typer_info.typer_instance.info.help277+ if not isinstance(instance_help, DefaultPlaceholder):278+ return inspect.cleandoc(instance_help or "")279+ except AttributeError:280+ pass281+ # Priority 4: Implicit inference from callback docstring in app.add_typer()282 if typer_info.callback:283 doc = inspect.getdoc(typer_info.callback)284 if doc:285 return doc286+ # Priority 5: Implicit inference from callback docstring in @app.callback()287 try:273- # Priority 2a: Value was set in @subapp.callback()274- doc = typer_info.typer_instance.registered_callback.help275- if not isinstance(doc, DefaultPlaceholder):276- return inspect.cleandoc(doc or "")277- # Priority 2b: Value was set in @subapp.callback(), in callback docstring278- doc = inspect.getdoc(typer_info.typer_instance.registered_callback.callback)279- if doc:280- return doc288+ callback = typer_info.typer_instance.registered_callback.callback289+ if not isinstance(callback, DefaultPlaceholder):290+ doc = inspect.getdoc(callback or "")291+ if doc:292+ return doc293 except AttributeError:294 pass295+ # Priority 6: Implicit inference from callback docstring in typer.Typer()296 try:284- # Priority 3a: Value set in subapp = typer.Typer()285- instance_value = typer_info.typer_instance.info.help286- if not isinstance(instance_value, DefaultPlaceholder):287- return inspect.cleandoc(instance_value or "")288- doc = inspect.getdoc(typer_info.typer_instance.callback)289- if doc:290- return doc297+ instance_callback = typer_info.typer_instance.info.callback298+ if not isinstance(instance_callback, DefaultPlaceholder):299+ doc = inspect.getdoc(instance_callback)300+ if doc:301+ return doc302 except AttributeError:303 pass304 # Value not set, use the default305 return typer_info.help.value306 307 308 def solve_typer_info_defaults(typer_info: TyperInfo) -> TyperInfo:309 values: Dict[str, Any] = {}299- values["help"] = solve_typer_info_help(typer_info)310 name = None311 for name, value in typer_info.__dict__.items():312 # Priority 1: Value was set in app.add_typer()313 if not isinstance(value, DefaultPlaceholder):20 unmodified lines334 # Value not set, use the default335 values[name] = value.value336 if values["name"] is None:337 values["name"] = get_group_name(typer_info)338+ values["help"] = solve_typer_info_help(typer_info)339 return TyperInfo(**values)340 341 342 def get_group_from_info(group_info: TyperInfo) -> click.Command:390 unmodified linesmodified:.travis.yml+1 added-1 removed
14 unmodified lines15 - python: "nightly"16 17 install:18 - pip install flit19- - flit install --symlink19+ - flit install --deps=develop --symlink20 21 script:22 - bash scripts/test.sh23 9 unmodified linesmodified:mkdocs.yml+4 added
45 unmodified lines46 - DateTime: 'tutorial/parameter-types/datetime.md'47 - Enum - Choices: 'tutorial/parameter-types/enum.md'48 - Path: 'tutorial/parameter-types/path.md'49 - File: 'tutorial/parameter-types/file.md'50+ - SubCommands:51+ - SubCommands Intro: 'tutorial/subcommands/index.md'52+ - Add Typer: 'tutorial/subcommands/add-typer.md'53+ - SubCommands in a Single File: 'tutorial/subcommands/single-file.md'54 - Ask with Prompt: 'tutorial/prompt.md'55 - Progress Bar: 'tutorial/progressbar.md'56 - CLI Application Directory: 'tutorial/app-dir.md'57 - Launching Applications: 'tutorial/launch.md'38 unmodified linesmodified:pyproject.toml+4 added-1 removed
35 unmodified lines36 Documentation = "https://typer.tiangolo.com/"37 38 [tool.flit.metadata.requires-extra]39 test = [40+ "click-completion",40- "pytest >=4.0.0",41+ "pytest >=4.4.0",42 "pytest-cov",43 "coverage",44+ "pytest-xdist",45+ "pytest-sugar",46 "mypy",47 "black",48 "isort"49 ]9 unmodified lines