Skip to content
Myr

: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

53 files+2542 added−36 removed

added:docs/src/subcommands/callback_override/tutorial001.py+20 added
1import typer23app = typer.Typer()45users_app = typer.Typer()6app.add_typer(users_app, name="users")789@users_app.callback()10def users_callback():11 typer.echo("Running a users command")121314@users_app.command()15def create(name: str):16 typer.echo(f"Creating user: {name}")171819if __name__ == "__main__":20 app()
added:docs/src/subcommands/callback_override/tutorial002.py+20 added
1import typer23app = typer.Typer()456def users_callback():7 typer.echo("Running a users command")8910users_app = typer.Typer(callback=users_callback)11app.add_typer(users_app, name="users")121314@users_app.command()15def create(name: str):16 typer.echo(f"Creating user: {name}")171819if __name__ == "__main__":20 app()
added:docs/src/subcommands/callback_override/tutorial003.py+25 added
1import typer23app = typer.Typer()456def default_callback():7 typer.echo("Running a users command")8910users_app = typer.Typer(callback=default_callback)11app.add_typer(users_app, name="users")121314@users_app.callback()15def user_callback():16 typer.echo("Callback override, running users command")171819@users_app.command()20def create(name: str):21 typer.echo(f"Creating user: {name}")222324if __name__ == "__main__":25 app()
added:docs/src/subcommands/callback_override/tutorial004.py+31 added
1import typer23app = typer.Typer()456def default_callback():7 typer.echo("Running a users command")8910users_app = typer.Typer(callback=default_callback)111213def callback_for_add_typer():14 typer.echo("I have the high land! Running users command")151617app.add_typer(users_app, name="users", callback=callback_for_add_typer)181920@users_app.callback()21def user_callback():22 typer.echo("Callback override, running users command")232425@users_app.command()26def create(name: str):27 typer.echo(f"Creating user: {name}")282930if __name__ == "__main__":31 app()
added:docs/src/subcommands/name_help/tutorial001.py+15 added
1import typer23app = typer.Typer()45users_app = typer.Typer()6app.add_typer(users_app, name="users", help="Manage users in the app.")789@users_app.command()10def create(name: str):11 typer.echo(f"Creating user: {name}")121314if __name__ == "__main__":15 app()
added:docs/src/subcommands/name_help/tutorial002.py+22 added
1import typer23app = typer.Typer()45users_app = typer.Typer()6app.add_typer(users_app)789@users_app.callback()10def users():11 """12 Manage users in the app.13 """141516@users_app.command()17def create(name: str):18 typer.echo(f"Creating user: {name}")192021if __name__ == "__main__":22 app()
added:docs/src/subcommands/name_help/tutorial003.py+22 added
1import typer23app = typer.Typer()456def users():7 """8 Manage users in the app.9 """101112users_app = typer.Typer(callback=users)13app.add_typer(users_app)141516@users_app.command()17def create(name: str):18 typer.echo(f"Creating user: {name}")192021if __name__ == "__main__":22 app()
added:docs/src/subcommands/name_help/tutorial004.py+29 added
1import typer23app = typer.Typer()456def old_callback():7 """8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback)13app.add_typer(users_app)141516@users_app.callback()17def users():18 """19 Manage users in the app.20 """212223@users_app.command()24def create(name: str):25 typer.echo(f"Creating user: {name}")262728if __name__ == "__main__":29 app()
added:docs/src/subcommands/name_help/tutorial005.py+37 added
1import typer23app = typer.Typer()456def old_callback():7 """8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback)131415def new_users():16 """17 I have the highland! Create some users.18 """192021app.add_typer(users_app, callback=new_users)222324@users_app.callback()25def users():26 """27 Manage users in the app.28 """293031@users_app.command()32def create(name: str):33 typer.echo(f"Creating user: {name}")343536if __name__ == "__main__":37 app()
added:docs/src/subcommands/name_help/tutorial006.py+37 added
1import typer23app = typer.Typer()456def old_callback():7 """8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")131415def new_users():16 """17 I have the highland! Create some users.18 """192021app.add_typer(users_app, callback=new_users)222324@users_app.callback()25def users():26 """27 Manage users in the app.28 """293031@users_app.command()32def create(name: str):33 typer.echo(f"Creating user: {name}")343536if __name__ == "__main__":37 app()
added:docs/src/subcommands/name_help/tutorial007.py+37 added
1import typer23app = typer.Typer()456def old_callback():7 """8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")131415def new_users():16 """17 I have the highland! Create some users.18 """192021app.add_typer(users_app, callback=new_users)222324@users_app.callback("call-users", help="Help from callback for users.")25def users():26 """27 Manage users in the app.28 """293031@users_app.command()32def create(name: str):33 typer.echo(f"Creating user: {name}")343536if __name__ == "__main__":37 app()
added:docs/src/subcommands/name_help/tutorial008.py+42 added
1import typer23app = typer.Typer()456def old_callback():7 """8 Old callback help.9 """101112users_app = typer.Typer(callback=old_callback, name="exp-users", help="Explicit help.")131415def new_users():16 """17 I have the highland! Create some users.18 """192021app.add_typer(22 users_app,23 callback=new_users,24 name="cake-sith-users",25 help="Unlimited powder! Eh, users.",26)272829@users_app.callback("call-users", help="Help from callback for users.")30def users():31 """32 Manage users in the app.33 """343536@users_app.command()37def create(name: str):38 typer.echo(f"Creating user: {name}")394041if __name__ == "__main__":42 app()
added:docs/src/subcommands/tutorial001/items.py+22 added
1import typer23app = typer.Typer()456@app.command()7def create(item: str):8 typer.echo(f"Creating item: {item}")91011@app.command()12def delete(item: str):13 typer.echo(f"Deleting item: {item}")141516@app.command()17def sell(item: str):18 typer.echo(f"Selling item: {item}")192021if __name__ == "__main__":22 app()
added:docs/src/subcommands/tutorial001/main.py+11 added
1import typer23import items4import users56app = typer.Typer()7app.add_typer(users.app, name="users")8app.add_typer(items.app, name="items")910if __name__ == "__main__":11 app()
added:docs/src/subcommands/tutorial001/users.py+17 added
1import typer23app = typer.Typer()456@app.command()7def create(user_name: str):8 typer.echo(f"Creating user: {user_name}")91011@app.command()12def delete(user_name: str):13 typer.echo(f"Deleting user: {user_name}")141516if __name__ == "__main__":17 app()
added:docs/src/subcommands/tutorial002/main.py+36 added
1import typer23app = typer.Typer()4items_app = typer.Typer()5app.add_typer(items_app, name="items")6users_app = typer.Typer()7app.add_typer(users_app, name="users")8910@items_app.command("create")11def items_create(item: str):12 typer.echo(f"Creating item: {item}")131415@items_app.command("delete")16def items_delete(item: str):17 typer.echo(f"Deleting item: {item}")181920@items_app.command("sell")21def items_sell(item: str):22 typer.echo(f"Selling item: {item}")232425@users_app.command("create")26def users_create(user_name: str):27 typer.echo(f"Creating user: {user_name}")282930@users_app.command("delete")31def users_delete(user_name: str):32 typer.echo(f"Deleting user: {user_name}")333435if __name__ == "__main__":36 app()
added:docs/src/subcommands/tutorial003/items.py+22 added
1import typer23app = typer.Typer()456@app.command()7def create(item: str):8 typer.echo(f"Creating item: {item}")91011@app.command()12def delete(item: str):13 typer.echo(f"Deleting item: {item}")141516@app.command()17def sell(item: str):18 typer.echo(f"Selling item: {item}")192021if __name__ == "__main__":22 app()
added:docs/src/subcommands/tutorial003/lands.py+11 added
1import typer23import reigns4import towns56app = typer.Typer()7app.add_typer(reigns.app, name="reigns")8app.add_typer(towns.app, name="towns")910if __name__ == "__main__":11 app()
added:docs/src/subcommands/tutorial003/main.py+13 added
1import typer23import items4import lands5import users67app = typer.Typer()8app.add_typer(users.app, name="users")9app.add_typer(items.app, name="items")10app.add_typer(lands.app, name="lands")1112if __name__ == "__main__":13 app()
added:docs/src/subcommands/tutorial003/reigns.py+17 added
1import typer23app = typer.Typer()456@app.command()7def conquer(name: str):8 typer.echo(f"Conquering reign: {name}")91011@app.command()12def destroy(name: str):13 typer.echo(f"Destroying reign: {name}")141516if __name__ == "__main__":17 app()
added:docs/src/subcommands/tutorial003/towns.py+17 added
1import typer23app = typer.Typer()456@app.command()7def found(name: str):8 typer.echo(f"Founding town: {name}")91011@app.command()12def burn(name: str):13 typer.echo(f"Burning town: {name}")141516if __name__ == "__main__":17 app()
added:docs/src/subcommands/tutorial003/users.py+17 added
1import typer23app = typer.Typer()456@app.command()7def create(user_name: str):8 typer.echo(f"Creating user: {user_name}")91011@app.command()12def delete(user_name: str):13 typer.echo(f"Deleting user: {user_name}")141516if __name__ == "__main__":17 app()
added:docs/tutorial/subcommands/add-typer.md+169 added
1We'll start with the core idea.23To add a `typer.Typer()` app inside of another.45## Manage items67Let's imagine that you are creating a *CLI program* to manage items in some distant land.89It could be in an `items.py` file with this:1011```Python hl_lines=""12{!./src/subcommands/tutorial001/items.py!}13```1415And you would use it like:1617<div class="termy">1819```console20$ python items.py create Wand2122Creating item: Wand23```2425</div>2627## Manage users2829But then you realize that you also have to manage users from your *CLI app*.3031It could be a file `users.py` with something like:3233```Python hl_lines=""34{!./src/subcommands/tutorial001/users.py!}35```3637And you would use it like:3839<div class="termy">4041```console42$ python users.py create Camila4344Creating user: Camila45```4647</div>4849## Put them together5051Both parts are similar. In fact, `items.py` and `users.py` both have commands `create` and `delete`.5253But we need them to be part of the same *CLI program*.5455In this case, as with `git remote`, we can put them together as subcommands in another `typer.Typer()` *CLI program*.5657Now create a `main.py` with:5859```Python hl_lines="3 4 7 8"60{!./src/subcommands/tutorial001/main.py!}61```6263Here's what we do in `main.py`:6465* 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.6970And now your *CLI program* has 2 commands:7172* `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`.7475Check it:7677<div class="termy">7879```console80// Check the help81$ python main.py --help8283Usage: main.py [OPTIONS] COMMAND [ARGS]...8485Options: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.8990Commands:91 items92 users93```9495</div>9697Now you have a *CLI program* with commands `items` and `users`, and they in turn have their own commands (subcommands).9899Let's check the `items` command:100101<div class="termy">102103```console104// Check the help for items105$ python main.py items --help106107// It shows its own commands (subcommands): create, delete, sell108Usage: main.py items [OPTIONS] COMMAND [ARGS]...109110Options:111 --help Show this message and exit.112113Commands:114 create115 delete116 sell117118// Try it119$ python main.py items create Wand120121Creating item: Wand122123$ python main.py items sell Vase124125Selling item: Vase126```127128</div>129130!!! tip131 Notice that we are still calling `$ python main.py` but now we are using the command `items`.132133And now check the command `users`, with all its subcommands:134135<div class="termy">136137```console138$ python main.py users --help139140Usage: main.py users [OPTIONS] COMMAND [ARGS]...141142Options:143 --help Show this message and exit.144145Commands:146 create147 delete148149// Try it150$ python main.py users create Camila151152Creating user: Camila153```154155</div>156157## Recap158159That's the core idea.160161You can just create `typer.Typer()` apps and add them inside one another.162163And you can do that with any levels of commands that you want.164165Do you need sub-sub-sub-subcommands? Go ahead, create all the `typer.Typer()`s you need and put them together with `app.add_typer()`.166167In the next sections we'll update this with more features, but you already have the core idea.168169This 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
1When 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.23When adding a Typer app inside of another, the sub-Typer can also have its own callback.45It can handle any *CLI parameters* that go before its own commands and execute any extra code:67```Python hl_lines="9 10 11"8{!./src/subcommands/callback_override/tutorial001.py!}9```1011In this case it doesn't define any *CLI parameters*, it just writes a message.1213Check it:1415<div class="termy">1617```console18$ python main.py users create Camila1920// Notice the first message is not created by the command function but by the callback21Running a users command22Creating user: Camila23```2425</div>2627## Add a callback on creation2829It's also possible to add a callback when creating the `typer.Typer()` app that will be added to another Typer app:3031```Python hl_lines="6 7 10"32{!./src/subcommands/callback_override/tutorial002.py!}33```3435This achieves exactly the same as above, it's just another place to add the callback.3637Check it:3839<div class="termy">4041```console42$ python main.py users create Camila4344Running a users command45Creating user: Camila46```4748</div>4950## Overriding the callback on creation5152If a callback was added when creating the `typer.Typer()` app, it's possible to override it with a new one using `@app.callback()`.5354This 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:5556```Python hl_lines="6 7 10 14 15 16"57{!./src/subcommands/callback_override/tutorial003.py!}58```5960Here 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()`.6162As `@app.callback()` takes precedence over `typer.Typer(callback=some_function)`, now our CLI app will use this new callback.6364Check it:6566<div class="termy">6768```console69$ python main.py users create Camila7071// Notice the message from the new callback72Callback override, running users command73Creating user: Camila74```7576</div>7778## Overriding the callback when adding a sub-Typer7980Lastly, you can override the callback defined anywhere else when adding a sub-Typer with `app.add_typer()` using the `callback` parameter.8182This has the highest priority:8384```Python hl_lines="13 14 17"85{!./src/subcommands/callback_override/tutorial004.py!}86```8788Notice 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.8990Now when you use the CLI program it will use the new callback function `callback_for_add_typer()`.9192Check it:9394<div class="termy">9596```console97$ python users create Camila9899// Notice the message from the callback added in add_typer()100I have the high land! Running users command101Creating user: Camila102```103104</div>
added:docs/tutorial/subcommands/index.md+39 added
1You read before how to create a program with <a href="https://typer.tiangolo.com/tutorial/commands/" target="_blank">Commands</a>.23Now we'll see how to create a *CLI program* with commands that have their own subcommands. Also known as command groups.45For example, the *CLI program* `git` has a command `remote`.67But `git remote`, in turn, has its own subcommands, like `add`:89<div class="termy">1011```console12// git remote alone shows the current remote repositories13$ git remote1415origin1617// Use -v to make it verbose and show more info18$ git remote -v1920origin git@github.com:yourusername/typer.git (fetch)21origin git@github.com:yourusername/typer.git (push)2223// git remote add takes 2 CLI arguments, a name and URL24$ git remote add upstream https://github.com/tiangolo/typer.git2526// Doesn't output anything, but now you have another remote repository called upstream2728// Now check again29$ git remote -v3031origin git@github.com:yourusername/typer.git (fetch)32origin git@github.com:yourusername/typer.git (push)33upstream https://github.com/tiangolo/typer.git (fetch)34upstream https://github.com/tiangolo/typer.git (push)35```3637</div>3839In the next sections we'll see how to create subcommands like these.
added:docs/tutorial/subcommands/name-and-help.md+463 added
1When adding a Typer app to another we have seen how to set the `name` to use for the command.23For example to set the command to `users`:45```Python6app.add_typer(users.app, name="users")7```89## Add a help text1011We can also set the `help` while adding a Typer:1213```Python hl_lines="6"14{!./src/subcommands/name_help/tutorial001.py!}15```1617And then we get that help text for that command in the *CLI program*:1819<div class="termy">2021```console22// Check the main help23$ python main.py --help2425Usage: main.py [OPTIONS] COMMAND [ARGS]...2627Options: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.3132Commands:33 users Manage users in the app.3435// Check the help for the users command36$ python main.py users --help3738Usage: main.py users [OPTIONS] COMMAND [ARGS]...3940 Manage users in the app.4142Options:43 --help Show this message and exit.4445Commands:46 create47```4849</div>5051We can set the `name` and `help` in several places, each one taking precedence over the other, overriding the previous value.5253Let's see those locations.5455!!! tip56 There are other attributes that can be set in that same way in the same places we'll see next.5758 But those are documented later in another section.5960## Inferring name and help from callback6162### Inferring a command's name and help6364When you create a command with `@app.command()`, by default, it generates the name from the function name.6566And by default, the help text is extracted from the function's docstring.6768For example:6970```Python71@app.command()72def create(item: str):73 """74 Create an item.75 """76 typer.echo(f"Creating item: {item}")77```7879...will create a command `create` with a help text of `Create an item`.8081### Inferring name and help from `@app.callback()`8283The same way, if you define a callback in a `typer.Typer()`, the help text is extracted from the callback function's docstring.8485And 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.8687Here's an example:8889```Python hl_lines="6 9 10 11 12 13"90{!./src/subcommands/name_help/tutorial002.py!}91```9293Notice that now we added the sub-Typer without specifying a `name` nor a `help`.9495They are now inferred from the callback function.9697The command name will be the same callback function's name: `users`.9899And the help text for that `users` command will be the callback function's docstring: `Manage users in the app.`.100101Check it:102103<div class="termy">104105```console106// Check the main help107$ python main.py --help108109// Notice the command name "users" and the help text "Manage users in the app."110Usage: main.py [OPTIONS] COMMAND [ARGS]...111112Options: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.116117Commands:118 users Manage users in the app.119120// Check the help for the users command121$ python main.py users --help122123// Notice the main description: "Manage users in the app."124Usage: main.py users [OPTIONS] COMMAND [ARGS]...125126 Manage users in the app.127128Options:129 --help Show this message and exit.130131Commands:132 create133```134135</div>136137### Name and help from callback parameter in `typer.Typer()`138139If you pass a `callback` parameter while creating a `typer.Typer(callback=some_function)` it will be used to infer the name and help text.140141This has the lowest priority, we'll see later what has a higher priority and can override it.142143Check the code:144145```Python hl_lines="6 7 8 9 12"146{!./src/subcommands/name_help/tutorial003.py!}147```148149This achieves exactly the same as the previous example.150151Check it:152153<div class="termy">154155```console156// Check the main help157$ python main.py --help158159// Notice the command name "users" and the help text "Manage users in the app."160Usage: main.py [OPTIONS] COMMAND [ARGS]...161162Options: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.166167Commands:168 users Manage users in the app.169170// Check the help for the users command171$ python main.py users --help172173// Notice the main description: "Manage users in the app."174Usage: main.py users [OPTIONS] COMMAND [ARGS]...175176 Manage users in the app.177178Options:179 --help Show this message and exit.180181Commands:182 create183```184185</div>186187### Override a callback set in `typer.Typer()` with `@app.callback()`188189The 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:190191```Python hl_lines="16 17 18 19 20"192{!./src/subcommands/name_help/tutorial004.py!}193```194195Now 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.`.196197Check it:198199<div class="termy">200201```console202// Check the main help203$ python main.py --help204205// Notice the command name "users" and the help text "Manage users in the app."206Usage: main.py [OPTIONS] COMMAND [ARGS]...207208Options: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.212213Commands:214 users Manage users in the app.215216// Check the help for the users command217$ python main.py users --help218219// Notice the main description: "Manage users in the app."220Usage: main.py users [OPTIONS] COMMAND [ARGS]...221222 Manage users in the app.223224Options:225 --help Show this message and exit.226227Commands:228 create229```230231</div>232233### Infer name and help from callback in `app.add_typer()`234235If you override the callback in `app.add_typer()` when including a sub-app, the name and help will be inferred from this callback function.236237This takes precedence over inferring the name and help from a callback set in `@sub_app.callback()` and `typer.Typer(callback=sub_app_callback)`.238239Check the code:240241```Python hl_lines="15 16 17 18 21"242{!./src/subcommands/name_help/tutorial005.py!}243```244245Now 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.246247Check it:248249<div class="termy">250251```console252// Check the main help253$ python main.py --help254255// Check the command new-users and its help text256257Usage: main.py [OPTIONS] COMMAND [ARGS]...258259Options: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.263264Commands:265 new-users I have the highland! Create some users.266267// Now check the help for the new-users command268$ python main.py new-users --help269270// Notice the help text271Usage: main.py new-users [OPTIONS] COMMAND [ARGS]...272273 I have the highland! Create some users.274275Options:276 --help Show this message and exit.277278Commands:279 create280```281282</div>283284### Enough inferring285286So, when inferring a name and help text, the precedence order from lowest priority to highest is:287288* `sub_app = typer.Typer(callback=some_function)`289* `@sub_app.callback()`290* `app.add_typer(sub_app, callback=new_function)`291292That's for inferring the name and help text from functions.293294But if you set the name and help text explicitly, that has a higher priority than these.295296## Set the name and help297298Let's now see the places where you can set the command name and help text, from lowest priority to highest.299300!!! tip301 Setting the name and help text explicitly always has a higher precedence than inferring from a callback function.302303### Name and help in `typer.Typer()`304305You could have all the callbacks and overrides we defined before, but the name and help text was inferred from the function name and docstring.306307If you set it explicitly, that takes precedence over inferring.308309You can set it when creating a new `typer.Typer()`:310311```Python hl_lines="12"312{!./src/subcommands/name_help/tutorial006.py!}313```314315!!! 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.317318We set an explicit name `exp-users`, and an explicit help `Explicit help.`.319320So that will take precedence now.321322Check it:323324<div class="termy">325326```console327// Check the main help328$ python main.py --help329330// Notice the command name is exp-users and the help text is "Explicit help."331Usage: main.py [OPTIONS] COMMAND [ARGS]...332333Options: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.337338Commands:339 exp-users Explicit help.340341// Check the help for the exp-users command342$ python main.py exp-users --help343344// Notice the main help text345Usage: main.py exp-users [OPTIONS] COMMAND [ARGS]...346347 Explicit help.348349Options:350 --help Show this message and exit.351352Commands:353 create354```355356</div>357358### Name and help in `@app.callback()`359360Any parameter that you use when creating a `typer.Typer()` app can be overridden in the parameters of `@app.callback()`.361362Continuing with the previous example, we now override the values in `@user_app.callback()`:363364```Python hl_lines="24"365{!./src/subcommands/name_help/tutorial007.py!}366```367368And now the command name will be `call-users` and the help text will be `Help from callback for users.`.369370Check it:371372<div class="termy">373374```console375// Check the help376$ python main.py --help377378// The command name now is call-users and the help text is "Help from callback for users.".379Usage: main.py [OPTIONS] COMMAND [ARGS]...380381Options: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.385386Commands:387 call-users Help from callback for users.388389// Check the call-users command help390$ python main.py call-users --help391392// Notice the main help text393Usage: main.py call-users [OPTIONS] COMMAND [ARGS]...394395 Help from callback for users.396397Options:398 --help Show this message and exit.399400Commands:401 create402```403404</div>405406### Name and help in `app.add_typer()`407408And 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:409410```Python hl_lines="21"411{!./src/subcommands/name_help/tutorial008.py!}412```413414And 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.`.415416Check it:417418<div class="termy">419420```console421// Check the help422$ python main.py --help423424// Notice the command name cake-sith-users and the new help text "Unlimited powder! Eh, users."425Usage: main.py [OPTIONS] COMMAND [ARGS]...426427Options: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.431432Commands:433 cake-sith-users Unlimited powder! Eh, users.434435// And check the help for the command cake-sith-users436$ python main.py cake-sith-users --help437438// Notice the main help text439Usage: main.py cake-sith-users [OPTIONS] COMMAND [ARGS]...440441 Unlimited powder! Eh, users.442443Options:444 --help Show this message and exit.445446Commands:447 create448```449450</div>451452## Recap453454The precedence to generate a command's name and help, from lowest priority to highest, is:455456* 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.")`462463So, `app.add_typer(sub_app, name="some-name", help="Some help.")` always wins.
added:docs/tutorial/subcommands/nested-subcommands.md+295 added
1We'll now see how these same ideas can be extended for deeply nested commands.23Let's imagine that the same *CLI program* from the previous examples now needs to handle `lands`.45But a land could be a `reign` or `town`.67And each of those could have their own commands, like `create` and `delete`.89## A CLI app for reigns1011Let's start with a file `reigns.py`:1213```Python hl_lines=""14{!./src/subcommands/tutorial003/reigns.py!}15```1617This is already a simple *CLI program* to manage reigns:1819<div class="termy">2021```console22// Check the help23$ python reigns.py --help2425Usage: reigns.py [OPTIONS] COMMAND [ARGS]...2627Options: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.3132Commands:33 conquer34 destroy3536// Try it37$ python reigns.py conquer Cintra3839Conquering reign: Cintra4041$ python reigns.py destroy Mordor4243Destroying reign: Mordor44```4546</div>4748## A CLI app for towns4950And now the equivalent for managing towns in `towns.py`:5152```Python hl_lines=""53{!./src/subcommands/tutorial003/towns.py!}54```5556With it, you can manage towns:5758<div class="termy">5960```console61// Check the help62$ python towns.py --help6364Usage: towns.py [OPTIONS] COMMAND [ARGS]...6566Options: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.7071Commands:72 burn73 found7475// Try it76$ python towns.py found "New Asgard"7778Founding town: New Asgard7980$ python towns.py burn Vizima8182Burning town: Vizima83```8485</div>8687## Manage the land in a CLI app8889Now let's put the `reigns` and `towns` together in the same *CLI program* in `lands.py`:9091```Python hl_lines=""92{!./src/subcommands/tutorial003/lands.py!}93```9495And 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.9697Check it:9899<div class="termy">100101```console102// Check the help103$ python lands.py --help104105Usage: lands.py [OPTIONS] COMMAND [ARGS]...106107Options: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.111112Commands:113 reigns114 towns115116// We still have the help for reigns117$ python lands.py reigns --help118119Usage: lands.py reigns [OPTIONS] COMMAND [ARGS]...120121Options:122 --help Show this message and exit.123124Commands:125 conquer126 destroy127128// And the help for towns129$ python lands.py towns --help130131Usage: lands.py towns [OPTIONS] COMMAND [ARGS]...132133Options:134 --help Show this message and exit.135136Commands:137 burn138 found139```140141</div>142143Now try it, manage the lands through the CLI:144145<div class="termy">146147```console148// Try the reigns command149$ python lands.py reigns conquer Gondor150151Conquering reign: Gondor152153$ python lands.py reigns destroy Nilfgaard154155Destroying reign: Nilfgaard156157// Try the towns command158$ python lands.py towns found Springfield159160Founding town: Springfield161162$ python lands.py towns burn Atlantis163164Burning town: Atlantis165```166167</div>168169## Deeply nested subcommands170171Now 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.172173We want our *CLI program* to have these commands/command groups:174175* `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`189190This already is a quite deeply nested "tree" of commands/command groups.191192But to achieve that, we just have to add the `lands` **Typer** app to the same `main.py` file we already had:193194```Python hl_lines="4 10"195{!./src/subcommands/tutorial003/main.py!}196```197198And now we have everything in a single *CLI program*:199200<div class="termy">201202```console203// Check the main help204$ python main.py --help205206Usage: main.py [OPTIONS] COMMAND [ARGS]...207208Options: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.212213Commands:214 items215 lands216 users217218// Try some users commands219$ python main.py users create Camila220221Creating user: Camila222223// Now try some items commands224$ python main.py items create Sword225226Creating item: Sword227228// And now some lands commands for reigns229$ python main.py lands reigns conquer Gondor230231Conquering reign: Gondor232233// And for towns234$ python main.py lands towns found Cartagena235236Founding town: Cartagena237```238239</div>240241## Review the files242243Here are all the files if you want to review/copy them:244245`reigns.py`:246247```Python hl_lines=""248{!./src/subcommands/tutorial003/reigns.py!}249```250251`towns.py`:252253```Python hl_lines=""254{!./src/subcommands/tutorial003/towns.py!}255```256257`lands.py`:258259```Python hl_lines=""260{!./src/subcommands/tutorial003/lands.py!}261```262263`users.py`:264265```Python hl_lines=""266{!./src/subcommands/tutorial003/users.py!}267```268269`items.py`:270271```Python hl_lines=""272{!./src/subcommands/tutorial003/items.py!}273```274275`main.py`:276277```Python hl_lines=""278{!./src/subcommands/tutorial003/main.py!}279```280281!!! tip282 All these files have an `if __name__ == "__main__"` block just to demonstrate how each of them can also be an independent *CLI app*.283284 But for your final application, only `main.py` would need it.285286## Recap287288That'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.289290You 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.291292!!! tip293 Auto completion helps a lot, specially with complex programs.294295 Check the docs about adding auto completion to your *CLI apps*.
added:docs/tutorial/subcommands/single-file.md+148 added
1In some cases, it's possible that your application code needs to live on a single file.23You can still use the same ideas:45```Python hl_lines=""6{!./src/subcommands/tutorial002/main.py!}7```89There are several things to notice here...1011## Apps at the top1213First, you can create `typer.Typer()` objects and add them to another one at the top.1415It doesn't have to be done after creating the subcommands:1617```Python hl_lines="4 5 6 7"18{!./src/subcommands/tutorial002/main.py!}19```2021You can add the commands (subcommands) to each `typer.Typer()` app later and it will still work.2223## Function names2425As 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.2627So we use longer names:2829```Python hl_lines="11 16 21 26 31"30{!./src/subcommands/tutorial002/main.py!}31```3233## Command name3435We are naming the functions with longer names so that they don't overwrite each other.3637But we still want the subcommands to be `create`, `delete`, etc.3839To call them like:4041<div class="termy">4243```console44// We want this ✔️45$ python main.py items create46```4748</div>4950instead of:5152<div class="termy">5354```console55// We don't want this ⛔️56$ python main.py items items-create57```5859</div>6061So we pass the name we want to use for each subcommand as the function argument to the decorator:6263```Python hl_lines="10 15 20 25 30"64{!./src/subcommands/tutorial002/main.py!}65```6667## Check it6869It still works the same:707172<div class="termy">7374```console75// Check the help76$ python main.py --help7778Usage: main.py [OPTIONS] COMMAND [ARGS]...7980Options: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.8586Commands:87 items88 users89```9091</div>9293Check the `items` command:949596<div class="termy">9798```console99// Check the help for items100$ python main.py items --help101102// It shows its own commands (subcommands): create, delete, sell103Usage: main.py items [OPTIONS] COMMAND [ARGS]...104105Options:106 --help Show this message and exit.107108Commands:109 create110 delete111 sell112113// Try it114$ python main.py items create Wand115116Creating item: Wand117118$ python main.py items sell Vase119120Selling item: Vase121```122123</div>124125And the same for the `users` command:126127128<div class="termy">129130```console131$ python main.py users --help132133Usage: main.py users [OPTIONS] COMMAND [ARGS]...134135Options:136 --help Show this message and exit.137138Commands:139 create140 delete141142// Try it143$ python main.py users create Camila144145Creating user: Camila146```147148</div>
added:scripts/test-files.sh+10 added
1#!/usr/bin/env bash23set -e4set -x56# Check README.md is up to date7diff --brief docs/index.md README.md8# Check copy paste errors in tutorials9if grep -r --include "*.md" "Usage: tutorial" ./docs ; then echo "Incorrect console demo"; exit 1 ; fi10if grep -r --include "*.md" "python tutorial" ./docs ; then echo "Incorrect console demo"; exit 1 ; fi
modified:scripts/test.sh+4 added-3 removed
2 unmodified lines
3set -e4set -x56export PYTHONPATH=./docs/src7# Use xdist-pytest --forked to ensure modified sys.path to import relative modules in examples keeps working7pytest --cov=typer --cov=tests --cov=docs/src --cov-report=term-missing ${@}8pytest --cov=typer --cov=tests --cov=docs/src --cov-report=term-missing -o console_output_style=progress --forked --numprocesses=auto ${@}9bash ./scripts/lint.sh9# Check README.md is up to date10diff --brief docs/index.md README.md10# Include tests for files11bash ./scripts/test-files.sh
added:tests/test_tutorial/test_subcommands/test_callback_override/__init__.py
added:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial001.py+26 added
1import subprocess23from typer.testing import CliRunner45from subcommands.callback_override import tutorial001 as mod67runner = CliRunner()89app = mod.app101112def 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.output171819def 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.stdout
added:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial002.py+26 added
1import subprocess23from typer.testing import CliRunner45from subcommands.callback_override import tutorial002 as mod67runner = CliRunner()89app = mod.app101112def 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.output171819def 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.stdout
added:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial003.py+31 added
1import subprocess23from typer.testing import CliRunner45from subcommands.callback_override import tutorial003 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def test_for_coverage():21 mod.default_callback()222324def 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.stdout
added:tests/test_tutorial/test_subcommands/test_callback_override/test_tutorial004.py+33 added
1import subprocess23from typer.testing import CliRunner45from subcommands.callback_override import tutorial004 as mod67runner = CliRunner()89app = mod.app101112def 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.output192021def test_for_coverage():22 mod.default_callback()23 mod.user_callback()242526def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/__init__.py
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial001.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial001 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def test_command_help():21 result = runner.invoke(app, ["users", "--help"])22 assert result.exit_code == 023 assert "Manage users in the app." in result.output242526def test_command():27 result = runner.invoke(app, ["users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial002.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial002 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def test_command_help():21 result = runner.invoke(app, ["users", "--help"])22 assert result.exit_code == 023 assert "Manage users in the app." in result.output242526def test_command():27 result = runner.invoke(app, ["users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial003.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial003 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def test_command_help():21 result = runner.invoke(app, ["users", "--help"])22 assert result.exit_code == 023 assert "Manage users in the app." in result.output242526def test_command():27 result = runner.invoke(app, ["users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial004.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial004 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def test_command_help():21 result = runner.invoke(app, ["users", "--help"])22 assert result.exit_code == 023 assert "Manage users in the app." in result.output242526def test_command():27 result = runner.invoke(app, ["users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial005.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial005 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def 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.output242526def test_command():27 result = runner.invoke(app, ["new-users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial006.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial006 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def test_command_help():21 result = runner.invoke(app, ["exp-users", "--help"])22 assert result.exit_code == 023 assert "Explicit help." in result.output242526def test_command():27 result = runner.invoke(app, ["exp-users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial007.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial007 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def 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.output242526def test_command():27 result = runner.invoke(app, ["call-users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/test_name_help/test_tutorial008.py+39 added
1import subprocess23from typer.testing import CliRunner45from subcommands.name_help import tutorial008 as mod67runner = CliRunner()89app = mod.app101112def 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.output181920def 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.output242526def test_command():27 result = runner.invoke(app, ["cake-sith-users", "create", "Camila"])28 assert result.exit_code == 029 assert "Creating user: Camila" in result.output303132def 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.stdout
added:tests/test_tutorial/test_subcommands/__init__.py
added:tests/test_tutorial/test_subcommands/test_tutorial001.py+94 added
1import subprocess23import pytest4from typer.testing import CliRunner56from subcommands import tutorial00178runner = CliRunner()91011@pytest.fixture()12def mod(monkeypatch):13 with monkeypatch.context() as m:14 monkeypatch.syspath_prepend(list(tutorial001.__path__)[0])15 from subcommands.tutorial001 import main1617 return main181920@pytest.fixture()21def app(mod):22 return mod.app232425def 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.output323334def 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.output424344def test_items_create(app):45 result = runner.invoke(app, ["items", "create", "Wand"])46 assert result.exit_code == 047 assert "Creating item: Wand" in result.output484950def test_items_sell(app):51 result = runner.invoke(app, ["items", "sell", "Vase"])52 assert result.exit_code == 053 assert "Selling item: Vase" in result.output545556def test_items_delete(app):57 result = runner.invoke(app, ["items", "delete", "Vase"])58 assert result.exit_code == 059 assert "Deleting item: Vase" in result.output606162def 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.output707172def test_users_create(app):73 result = runner.invoke(app, ["users", "create", "Camila"])74 assert result.exit_code == 075 assert "Creating user: Camila" in result.output767778def test_users_delete(app):79 result = runner.invoke(app, ["users", "delete", "Camila"])80 assert result.exit_code == 081 assert "Deleting user: Camila" in result.output828384def test_scripts(mod):85 from subcommands.tutorial001 import items, users8687 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.stdout
added:tests/test_tutorial/test_subcommands/test_tutorial002.py+77 added
1import subprocess23from typer.testing import CliRunner45from subcommands.tutorial002 import main as mod67app = mod.app8runner = CliRunner()91011def 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.output181920def 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.output282930def test_items_create():31 result = runner.invoke(app, ["items", "create", "Wand"])32 assert result.exit_code == 033 assert "Creating item: Wand" in result.output343536def test_items_sell():37 result = runner.invoke(app, ["items", "sell", "Vase"])38 assert result.exit_code == 039 assert "Selling item: Vase" in result.output404142def test_items_delete():43 result = runner.invoke(app, ["items", "delete", "Vase"])44 assert result.exit_code == 045 assert "Deleting item: Vase" in result.output464748def 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.output565758def test_users_create():59 result = runner.invoke(app, ["users", "create", "Camila"])60 assert result.exit_code == 061 assert "Creating user: Camila" in result.output626364def test_users_delete():65 result = runner.invoke(app, ["users", "delete", "Camila"])66 assert result.exit_code == 067 assert "Deleting user: Camila" in result.output686970def 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.stdout
added:tests/test_tutorial/test_subcommands/test_tutorial003.py+146 added
1import subprocess23import pytest4from typer.testing import CliRunner56from subcommands import tutorial00378runner = CliRunner()91011@pytest.fixture()12def mod(monkeypatch):13 with monkeypatch.context() as m:14 m.syspath_prepend(list(tutorial003.__path__)[0])15 from subcommands.tutorial003 import main1617 return main181920@pytest.fixture()21def app(mod):22 return mod.app232425def 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.output333435def 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.output434445def test_items_create(app):46 result = runner.invoke(app, ["items", "create", "Wand"])47 assert result.exit_code == 048 assert "Creating item: Wand" in result.output495051def test_items_sell(app):52 result = runner.invoke(app, ["items", "sell", "Vase"])53 assert result.exit_code == 054 assert "Selling item: Vase" in result.output555657def test_items_delete(app):58 result = runner.invoke(app, ["items", "delete", "Vase"])59 assert result.exit_code == 060 assert "Deleting item: Vase" in result.output616263def 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.output717273def test_users_create(app):74 result = runner.invoke(app, ["users", "create", "Camila"])75 assert result.exit_code == 076 assert "Creating user: Camila" in result.output777879def test_users_delete(app):80 result = runner.invoke(app, ["users", "delete", "Camila"])81 assert result.exit_code == 082 assert "Deleting user: Camila" in result.output838485def 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.output929394def 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.output101102103def 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.output107108109def 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.output113114115def 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.output122123124def 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.output128129130def 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.output134135136def test_scripts(mod):137 from subcommands.tutorial003 import items, lands, reigns, towns, users138139 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.stdout
modified:typer/__init__.py+7 added-13 removed
1"""Typer, build great CLIs. Easy to code. Based on Python type hints."""23__version__ = "0.0.7"45from click.exceptions import Abort, Exit # noqa6from click.termui import ( # noqa5from click.exceptions import Abort, Exit6from click.termui import (7 clear,8 confirm,9 echo_via_pager,10 edit,
6 unmodified lines
17 secho,18 style,19 unstyle,20)21from click.utils import ( # noqa21from click.utils import (22 echo,23 format_filename,24 get_app_dir,25 get_binary_stream,26 get_text_stream,27 open_file,28)2930from . import colors # noqa31from .main import Typer, run # noqa32from .models import ( # noqa33 Context,34 FileBinaryRead,35 FileBinaryWrite,36 FileText,37 FileTextWrite,38)39from .params import Argument, Option # noqa30from . import colors31from .main import Typer, run32from .models import Context, FileBinaryRead, FileBinaryWrite, FileText, FileTextWrite33from .params import Argument, Option
modified:typer/main.py+29 added-18 removed
259 unmodified lines
260 return None261262263def 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.value306307308def 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 lines
334 # 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)340341342def get_group_from_info(group_info: TyperInfo) -> click.Command:
390 unmodified lines
modified:.travis.yml+1 added-1 removed
14 unmodified lines
15 - python: "nightly"1617install:18 - pip install flit19 - flit install --symlink19 - flit install --deps=develop --symlink2021script:22 - bash scripts/test.sh23
9 unmodified lines
modified:mkdocs.yml+4 added
45 unmodified lines
46 - 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 lines
modified:pyproject.toml+4 added-1 removed
35 unmodified lines
36Documentation = "https://typer.tiangolo.com/"3738[tool.flit.metadata.requires-extra]39test = [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