Skip to content
Myr

📝 Update docs to use `Typer()` more prominently (#1418)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sofie Van Landeghem · committed by GitHub · parent ae80129 · Browse files · 199 files+917 added−432 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>

Diff stats

199 files+917 added−432 removed

  • tests:+41 added−38 removed
  • other:+876 added−394 removed

199 files+917 added−432 removed

modified:.github/DISCUSSION_TEMPLATE/questions.yml+3 added-1 removed
modified:docs/tutorial/arguments/default.md+2 added-2 removed
6 unmodified lines
7## An optional *CLI argument* with a default89We can also use `typer.Argument()` to make a *CLI argument* have a default value other than `None`:1011{* docs_src/arguments/default/tutorial001_an.py hl[5] *}11{* docs_src/arguments/default/tutorial001_an.py hl[8] *}1213/// tip1415Because now the value will be a `str` passed by the user or the default value of `"Wade Wilson"` which is also a `str`, we know the value will never be `None`, so we don't have to (and shouldn't) use `Optional[str]`.
35 unmodified lines
51## Dynamic default value5253And we can even make the default value be dynamically generated by passing a function as the `default_factory` argument:5455{* docs_src/arguments/default/tutorial002_an.py hl[7:8,11] *}55{* docs_src/arguments/default/tutorial002_an.py hl[10:11,14] *}5657In this case, we created the function `get_name` that will just return a random `str` each time.5859And we pass it as the first function argument to `typer.Argument()`.
43 unmodified lines
modified:docs/tutorial/arguments/envvar.md+3 added-3 removed
8 unmodified lines
9///1011To do that, use the `envvar` parameter for `typer.Argument()`:1213{* docs_src/arguments/envvar/tutorial001_an.py hl[5] *}13{* docs_src/arguments/envvar/tutorial001_an.py hl[8] *}1415In this case, the *CLI argument* `name` will have a default value of `"World"`, but will also read any value passed to the environment variable `AWESOME_NAME` if no value is provided in the command line:1617<div class="termy">
36 unmodified lines
54## Multiple environment variables5556You are not restricted to a single environment variable, you can declare a list of environment variables that could be used to get a value if it was not passed in the command line:5758{* docs_src/arguments/envvar/tutorial002_an.py hl[6] *}58{* docs_src/arguments/envvar/tutorial002_an.py hl[9] *}5960Check it:6162<div class="termy">
26 unmodified lines
89## Hide an env var from the help text9091By default, environment variables used will be shown in the help text, but you can disable them with `show_envvar=False`:9293{* docs_src/arguments/envvar/tutorial003_an.py hl[7] *}93{* docs_src/arguments/envvar/tutorial003_an.py hl[10] *}9495Check it:9697<div class="termy">
29 unmodified lines
modified:docs/tutorial/arguments/help.md+8 added-8 removed
10 unmodified lines
11## Add a `help` text for a *CLI argument*1213You can use the `help` parameter to add a help text for a *CLI argument*:1415{* docs_src/arguments/help/tutorial001_an.py hl[5] *}15{* docs_src/arguments/help/tutorial001_an.py hl[8] *}1617And it will be used in the automatic `--help` option:1819<div class="termy">
16 unmodified lines
36## Combine help text and docstrings3738And of course, you can also combine that `help` with the <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>:3940{* docs_src/arguments/help/tutorial002_an.py hl[5:8] *}40{* docs_src/arguments/help/tutorial002_an.py hl[8:11] *}4142And the `--help` option will combine all the information:4344<div class="termy">
18 unmodified lines
63## Help with defaults6465If you have a *CLI argument* with a default value, like `"World"`:6667{* docs_src/arguments/help/tutorial003_an.py hl[5] *}67{* docs_src/arguments/help/tutorial003_an.py hl[8] *}6869It will show that default value in the help text:7071<div class="termy">
16 unmodified lines
88</div>8990But you can disable that if you want to, with `show_default=False`:9192{* docs_src/arguments/help/tutorial004_an.py hl[7] *}92{* docs_src/arguments/help/tutorial004_an.py hl[10] *}9394And then it won't show the default value:9596<div class="termy">
26 unmodified lines
123## Custom default string124125You can use the same `show_default` to pass a custom string (instead of a `bool`) to customize the default value to be shown in the help text:126127{* docs_src/arguments/help/tutorial005_an.py hl[9] *}127{* docs_src/arguments/help/tutorial005_an.py hl[12] *}128129And it will be used in the help text:130131<div class="termy">
36 unmodified lines
168But you can customize it with the `metavar` parameter for `typer.Argument()`.169170For example, let's say you don't want to have the default of `NAME`, you want to have `username`, in lowercase, and you really want ✨ emojis ✨ everywhere:171172{* docs_src/arguments/help/tutorial006_an.py hl[5] *}172{* docs_src/arguments/help/tutorial006_an.py hl[8] *}173174Now the generated help text will have `✨username✨` instead of `NAME`:175176<div class="termy">
17 unmodified lines
194You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.195196If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel where you want this *CLI argument* to be shown:197198{* docs_src/arguments/help/tutorial007_an.py hl[8,12] *}198{* docs_src/arguments/help/tutorial007_an.py hl[11,15] *}199200Then, if you check the `--help` option, you will see a default panel named "`Arguments`" for the *CLI arguments* that don't have a custom `rich_help_panel`.201202And next you will see other panels for the *CLI arguments* that have a custom panel set in the `rich_help_panel` parameter:
34 unmodified lines
237If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.238239You will probably not want to do this normally, but it's possible:240241{* docs_src/arguments/help/tutorial008_an.py hl[5] *}241{* docs_src/arguments/help/tutorial008_an.py hl[8] *}242243Check it:244245<div class="termy">
48 unmodified lines
modified:docs/tutorial/arguments/optional.md+11 added-8 removed
37 unmodified lines
38{* docs_src/first_steps/tutorial002.py hl[4] *}3940Now let's see an alternative way to create the same *CLI argument*:4142{* docs_src/arguments/optional/tutorial000.py hl[4] *}4343{* docs_src/arguments/optional/tutorial001_an.py hl[5] *}44Or, using an explicit `Typer()` instance creation:4546{* docs_src/arguments/optional/tutorial001_an.py hl[8] *}4748/// info4950Typer added support for `Annotated` (and started recommending it) in version 0.9.0.51
61 unmodified lines
113Now, finally what we came for, an optional *CLI argument*.114115To make a *CLI argument* optional, use `typer.Argument()` and make sure to provide a "default" value, for example `"World"`:116114{* docs_src/arguments/optional/tutorial002_an.py hl[5] *}117{* docs_src/arguments/optional/tutorial002_an.py hl[8] *}118119Now we have:120121```Python
58 unmodified lines
180**Typer** also supports another older alternative syntax for declaring *CLI arguments* with additional metadata.181182Instead of using `Annotated`, you can use `typer.Argument()` as the default value:183181{* docs_src/arguments/optional/tutorial001.py hl[4] *}184{* docs_src/arguments/optional/tutorial001.py hl[7] *}185186/// tip187188Prefer to use the `Annotated` version if possible.
25 unmodified lines
214If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.215216///217215{* docs_src/arguments/optional/tutorial003.py hl[4] *}218{* docs_src/arguments/optional/tutorial003.py hl[7] *}219217And the same way, you can make it optional by passing a different `default` value, for example `None`:220And the same way, you can make it optional by passing a different `default` value, for example `"World"`:221219{* docs_src/arguments/optional/tutorial002.py hl[6] *}222{* docs_src/arguments/optional/tutorial002.py hl[7] *}223221Because the first parameter passed to `typer.Argument(default=None)` (the new "default" value) is `None`, **Typer** knows that this is an **optional** *CLI argument*, if no value is provided when calling it in the command line, it will have that default value of `None`.224Because the first parameter passed to `typer.Argument(default="World")` (the new "default" value) is `"World"`, **Typer** knows that this is an **optional** *CLI argument*, if no value is provided when calling it in the command line, it will have that default value of `"World"`.225226The `default` argument is the first one, so it's possible that you see code that passes the value without explicitly using `default=`, like:227228```Python
2 unmodified lines
231232...or like:233234```Python232name: str = typer.Argument(None)235name: str = typer.Argument("World")236```237238...but again, try to use `Annotated` if possible, that way your code in terms of Python will mean the same thing as with **Typer** and you won't have to remember any of these details.
modified:docs/tutorial/commands/index.md+1 added-119 removed
44 unmodified lines
45Have that in mind so you don't get confused.4647Here I'll use **CLI application** or **program** to refer to the program you are building in Python with Typer, and **command** to refer to one of these "subcommands" of your program.4849## Explicit application5051Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.5253In the *CLI options* and *CLI argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.5455For example:5657{* docs_src/first_steps/tutorial002.py hl[9] *}5859But that is actually a shortcut. Under the hood, **Typer** converts that to a CLI application with `typer.Typer()` and executes it. All that inside of `typer.run()`.6061There's also a more explicit way to achieve the same:6263{* docs_src/commands/index/tutorial001.py hl[3,6,12] *}6465When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:6667* Create a new `typer.Typer()` "application".68* Create a new "`command`" with your function.69* Call the same "application" as if it was a function with "`app()`".7071/// info | `@decorator` Info7273That `@something` syntax in Python is called a "decorator".7475You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).7677A "decorator" takes the function below and does something with it.7879In our case, this decorator tells **Typer** that the function below is a "`command`".8081///8283Both ways, with `typer.run()` and creating the explicit application, achieve almost the same.8485/// tip8687If your use case is solved with just `typer.run()`, that's fine, you don't have to create the explicit `app` and use `@app.command()`, etc.8889You might want to do that later when your app needs the extra features, but if it doesn't need them yet, that's fine.9091///9293If you run the second example, with the explicit `app`, it works exactly the same:9495<div class="termy">9697```console98// Without a CLI argument99$ python main.py100101Usage: main.py [OPTIONS] NAME102Try "main.py --help" for help.103104Error: Missing argument 'NAME'.105106// With the NAME CLI argument107$ python main.py Camila108109Hello Camila110111// Asking for help112$ python main.py --help113114Usage: main.py [OPTIONS] NAME115116Options:117 --install-completion Install completion for the current shell.118 --show-completion Show completion for the current shell, to copy it or customize the installation.119 --help Show this message and exit.120```121122</div>123124## CLI application completion125126There's a little detail that is worth noting here.127128Now the help shows two new *CLI options*:129130* `--install-completion`131* `--show-completion`132133To get shell/tab completion, it's necessary to build a package that you and your users can install and **call directly**.134135So instead of running a Python script like:136137<div class="termy">138139```console140$ python main.py141142✨ Some magic here ✨143```144145</div>146147...It would be called like:148149<div class="termy">150151```console152$ magic-app153154✨ Some magic here ✨155```156157</div>158159Having a standalone program like that allows setting up shell/tab completion.160161The first step to be able to create an installable package like that is to use an explicit `typer.Typer()` app.162163Later you can learn all the process to create a standalone CLI application and [Build a Package](../package.md){.internal-link target=_blank}.164165But for now, it's just good to know that you are on that path. 😎16649## A CLI application with multiple commands50169Coming back to the CLI applications with multiple commands/subcommands, **Typer** allows creating CLI applications with multiple of them.51**Typer** allows creating CLI applications with multiple commands/subcommands.5253Now that you know how to create an explicit `typer.Typer()` application and add one command, let's see how to add multiple commands.5455Let's say that we have a CLI application to manage users.
136 unmodified lines
modified:docs/tutorial/commands/one-or-multiple.md+2 added-2 removed
1# One or Multiple Commands23You might have noticed that if you create a single command, as in the first example:3You might have noticed that if you create a single command, as in the following example:45{* docs_src/commands/index/tutorial001.py hl[3,6,12] *}5{* docs_src/typer_app/tutorial001.py hl[3,6,12] *}67**Typer** is smart enough to create a CLI application with that single function as the main CLI application, not as a command/subcommand:89<div class="termy">
139 unmodified lines
modified:docs/tutorial/multiple-values/arguments-with-multiple-values.md+2 added-2 removed
2 unmodified lines
3*CLI arguments* can also receive multiple values.45You can define the type of a *CLI argument* using `typing.List`.67{* docs_src/multiple_values/arguments_with_multiple_values/tutorial001.py hl[7] *}7{* docs_src/multiple_values/arguments_with_multiple_values/tutorial001.py hl[10] *}89And then you can pass it as many *CLI arguments* of that type as you want:1011<div class="termy">
24 unmodified lines
36## *CLI arguments* with tuples3738If you want a specific number of values and types, you can use a tuple, and it can even have default values:3940{* docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py hl[8:10] *}40{* docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py hl[11:13] *}4142Check it:4344<div class="termy">
34 unmodified lines
modified:docs/tutorial/multiple-values/multiple-options.md+2 added-2 removed
4 unmodified lines
5For example, let's say you want to accept several users in a single execution.67For this, use the standard Python `typing.List` to declare it as a `list` of `str`:89{* docs_src/multiple_values/multiple_options/tutorial001_an.py hl[1,7] *}9{* docs_src/multiple_values/multiple_options/tutorial001_an.py hl[1,10] *}1011You will receive the values as you declared them, as a `list` of `str`.1213Check it:
25 unmodified lines
39## Multiple `float`4041The same way, you can use other types and they will be converted by **Typer** to their declared type:4243{* docs_src/multiple_values/multiple_options/tutorial002_an.py hl[7] *}43{* docs_src/multiple_values/multiple_options/tutorial002_an.py hl[10] *}4445Check it:4647<div class="termy">
18 unmodified lines
modified:docs/tutorial/multiple-values/options-with-multiple-values.md+1 added-1 removed
4 unmodified lines
5You can set the number of values and types to anything you want, but it has to be a fixed number of values.67For this, use the standard Python `typing.Tuple`:89{* docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py hl[1,7] *}9{* docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py hl[1,10] *}1011Each of the internal types defines the type of each value in the tuple.1213So:
80 unmodified lines
modified:docs/tutorial/options/callback-and-context.md+4 added-4 removed
6 unmodified lines
7## Validate *CLI parameters*89For example, you could do some validation before the rest of the code is executed.1011{* docs_src/options/callback/tutorial001_an.py hl[7:10,13] *}11{* docs_src/options/callback/tutorial001_an.py hl[9:12,16] *}1213Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.1415The function receives the value from the command line. It can do anything with it, and then return the value.
77 unmodified lines
93### Breaking completion in a callback9495Let's say that when the callback is running, we want to show a message saying that it's validating the name:9697{* docs_src/options/callback/tutorial002_an.py hl[8] *}97{* docs_src/options/callback/tutorial002_an.py hl[10] *}9899And because the callback will be called when the shell calls your program asking for completion, that message `"Validating name"` will be printed and it will break completion.100101It will look something like:
26 unmodified lines
128But you can access the context by declaring a function parameter of type `typer.Context`.129130The "context" has some additional data about the current execution of your program:131132{* docs_src/options/callback/tutorial003_an.py hl[7:9] *}132{* docs_src/options/callback/tutorial003_an.py hl[9:11] *}133134The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.135136But it will be `False` when calling the program normally. So you can continue the execution of your previous code.
23 unmodified lines
160## Using the `CallbackParam` object161162The same way you can access the `typer.Context` by declaring a function parameter with its value, you can declare another function parameter with type `typer.CallbackParam` to get the specific Click `Parameter` object.163164{* docs_src/options/callback/tutorial004_an.py hl[7,10] *}164{* docs_src/options/callback/tutorial004_an.py hl[9,12] *}165166It's probably not very common, but you could do it if you need it.167168For example if you had a callback that could be used by several *CLI parameters*, that way the callback could know which parameter is each time.
43 unmodified lines
modified:docs/tutorial/options/help.md+4 added-4 removed
2 unmodified lines
3You already saw how to add a help text for *CLI arguments* with the `help` parameter.45Let's now do the same for *CLI options*:67{* docs_src/options/help/tutorial001_an.py hl[7:8] *}7{* docs_src/options/help/tutorial001_an.py hl[10:11] *}89The same way as with `typer.Argument()`, we can put `typer.Option()` inside of `Annotated`.1011We can then pass the `help` keyword parameter:
43 unmodified lines
55The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.5657If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel you want for each *CLI option*:5859{* docs_src/options/help/tutorial002_an.py hl[11,17] *}59{* docs_src/options/help/tutorial002_an.py hl[14,20] *}6061Now, when you check the `--help` option, you will see a default panel named "`Options`" for the *CLI options* that don't have a custom `rich_help_panel`.6263And below you will see other panels for the *CLI options* that have a custom panel set in the `rich_help_panel` parameter:
37 unmodified lines
101## Hide default from help102103You can tell Typer to not show the default value in the help text with `show_default=False`:104105{* docs_src/options/help/tutorial003_an.py hl[5] *}105{* docs_src/options/help/tutorial003_an.py hl[8] *}106107And it will no longer show the default value in the help text:108109<div class="termy">
28 unmodified lines
138## Custom default string139140You can use the same `show_default` to pass a custom string (instead of a `bool`) to customize the default value to be shown in the help text:141142{* docs_src/options/help/tutorial004_an.py hl[7] *}142{* docs_src/options/help/tutorial004_an.py hl[10] *}143144And it will be used in the help text:145146<div class="termy">
19 unmodified lines
modified:docs/tutorial/options/name.md+5 added-5 removed
26 unmodified lines
27Let's say the function parameter name is `user_name` as above, but you want the *CLI option* to be just `--name`.2829You can pass the *CLI option* name that you want to have in the following positional argument passed to `typer.Option()`:3031{* docs_src/options/name/tutorial001_an.py hl[5] *}31{* docs_src/options/name/tutorial001_an.py hl[8] *}3233/// info3435"<a href="https://docs.python.org/3.8/glossary.html#term-argument" class="external-link" target="_blank">Positional</a>" means that it's not a function argument with a keyword name.
148 unmodified lines
184You can overwrite the *CLI option* name to use as in the previous example, but you can also declare extra alternatives, including short names.185186For example, extending the previous example, let's add a *CLI option* short name `-n`:187188{* docs_src/options/name/tutorial002_an.py hl[5] *}188{* docs_src/options/name/tutorial002_an.py hl[8] *}189190Here we are overwriting the *CLI option* name that by default would be `--user-name`, and we are defining it to be `--name`. And we are also declaring a *CLI option* short name of `-n`.191192Check it:
22 unmodified lines
215### *CLI option* only short name216217If you only declare a short name like `-n` then that will be the only *CLI option* name. And neither `--name` nor `--user-name` will be available.218219{* docs_src/options/name/tutorial003_an.py hl[5] *}219{* docs_src/options/name/tutorial003_an.py hl[8] *}220221Check it:222223<div class="termy">
19 unmodified lines
243### *CLI option* short name and default244245Continuing with the example above, as **Typer** allows you to declare a *CLI option* as having only a short name, if you want to have the default long name plus a short name, you have to declare both explicitly:246247{* docs_src/options/name/tutorial004_an.py hl[5] *}247{* docs_src/options/name/tutorial004_an.py hl[8] *}248249Check it:250251<div class="termy">
25 unmodified lines
277You can create multiple short names and use them together.278279You don't have to do anything special for it to work (apart from declaring those short versions):280281{* docs_src/options/name/tutorial005_an.py hl[6:7] *}281{* docs_src/options/name/tutorial005_an.py hl[9:10] *}282283/// tip284285Notice that, again, we are declaring the long and short version of the *CLI option* names.
32 unmodified lines
modified:docs/tutorial/options/password.md+2 added-2 removed
1# Password CLI Option and Confirmation Prompt23Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:45{* docs_src/options/password/tutorial001_an.py hl[7] *}5{* docs_src/options/password/tutorial001_an.py hl[10] *}67And the CLI program will ask for confirmation:89<div class="termy">
19 unmodified lines
29You can achieve the same using `hide_input=True`.3031And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:3233{* docs_src/options/password/tutorial002_an.py hl[8] *}33{* docs_src/options/password/tutorial002_an.py hl[11] *}3435Check it:3637<div class="termy">
14 unmodified lines
modified:docs/tutorial/options/prompt.md+3 added-3 removed
1# CLI Option Prompt23It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:45{* docs_src/options/prompt/tutorial001_an.py hl[5] *}5{* docs_src/options/prompt/tutorial001_an.py hl[8] *}67And then your program will ask the user for it in the terminal:89<div class="termy">
13 unmodified lines
23## Customize the prompt2425You can also set a custom prompt, passing the string that you want to use instead of just `True`:2627{* docs_src/options/prompt/tutorial002_an.py hl[7] *}27{* docs_src/options/prompt/tutorial002_an.py hl[10] *}2829And then your program will ask for it using with your custom prompt:3031<div class="termy">
17 unmodified lines
49You can do it passing the parameter `confirmation_prompt=True`.5051Let's say it's a CLI app to delete a project:5253{* docs_src/options/prompt/tutorial003_an.py hl[6] *}53{* docs_src/options/prompt/tutorial003_an.py hl[9] *}5455And it will prompt the user for a value and then for the confirmation:5657<div class="termy">
27 unmodified lines
modified:docs/tutorial/options/required.md+3 added-3 removed
11 unmodified lines
12To make a *CLI option* required, you can put `typer.Option()` inside of `Annotated` and leave the parameter without a default value.1314Let's make `--lastname` a required *CLI option*:1516{* docs_src/options/required/tutorial001_an.py hl[5] *}16{* docs_src/options/required/tutorial001_an.py hl[8] *}1718The same way as with `typer.Argument()`, the old style of using the function parameter default value is also supported, in that case you would just not pass anything to the `default` parameter.1920{* docs_src/options/required/tutorial001.py hl[4] *}20{* docs_src/options/required/tutorial001.py hl[7] *}2122Or you can explicitly pass `...` to `typer.Option(default=...)`:2324{* docs_src/options/required/tutorial002.py hl[4] *}24{* docs_src/options/required/tutorial002.py hl[7] *}2526/// info2728If you hadn't seen that `...` before: it is a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" class="external-link" target="_blank">part of Python and is called "Ellipsis"</a>.
43 unmodified lines
modified:docs/tutorial/options/version.md+3 added-3 removed
6 unmodified lines
7## First version of `--version`89Let's see a first version of how it could look like:1011{* docs_src/options/version/tutorial001_an.py hl[9:12,17:19] *}11{* docs_src/options/version/tutorial001_an.py hl[11:14,20:22] *}1213/// tip1415Notice that we don't have to get the `typer.Context` and check for `ctx.resilient_parsing` for completion to work, because we only print and modify the program when `--version` is passed, otherwise, nothing is printed or changed from the callback.
40 unmodified lines
56## Previous parameters and `is_eager`5758But now let's say that the `--name` *CLI option* that we declared before `--version` is required, and it has a callback that could exit the program:5960{* docs_src/options/version/tutorial002_an.py hl[15:17,22:24] *}60{* docs_src/options/version/tutorial002_an.py hl[17:19,25:27] *}6162Then our CLI program could not work as expected in some cases as it is *right now*, because if we use `--version` after `--name` then the callback for `--name` will be processed before and we can get its error:6364<div class="termy">
30 unmodified lines
95For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.9697That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:9899{* docs_src/options/version/tutorial003_an.py hl[23:26] *}99{* docs_src/options/version/tutorial003_an.py hl[26:29] *}100101Check it:102103<div class="termy">
9 unmodified lines
modified:docs/tutorial/parameter-types/bool.md+4 added-4 removed
8 unmodified lines
9Let's say that we want a `--force` *CLI option* only, we want to discard `--no-force`.1011We can do that by specifying the exact name we want:1213{* docs_src/parameter_types/bool/tutorial001_an.py hl[5] *}13{* docs_src/parameter_types/bool/tutorial001_an.py hl[8] *}1415Now there's only a `--force` *CLI option*:1617<div class="termy">
39 unmodified lines
57We might want to instead have `--accept` and `--reject`.5859We can do that by passing a single `str` with the 2 names for the `bool` *CLI option* separated by `/`:6061{* docs_src/parameter_types/bool/tutorial002_an.py hl[7] *}61{* docs_src/parameter_types/bool/tutorial002_an.py hl[10] *}6263Check it:6465<div class="termy">
32 unmodified lines
98The same way, you can declare short versions of the names for these *CLI options*.99100For example, let's say we want `-f` for `--force` and `-F` for `--no-force`:101102{* docs_src/parameter_types/bool/tutorial003_an.py hl[5] *}102{* docs_src/parameter_types/bool/tutorial003_an.py hl[8] *}103104Check it:105106<div class="termy">
27 unmodified lines
134If you want to (although it might not be a good idea), you can declare only *CLI option* names to set the `False` value.135136To do that, use a space and a single `/` and pass the negative name after:137138{* docs_src/parameter_types/bool/tutorial004_an.py hl[5] *}138{* docs_src/parameter_types/bool/tutorial004_an.py hl[8] *}139140/// tip141142Have in mind that it's a string with a preceding space and then a `/`.
37 unmodified lines
modified:docs/tutorial/parameter-types/custom-types.md+2 added-2 removed
11 unmodified lines
12## Type Parser1314`typer.Argument` and `typer.Option` can create custom parameter types with a `parser` <abbr title="something that can be called like a function">callable</abbr>.1516{* docs_src/parameter_types/custom_types/tutorial001_an.py hl[13:14,18:19] *}16{* docs_src/parameter_types/custom_types/tutorial001_an.py hl[13:14,22:23] *}1718The function (or callable) that you pass to the parameter `parser` will receive the input value as a string and should return the parsed value with your own custom type.1920## Click Custom Type2122If you already have a <a href="https://click.palletsprojects.com/en/8.1.x/parameters/#implementing-custom-types" class="external-link" target="_blank">Click Custom Type</a>, you can use it in `typer.Argument()` and `typer.Option()` with the `click_type` parameter.2324{* docs_src/parameter_types/custom_types/tutorial002_an.py hl[14:18,22:25] *}24{* docs_src/parameter_types/custom_types/tutorial002_an.py hl[14:18,26:29] *}
modified:docs/tutorial/parameter-types/datetime.md+2 added-2 removed
2 unmodified lines
3You can specify a *CLI parameter* as a Python <a href="https://docs.python.org/3/library/datetime.html" class="external-link" target="_blank">`datetime`</a>.45Your function will receive a standard Python `datetime` object, and again, your editor will give you completion, etc.67{* docs_src/parameter_types/datetime/tutorial001.py hl[1,6,7,8] *}7{* docs_src/parameter_types/datetime/tutorial001.py hl[1,9,10,11] *}89Typer will accept any string from the following formats:1011* `%Y-%m-%d`
45 unmodified lines
57* separated with "`/`"5859...It's a crazy example, but let's say you also needed that strange format:6061{* docs_src/parameter_types/datetime/tutorial002_an.py hl[11] *}61{* docs_src/parameter_types/datetime/tutorial002_an.py hl[14] *}6263/// tip6465Notice the last string in `formats`: `"%m/%d/%Y"`.
20 unmodified lines
modified:docs/tutorial/parameter-types/enum.md+4 added-4 removed
1# Enum - Choices23To define a *CLI parameter* that can take a value from a predefined set of values you can use a standard Python <a href="https://docs.python.org/3/library/enum.html" class="external-link" target="_blank">`enum.Enum`</a>:45{* docs_src/parameter_types/enum/tutorial001.py hl[1,6,7,8,9,12,13] *}5{* docs_src/parameter_types/enum/tutorial001.py hl[1,6:9,16:17] *}67/// tip89Notice that the function parameter `network` will be an `Enum`, not a `str`.
43 unmodified lines
53### Case insensitive Enum choices5455You can make an `Enum` (choice) *CLI parameter* be case-insensitive with the `case_sensitive` parameter:5657{* docs_src/parameter_types/enum/tutorial002_an.py hl[15] *}57{* docs_src/parameter_types/enum/tutorial002_an.py hl[19] *}5859And then the values of the `Enum` will be checked no matter if lower case, upper case, or a mix:6061<div class="termy">
15 unmodified lines
77### List of Enum values7879A *CLI parameter* can also take a list of `Enum` values:8081{* docs_src/parameter_types/enum/tutorial003_an.py hl[14] *}81{* docs_src/parameter_types/enum/tutorial003_an.py hl[18] *}8283This works just like any other parameter value taking a list of things:8485<div class="termy">
29 unmodified lines
115### Literal choices116117You can also use `Literal` to represent a set of possible predefined choices, without having to use an `Enum`:118119{* docs_src/parameter_types/enum/tutorial004_an.py hl[6] *}119{* docs_src/parameter_types/enum/tutorial004_an.py hl[9] *}120121<div class="termy">122123```console
24 unmodified lines
modified:docs/tutorial/parameter-types/file.md+5 added-5 removed
45 unmodified lines
46```4748You will get all the correct editor support, attributes, methods, etc for the file-like object:`4950{* docs_src/parameter_types/file/tutorial001_an.py hl[5] *}50{* docs_src/parameter_types/file/tutorial001_an.py hl[8] *}5152Check it:5354<div class="termy">
18 unmodified lines
73## `FileTextWrite`7475For writing text, you can use `typer.FileTextWrite`:7677{* docs_src/parameter_types/file/tutorial002_an.py hl[5:6] *}77{* docs_src/parameter_types/file/tutorial002_an.py hl[8:9] *}7879This would be for writing human text, like:8081```
35 unmodified lines
117You will receive `bytes` from it.118119It's useful for reading binary files like images:120121{* docs_src/parameter_types/file/tutorial003_an.py hl[5] *}121{* docs_src/parameter_types/file/tutorial003_an.py hl[8] *}122123Check it:124125<div class="termy">
20 unmodified lines
146Have in mind that you have to pass `bytes` to its `.write()` method, not `str`.147148If you have a `str`, you have to encode it first to get `bytes`.149150{* docs_src/parameter_types/file/tutorial004_an.py hl[5] *}150{* docs_src/parameter_types/file/tutorial004_an.py hl[8] *}151152<div class="termy">153154```console
41 unmodified lines
196You can override the `mode` from the defaults above.197198For example, you could use `mode="a"` to write "appending" to the same file:199200{* docs_src/parameter_types/file/tutorial005_an.py hl[5] *}200{* docs_src/parameter_types/file/tutorial005_an.py hl[8] *}201202/// tip203204As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.
48 unmodified lines
modified:docs/tutorial/parameter-types/index.md+1 added-1 removed
6 unmodified lines
7When you declare a *CLI parameter* with some type **Typer** will convert the data received in the command line to that data type.89For example:1011{* docs_src/parameter_types/index/tutorial001.py hl[4] *}11{* docs_src/parameter_types/index/tutorial001.py hl[7] *}1213In this example, the value received for the *CLI argument* `NAME` will be treated as `str`.1415The value for the *CLI option* `--age` will be converted to an `int` and `--height-meters` will be converted to a `float`.
54 unmodified lines
modified:docs/tutorial/parameter-types/number.md+3 added-3 removed
1# Number23You can define numeric validations with `max` and `min` values for `int` and `float` *CLI parameters*:45{* docs_src/parameter_types/number/tutorial001_an.py hl[6:8] *}5{* docs_src/parameter_types/number/tutorial001_an.py hl[9:11] *}67*CLI arguments* and *CLI options* can both use these validations.89You can specify `min`, `max` or both.
62 unmodified lines
72You might want to, instead of showing an error, use the closest minimum or maximum valid values.7374You can do it with the `clamp` parameter:7576{* docs_src/parameter_types/number/tutorial002_an.py hl[6:8] *}76{* docs_src/parameter_types/number/tutorial002_an.py hl[9:11] *}7778And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:7980<div class="termy">
20 unmodified lines
101## Counter *CLI options*102103You can make a *CLI option* work as a counter with the `count` parameter:104105{* docs_src/parameter_types/number/tutorial003_an.py hl[5] *}105{* docs_src/parameter_types/number/tutorial003_an.py hl[8] *}106107It means that the *CLI option* will be like a boolean flag, e.g. `--verbose`.108109And the value you receive in the function will be the amount of times that `--verbose` was added:
36 unmodified lines
modified:docs/tutorial/parameter-types/path.md+2 added-2 removed
2 unmodified lines
3You can declare a *CLI parameter* to be a standard Python <a href="https://docs.python.org/3/library/pathlib.html#basic-use" class="external-link" target="_blank">`pathlib.Path`</a>.45This is what you would do for directory paths, file paths, etc:67{* docs_src/parameter_types/path/tutorial001_an.py hl[1,8] *}7{* docs_src/parameter_types/path/tutorial001_an.py hl[1,11] *}89And again, as you receive a standard Python `Path` object the same as the type annotation, your editor will give you autocompletion for all its attributes and methods.1011Check it:
52 unmodified lines
64///6566For example:6768{* docs_src/parameter_types/path/tutorial002_an.py hl[11:16] *}68{* docs_src/parameter_types/path/tutorial002_an.py hl[14:19] *}6970Check it:7172<div class="termy">
40 unmodified lines
modified:docs/tutorial/parameter-types/uuid.md+1 added-1 removed
20 unmodified lines
21///2223You can declare a *CLI parameter* as a UUID:2425{* docs_src/parameter_types/uuid/tutorial001.py hl[1,6,7,8] *}25{* docs_src/parameter_types/uuid/tutorial001.py hl[1,9:11] *}2627Your Python code will receive a standard Python <a href="https://docs.python.org/3.8/library/uuid.html" class="external-link" target="_blank">`UUID`</a> object with all its attributes and methods, and as you are annotating your function parameter with that type, you will have type checks, autocompletion in your editor, etc.2829Check it:
20 unmodified lines
modified:docs/tutorial/app-dir.md+1 added-1 removed
1# CLI Application Directory23You can get the application directory where you can, for example, save configuration files with `typer.get_app_dir()`:45{* docs_src/app_dir/tutorial001.py hl[9] *}5{* docs_src/app_dir/tutorial001.py hl[12] *}67It will give you a directory for storing configurations appropriate for your CLI program for the current user in each operating system.89Check it:
34 unmodified lines
modified:docs/tutorial/exceptions.md+11 added-11 removed
6 unmodified lines
7## Example Broken App89Let's take this example broken app:1011{* docs_src/exceptions/tutorial001.py hl[5] *}11{* docs_src/exceptions/tutorial001.py hl[8] *}1213This code is broken because you can't sum a string and a number (`name + 3`).1415## Exceptions with Rich
9 unmodified lines
25```console26$ python main.py2728<font color="#F92672">╭──────────────── </font><font color="#F92672"><b>Traceback (most recent call last)</b></font><font color="#F92672"> ────────────────╮</font>29<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/</font><font color="#F4BF75"><b>main.py</b></font>:<font color="#66D9EF">5</font> in <font color="#A6E22E">main</font> <font color="#F92672">│</font>29<font color="#F92672">│</font> <font color="#A37F4E">/home/user/code/superapp/</font><font color="#F4BF75"><b>main.py</b></font>:<font color="#66D9EF">8</font> in <font color="#A6E22E">main</font> <font color="#F92672">│</font>30<font color="#F92672">│</font> <font color="#F92672">│</font>31<font color="#F92672">│</font> 2 <font color="#F92672">│</font>32<font color="#F92672">│</font> 3 <font color="#F92672">│</font>33<font color="#F92672">│</font> 4 <font color="#66D9EF">def</font> <font color="#A6E22E">main</font>(name: <font color="#A1EFE4">str</font> = <font color="#F4BF75">&quot;morty&quot;</font>): <font color="#F92672">│</font>34<font color="#F92672">│</font> <font color="#F92672">❱ </font> 5 │ <font color="#A1EFE4">print</font>(name + <font color="#66D9EF">3</font>) <font color="#F92672">│</font>35<font color="#F92672">│</font> 6 <font color="#F92672">│</font>36<font color="#F92672">│</font> 7 <font color="#F92672">│</font>37<font color="#F92672">│</font> 8 <font color="#66D9EF">if</font> <font color="#F92672">__name__</font> == <font color="#F4BF75">&quot;__main__&quot;</font>: <font color="#F92672">│</font>31<font color="#F92672">│</font> 5 <font color="#F92672">│</font>32<font color="#F92672">│</font> 6 <font color="#FF00FF">@app</font>.command() <font color="#F92672">│</font>33<font color="#F92672">│</font> 7 <font color="#66D9EF">def</font> <font color="#A6E22E">main</font>(name: <font color="#A1EFE4">str</font> = <font color="#F4BF75">&quot;morty&quot;</font>): <font color="#F92672">│</font>34<font color="#F92672">│</font> <font color="#F92672">❱ </font> 8 │ <font color="#A1EFE4">print</font>(name + <font color="#66D9EF">3</font>) <font color="#F92672">│</font>35<font color="#F92672">│</font> 9 <font color="#F92672">│</font>36<font color="#F92672">│</font> 10 <font color="#F92672">│</font>37<font color="#F92672">│</font> 11 <font color="#66D9EF">if</font> <font color="#F92672">__name__</font> == <font color="#F4BF75">&quot;__main__&quot;</font>: <font color="#F92672">│</font>38<font color="#F92672">│</font> <font color="#F92672">│</font>39<font color="#F92672">│</font> <font color="#F4BF75">╭──── locals ────╮</font> <font color="#F92672">│</font>40<font color="#F92672">│</font> <font color="#F4BF75">│</font> name = <font color="#F4BF75">&apos;morty&apos;</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>41<font color="#F92672">│</font> <font color="#F4BF75">╰────────────────╯</font> <font color="#F92672">│</font>
14 unmodified lines
5657Traceback (most recent call last):5859 File "main.py", line 12, in <module>60 typer.run(main)60 app()6162 File "main.py", line 8, in main63 print(name + 3)64
17 unmodified lines
82In this case, `name` is a local variable, it comes from a parameter passed to the function.8384But if it was something like a password, you would have liked to hide it.8586In that case, you can create the `typer.Typer()` application explicitly and set the parameter `pretty_exceptions_show_locals=False`:86In that case, you can set the parameter `pretty_exceptions_show_locals=False` when creating the `typer.Typer()` application:8788{* docs_src/exceptions/tutorial002.py hl[3] *}8990And now when you run it, you will see the error without the local variables:
183 unmodified lines
modified:docs/tutorial/launch.md+2 added-2 removed
2 unmodified lines
3You can launch applications from your CLI program with `typer.launch()`.45It will launch the appropriate application depending on the URL or file type you pass it:67{* docs_src/launch/tutorial001.py hl[6] *}7{* docs_src/launch/tutorial001.py hl[9] *}89Check it:1011<div class="termy">
11 unmodified lines
23## Locating a file2425You can also make the operating system open the file browser indicating where a file is located with `locate=True`:2627{* docs_src/launch/tutorial002.py hl[17] *}27{* docs_src/launch/tutorial002.py hl[20] *}2829/// tip3031The rest of the code in this example is just making sure the app directory exists and creating the config file.
18 unmodified lines
modified:docs/tutorial/printing.md+8 added-8 removed
1# Printing and Colors23You can use the normal `print()` to show information on the screen:45{* docs_src/first_steps/tutorial001.py hl[5] *}5{* docs_src/typer_app/tutorial001.py hl[8] *}67It will show the output normally:89<div class="termy">1011```console12$ python main.py12$ python main.py World1314Hello World15```16
6 unmodified lines
23### Use Rich `print`2425For the simplest cases, you can just import `print` from `rich` and use it instead of the standard `print`:2627{* docs_src/printing/tutorial001.py hl[2,15] *}27{* docs_src/printing/tutorial001.py hl[2,18] *}2829Just with that, **Rich** will be able to print your data with nice colors and structure:3031<div class="termy">
19 unmodified lines
51### Rich Markup5253Rich also supports a <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">custom markup syntax</a> to set colors and styles, for example:5455{* docs_src/printing/tutorial002.py hl[6] *}55{* docs_src/printing/tutorial002.py hl[9] *}5657<div class="termy">5859```console
15 unmodified lines
75When you call Rich's `print`, it automatically creates this object and uses it.7677But for advanced use cases, you could create a `Console` yourself.7879{* docs_src/printing/tutorial003.py hl[2:3,5,9:12] *}79{* docs_src/printing/tutorial003.py hl[2:3,5,12:15] *}8081In this example, we create a `Console`, and a `Table`. And then we can add some rows to the table, and print it.8283If you run it, you will see a nicely formatted table:
67 unmodified lines
151///152153Using `stderr=True` tells **Rich** that the output should be shown in "standard error".154155{* docs_src/printing/tutorial004.py hl[4,8] *}155{* docs_src/printing/tutorial004.py hl[4,11] *}156157When you try it in the terminal, it will probably just look the same:158159<div class="termy">
67 unmodified lines
227///228229You can create colored strings to output to the terminal with `typer.style()`, that gives you `str`s that you can then pass to `typer.echo()`:230231{* docs_src/printing/tutorial005.py hl[7,9] *}231{* docs_src/printing/tutorial005.py hl[10,12] *}232233/// tip234235The parameters `fg` and `bg` receive strings with the color names for the "**f**ore**g**round" and "**b**ack**g**round" colors. You could simply pass `fg="green"` and `bg="red"`.
37 unmodified lines
273///274275There's a shorter form to style and print at the same time with `typer.secho()` it's like `typer.echo()` but also adds style like `typer.style()`:276277{* docs_src/printing/tutorial006.py hl[5] *}277{* docs_src/printing/tutorial006.py hl[8] *}278279Check it:280281<div class="use-termynal" data-termynal>
3 unmodified lines
modified:docs/tutorial/progressbar.md+6 added-6 removed
4 unmodified lines
5## Progress Bar67You can use <a href="https://rich.readthedocs.io/en/stable/progress.html" class="external-link" target="_blank">Rich's Progress Display</a> to show a progress bar, for example:89{* docs_src/progressbar/tutorial001.py hl[4,9] *}9{* docs_src/progressbar/tutorial001.py hl[4,12] *}1011You put the thing that you want to iterate over inside of Rich's `track()`, and then iterate over that.1213Check it:
31 unmodified lines
45Rich allows you to display many things in complex and advanced ways.4647For example, this will show two spinners:4849{* docs_src/progressbar/tutorial002.py hl[4,8:15] *}49{* docs_src/progressbar/tutorial002.py hl[4,11:18] *}5051I can't show you the beautiful animation here in the docs. 😅5253But at some point in time it will look like this (imagine it's spinning). 🤓
45 unmodified lines
99```100101And you pass as function argument to `typer.progressbar()` the thing that you would normally iterate over.102103{* docs_src/progressbar/tutorial003.py hl[8] *}103{* docs_src/progressbar/tutorial003.py hl[11] *}104105So, if you have a list of users, this could be:106107```Python
54 unmodified lines
162The progress bar is generated from the length of the iterable (e.g. the list of users).163164But if the length is not available (for example, with something that fetches a new user from a web API each time) you can pass an explicit `length` to `typer.progressbar()`.165166{* docs_src/progressbar/tutorial004.py hl[14] *}166{* docs_src/progressbar/tutorial004.py hl[18] *}167168Check it:169170<div class="termy">
39 unmodified lines
210///211212You can also set a `label`:213214{* docs_src/progressbar/tutorial005.py hl[8] *}214{* docs_src/progressbar/tutorial005.py hl[11] *}215216Check it:217218<div class="use-termynal">
7 unmodified lines
226If you need to manually iterate over something and update the progress bar irregularly, you can do it by not passing an iterable but just a `length` to `typer.progressbar()`.227228And then calling the `.update()` method in the object from the `with` statement:229230{* docs_src/progressbar/tutorial006.py hl[8,12] *}230{* docs_src/progressbar/tutorial006.py hl[11,17] *}231232Check it:233234<div class="use-termynal">
4 unmodified lines
modified:docs/tutorial/prompt.md+4 added-4 removed
2 unmodified lines
3When you need to ask the user for info interactively you should normally use [*CLI Option*s with Prompt](options/prompt.md){.internal-link target=_blank}, because they allow using the CLI program in a non-interactive way (for example, a Bash script could use it).45But if you absolutely need to ask for interactive information without using a *CLI option*, you can use `typer.prompt()`:67{* docs_src/prompt/tutorial001.py hl[5] *}7{* docs_src/prompt/tutorial001.py hl[8] *}89Check it:1011<div class="termy">
11 unmodified lines
23## Confirm2425There's also an alternative to ask for confirmation. Again, if possible, you should use a [*CLI Option* with a confirmation prompt](options/prompt.md){.internal-link target=_blank}:2627{* docs_src/prompt/tutorial002.py hl[5] *}27{* docs_src/prompt/tutorial002.py hl[8] *}2829Check it:3031<div class="termy">
19 unmodified lines
51## Confirm or abort5253As it's very common to abort if the user doesn't confirm, there's an integrated parameter `abort` that does it automatically:5455{* docs_src/prompt/tutorial003.py hl[5] *}55{* docs_src/prompt/tutorial003.py hl[8] *}5657<div class="termy">5859```console
16 unmodified lines
76## Prompt with Rich7778If you installed Rich as described in [Printing and Colors](printing.md){.internal-link target=_blank}, you can use Rich to prompt the user for input:7980{* docs_src/prompt/tutorial004.py hl[2,6] *}80{* docs_src/prompt/tutorial004.py hl[2,9] *}8182And when you run it, it will look like:8384<div class="termy">
10 unmodified lines
modified:docs/tutorial/terminating.md+2 added-2 removed
54 unmodified lines
55`typer.Exit()` takes an optional `code` parameter. By default, `code` is `0`, meaning there was no error.5657You can pass a `code` with a number other than `0` to tell the terminal that there was an error in the execution of the program:5859{* docs_src/terminating/tutorial002.py hl[7] *}59{* docs_src/terminating/tutorial002.py hl[10] *}6061Check it:6263<div class="termy">
34 unmodified lines
98There's a special exception that you can use to "abort" a program.99100It works more or less the same as `typer.Exit()` but will print `"Aborted!"` to the screen and can be useful in certain cases later to make it explicit that the execution was aborted:101102{* docs_src/terminating/tutorial003.py hl[7] *}102{* docs_src/terminating/tutorial003.py hl[10] *}103104Check it:105106<div class="termy">
14 unmodified lines
added:docs/tutorial/typer-app.md+118 added
1# Typer App23## Explicit application45So far, you have seen how to create a single function and then pass that function to `typer.run()`.67For example:89{* docs_src/first_steps/tutorial002.py hl[9] *}1011But that is actually a shortcut. Under the hood, **Typer** converts that to a CLI application with `typer.Typer()` and executes it. All that inside of `typer.run()`.1213There's also a more explicit way to achieve the same:1415{* docs_src/typer_app/tutorial001.py hl[3,6,12] *}1617When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:1819* Create a new `typer.Typer()` "application".20* Create a new "`command`" with your function.21* Call the same "application" as if it was a function with "`app()`".2223/// info | `@decorator` Info2425That `@something` syntax in Python is called a "decorator".2627You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).2829A "decorator" takes the function below and does something with it.3031In our case, this decorator tells **Typer** that the function below is a "`command`".32You will learn more about commands later in the section [commands](./commands/index.md){.internal-link target=_blank}.3334///3536Both ways, with `typer.run()` and creating the explicit application, achieve almost the same.3738/// tip3940If your use case is solved with just `typer.run()`, that's fine, you don't have to create the explicit `app` and use `@app.command()`, etc.4142You might want to do that later when your app needs extra features, but if it doesn't need them yet, that's fine.4344///4546If you run the second example, with the explicit `app`, it works exactly the same:4748<div class="termy">4950```console51// Without a CLI argument52$ python main.py5354Usage: main.py [OPTIONS] NAME55Try "main.py --help" for help.5657Error: Missing argument 'NAME'.5859// With the NAME CLI argument60$ python main.py Camila6162Hello Camila6364// Asking for help65$ python main.py --help6667Usage: main.py [OPTIONS] NAME6869Options:70 --install-completion Install completion for the current shell.71 --show-completion Show completion for the current shell, to copy it or customize the installation.72 --help Show this message and exit.73```7475</div>7677## CLI application completion7879There's a little detail that is worth noting here.8081Now the help shows two new *CLI options*:8283* `--install-completion`84* `--show-completion`8586To get shell/tab completion, it's necessary to build a package that you and your users can install and **call directly**.8788So instead of running a Python script like:8990<div class="termy">9192```console93$ python main.py9495✨ Some magic here ✨96```9798</div>99100...It would be called like:101102<div class="termy">103104```console105$ magic-app106107✨ Some magic here ✨108```109110</div>111112Having a standalone program like that allows setting up shell/tab completion.113114The first step to be able to create an installable package like that is to use an explicit `typer.Typer()` app.115116Later you can learn all the process to create a standalone CLI application and [Build a Package](./package.md){.internal-link target=_blank}.117118But for now, it's just good to know that you are on that path. 😎
modified:docs_src/app_dir/tutorial001.py+4 added-1 removed
2 unmodified lines
3import typer45APP_NAME = "my-super-cli-app"67app = typer.Typer()8910@app.command()11def main():12 app_dir = typer.get_app_dir(APP_NAME)13 config_path: Path = Path(app_dir) / "config.json"14 if not config_path.is_file():15 print("Config file doesn't exist yet")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/arguments/default/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument()] = "Wade Wilson"):9 print(f"Hello {name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/arguments/default/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("Wade Wilson")):8 print(f"Hello {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/default/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def get_name():11 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])1213
1 unmodified line
15 print(f"Hello {name}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/arguments/default/tutorial002.py+4 added-1 removed
1import random23import typer45app = typer.Typer()678@app.command()9def get_name():10 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])1112
1 unmodified line
14 print(f"Hello {name}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/arguments/envvar/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument(envvar="AWESOME_NAME")] = "World"):9 print(f"Hello Mr. {name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/arguments/envvar/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", envvar="AWESOME_NAME")):8 print(f"Hello Mr. {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/envvar/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: Annotated[str, typer.Argument(envvar=["AWESOME_NAME", "GOD_NAME"])] = "World",10):11 print(f"Hello Mr. {name}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/arguments/envvar/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", envvar=["AWESOME_NAME", "GOD_NAME"])):8 print(f"Hello Mr. {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/envvar/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: Annotated[10 str, typer.Argument(envvar="AWESOME_NAME", show_envvar=False)11 ] = "World",
1 unmodified line
13 print(f"Hello Mr. {name}")141516if __name__ == "__main__":14 typer.run(main)17 app()
modified:docs_src/arguments/envvar/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", envvar="AWESOME_NAME", show_envvar=False)):8 print(f"Hello Mr. {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/help/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):9 print(f"Hello {name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/arguments/help/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument(..., help="The name of the user to greet")):8 print(f"Hello {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/help/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):9 """10 Say hi to NAME very gently, like Dirk.11 """12 print(f"Hello {name}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/arguments/help/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument(..., help="The name of the user to greet")):8 """9 Say hi to NAME very gently, like Dirk.10 """11 print(f"Hello {name}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/arguments/help/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument(help="Who to greet")] = "World"):9 """10 Say hi to NAME very gently, like Dirk.11 """12 print(f"Hello {name}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/arguments/help/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", help="Who to greet")):8 """9 Say hi to NAME very gently, like Dirk.10 """11 print(f"Hello {name}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/arguments/help/tutorial004_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: Annotated[10 str, typer.Argument(help="Who to greet", show_default=False)11 ] = "World",
4 unmodified lines
16 print(f"Hello {name}")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/arguments/help/tutorial004.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", help="Who to greet", show_default=False)):8 """9 Say hi to NAME very gently, like Dirk.10 """11 print(f"Hello {name}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/arguments/help/tutorial005_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: Annotated[10 str,11 typer.Argument(
4 unmodified lines
16 print(f"Hello {name}")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/arguments/help/tutorial005.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str = typer.Argument(9 "Wade Wilson", help="Who to greet", show_default="Deadpoolio the amazing's name"10 ),
1 unmodified line
12 print(f"Hello {name}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/arguments/help/tutorial006_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument(metavar="✨username✨")] = "World"):9 print(f"Hello {name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/arguments/help/tutorial006.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", metavar="✨username✨")):8 print(f"Hello {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/help/tutorial007_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: Annotated[str, typer.Argument(help="Who to greet")],10 lastname: Annotated[11 str, typer.Argument(help="The last name", rich_help_panel="Secondary Arguments")
9 unmodified lines
21 print(f"Hello {name}")222324if __name__ == "__main__":22 typer.run(main)25 app()
modified:docs_src/arguments/help/tutorial007.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str = typer.Argument(..., help="Who to greet"),9 lastname: str = typer.Argument(10 "", help="The last name", rich_help_panel="Secondary Arguments"
8 unmodified lines
19 print(f"Hello {name}")202122if __name__ == "__main__":20 typer.run(main)23 app()
modified:docs_src/arguments/help/tutorial008_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"):9 """10 Say hi to NAME very gently, like Dirk.11 """12 print(f"Hello {name}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/arguments/help/tutorial008.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument("World", hidden=True)):8 """9 Say hi to NAME very gently, like Dirk.10 """11 print(f"Hello {name}")121314if __name__ == "__main__":12 typer.run(main)15 app()
added:docs_src/arguments/optional/tutorial000.py+9 added
1import typer234def main(name: str = typer.Argument()):5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
modified:docs_src/arguments/optional/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument()]):9 print(f"Hello {name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/arguments/optional/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument()):8 print(f"Hello {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/optional/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Argument()] = "World"):9 print(f"Hello {name}!")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/arguments/optional/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument(default="World")):8 print(f"Hello {name}!")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/arguments/optional/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = typer.Argument(default=...)):8 print(f"Hello {name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
deleted:docs_src/commands/index/tutorial001.py-12 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str):8 print(f"Hello {name}")91011if __name__ == "__main__":12 app()
modified:docs_src/exceptions/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str = "morty"):8 print(name + 3)91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/launch/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main():8 print("Opening Typer's docs")9 typer.launch("https://typer.tiangolo.com")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/launch/tutorial002.py+4 added-1 removed
2 unmodified lines
3import typer45APP_NAME = "my-super-cli-app"67app = typer.Typer()8910@app.command()11def main():12 app_dir = typer.get_app_dir(APP_NAME)13 app_dir_path = Path(app_dir)14 app_dir_path.mkdir(parents=True, exist_ok=True)
5 unmodified lines
20 typer.launch(config_file_str, locate=True)212223if __name__ == "__main__":21 typer.run(main)24 app()
modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial001.py+4 added-1 removed
1 unmodified line
2from typing import List34import typer56app = typer.Typer()789@app.command()10def main(files: List[Path], celebration: str):11 for path in files:12 if path.is_file():13 print(f"This file exists: {path.name}")14 print(celebration)151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(11 names: Annotated[12 Tuple[str, str, str], typer.Argument(help="Select 3 characters to play with")13 ] = ("Harry", "Hermione", "Ron"),
2 unmodified lines
16 print(f"Hello {name}")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py+4 added-1 removed
1from typing import Tuple23import typer45app = typer.Typer()678@app.command()9def main(10 names: Tuple[str, str, str] = typer.Argument(11 ("Harry", "Hermione", "Ron"), help="Select 3 characters to play with"12 ),
2 unmodified lines
15 print(f"Hello {name}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/multiple_values/multiple_options/tutorial001_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(user: Annotated[Optional[List[str]], typer.Option()] = None):11 if not user:12 print(f"No provided users (raw input = {user})")13 raise typer.Abort()
1 unmodified line
15 print(f"Processing user: {u}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/multiple_values/multiple_options/tutorial001.py+4 added-1 removed
1from typing import List, Optional23import typer45app = typer.Typer()678@app.command()9def main(user: Optional[List[str]] = typer.Option(None)):10 if not user:11 print(f"No provided users (raw input = {user})")12 raise typer.Abort()
1 unmodified line
14 print(f"Processing user: {u}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/multiple_values/multiple_options/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(number: Annotated[List[float], typer.Option()] = []):11 print(f"The sum is {sum(number)}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/multiple_values/multiple_options/tutorial002.py+4 added-1 removed
1from typing import List23import typer45app = typer.Typer()678@app.command()9def main(number: List[float] = typer.Option([])):10 print(f"The sum is {sum(number)}")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(user: Annotated[Tuple[str, int, bool], typer.Option()] = (None, None, None)):11 username, coins, is_wizard = user12 if not username:13 print("No user provided")
3 unmodified lines
17 print("And this user is a wizard!")181920if __name__ == "__main__":18 typer.run(main)21 app()
modified:docs_src/multiple_values/options_with_multiple_values/tutorial001.py+4 added-1 removed
1from typing import Tuple23import typer45app = typer.Typer()678@app.command()9def main(user: Tuple[str, int, bool] = typer.Option((None, None, None))):10 username, coins, is_wizard = user11 if not username:12 print("No user provided")
3 unmodified lines
16 print("And this user is a wizard!")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/options/callback/tutorial001_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789def name_callback(value: str):10 if value != "Camila":11 raise typer.BadParameter("Only Camila is allowed")12 return value131415@app.command()16def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):17 print(f"Hello {name}")181920if __name__ == "__main__":18 typer.run(main)21 app()
modified:docs_src/options/callback/tutorial001.py+4 added-1 removed
1from typing import Optional23import typer45app = typer.Typer()678def name_callback(value: str):9 if value != "Camila":10 raise typer.BadParameter("Only Camila is allowed")11 return value121314@app.command()15def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):16 print(f"Hello {name}")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/options/callback/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789def name_callback(value: str):10 print("Validating name")11 if value != "Camila":12 raise typer.BadParameter("Only Camila is allowed")13 return value141516@app.command()17def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):18 print(f"Hello {name}")192021if __name__ == "__main__":19 typer.run(main)22 app()
modified:docs_src/options/callback/tutorial002.py+4 added-1 removed
1from typing import Optional23import typer45app = typer.Typer()678def name_callback(value: str):9 print("Validating name")10 if value != "Camila":11 raise typer.BadParameter("Only Camila is allowed")12 return value131415@app.command()16def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):17 print(f"Hello {name}")181920if __name__ == "__main__":18 typer.run(main)21 app()
modified:docs_src/options/callback/tutorial003_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789def name_callback(ctx: typer.Context, value: str):10 if ctx.resilient_parsing:11 return12 print("Validating name")
1 unmodified line
14 raise typer.BadParameter("Only Camila is allowed")15 return value161718@app.command()19def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):20 print(f"Hello {name}")212223if __name__ == "__main__":21 typer.run(main)24 app()
modified:docs_src/options/callback/tutorial003.py+4 added-1 removed
1from typing import Optional23import typer45app = typer.Typer()678def name_callback(ctx: typer.Context, value: str):9 if ctx.resilient_parsing:10 return11 print("Validating name")
1 unmodified line
13 raise typer.BadParameter("Only Camila is allowed")14 return value151617@app.command()18def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):19 print(f"Hello {name}")202122if __name__ == "__main__":20 typer.run(main)23 app()
modified:docs_src/options/callback/tutorial004_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):10 if ctx.resilient_parsing:11 return12 print(f"Validating param: {param.name}")
1 unmodified line
14 raise typer.BadParameter("Only Camila is allowed")15 return value161718@app.command()19def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):20 print(f"Hello {name}")212223if __name__ == "__main__":21 typer.run(main)24 app()
modified:docs_src/options/callback/tutorial004.py+4 added-1 removed
1from typing import Optional23import typer45app = typer.Typer()678def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):9 if ctx.resilient_parsing:10 return11 print(f"Validating param: {param.name}")
1 unmodified line
13 raise typer.BadParameter("Only Camila is allowed")14 return value151617@app.command()18def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):19 print(f"Hello {name}")202122if __name__ == "__main__":20 typer.run(main)23 app()
modified:docs_src/options/help/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: str,10 lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",11 formal: Annotated[bool, typer.Option(help="Say hi formally.")] = False,
9 unmodified lines
21 print(f"Hello {name} {lastname}")222324if __name__ == "__main__":22 typer.run(main)25 app()
modified:docs_src/options/help/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str,9 lastname: str = typer.Option("", help="Last name of person to greet."),10 formal: bool = typer.Option(False, help="Say hi formally."),
9 unmodified lines
20 print(f"Hello {name} {lastname}")212223if __name__ == "__main__":21 typer.run(main)24 app()
modified:docs_src/options/help/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: str,10 lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",11 formal: Annotated[
20 unmodified lines
32 print(f"Hello {name} {lastname}")333435if __name__ == "__main__":33 typer.run(main)36 app()
modified:docs_src/options/help/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str,9 lastname: str = typer.Option("", help="Last name of person to greet."),10 formal: bool = typer.Option(
14 unmodified lines
25 print(f"Hello {name} {lastname}")262728if __name__ == "__main__":26 typer.run(main)29 app()
modified:docs_src/options/help/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(fullname: Annotated[str, typer.Option(show_default=False)] = "Wade Wilson"):9 print(f"Hello {fullname}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/help/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):8 print(f"Hello {fullname}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/help/tutorial004_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 fullname: Annotated[10 str, typer.Option(show_default="Deadpoolio the amazing's name")11 ] = "Wade Wilson",
1 unmodified line
13 print(f"Hello {fullname}")141516if __name__ == "__main__":14 typer.run(main)17 app()
modified:docs_src/options/help/tutorial004.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 fullname: str = typer.Option(9 "Wade Wilson", show_default="Deadpoolio the amazing's name"10 ),
1 unmodified line
12 print(f"Hello {fullname}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/options/name/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(user_name: Annotated[str, typer.Option("--name")]):9 print(f"Hello {user_name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/name/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(user_name: str = typer.Option(..., "--name")):8 print(f"Hello {user_name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/name/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(user_name: Annotated[str, typer.Option("--name", "-n")]):9 print(f"Hello {user_name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/name/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(user_name: str = typer.Option(..., "--name", "-n")):8 print(f"Hello {user_name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/name/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(user_name: Annotated[str, typer.Option("-n")]):9 print(f"Hello {user_name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/name/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(user_name: str = typer.Option(..., "-n")):8 print(f"Hello {user_name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/name/tutorial004_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(user_name: Annotated[str, typer.Option("--user-name", "-n")]):9 print(f"Hello {user_name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/name/tutorial004.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(user_name: str = typer.Option(..., "--user-name", "-n")):8 print(f"Hello {user_name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/name/tutorial005_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: Annotated[str, typer.Option("--name", "-n")],10 formal: Annotated[bool, typer.Option("--formal", "-f")] = False,11):
3 unmodified lines
15 print(f"Hello {name}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/options/name/tutorial005.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str = typer.Option(..., "--name", "-n"),9 formal: bool = typer.Option(False, "--formal", "-f"),10):
3 unmodified lines
14 print(f"Hello {name}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/options/password/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: str,10 email: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)],11):12 print(f"Hello {name}, your email is {email}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/options/password/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str, email: str = typer.Option(..., prompt=True, confirmation_prompt=True)9):10 print(f"Hello {name}, your email is {email}")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/options/password/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: str,10 password: Annotated[11 str, typer.Option(prompt=True, confirmation_prompt=True, hide_input=True)
3 unmodified lines
15 print(f"...just kidding, here it is, very insecure: {password}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/options/password/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str,9 password: str = typer.Option(10 ..., prompt=True, confirmation_prompt=True, hide_input=True
3 unmodified lines
14 print(f"...just kidding, here it is, very insecure: {password}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/options/prompt/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):9 print(f"Hello {name} {lastname}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/prompt/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str, lastname: str = typer.Option(..., prompt=True)):8 print(f"Hello {name} {lastname}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/prompt/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 name: str,10 lastname: Annotated[str, typer.Option(prompt="Please tell me your last name")],11):12 print(f"Hello {name} {lastname}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/options/prompt/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 name: str, lastname: str = typer.Option(..., prompt="Please tell me your last name")9):10 print(f"Hello {name} {lastname}")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/options/prompt/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 project_name: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)],10):11 print(f"Deleting project {project_name}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/options/prompt/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(project_name: str = typer.Option(..., prompt=True, confirmation_prompt=True)):8 print(f"Deleting project {project_name}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/required/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: str, lastname: Annotated[str, typer.Option()]):9 print(f"Hello {name} {lastname}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/options/required/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str, lastname: str = typer.Option()):8 print(f"Hello {name} {lastname}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/required/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str, lastname: str = typer.Option(default=...)):8 print(f"Hello {name} {lastname}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/options/version/tutorial001_an.py+4 added-1 removed
3 unmodified lines
4from typing_extensions import Annotated56__version__ = "0.1.0"78app = typer.Typer()91011def version_callback(value: bool):12 if value:13 print(f"Awesome CLI Version: {__version__}")14 raise typer.Exit()151617@app.command()18def main(19 name: Annotated[str, typer.Option()] = "World",20 version: Annotated[21 Optional[bool], typer.Option("--version", callback=version_callback)
2 unmodified lines
24 print(f"Hello {name}")252627if __name__ == "__main__":25 typer.run(main)28 app()
modified:docs_src/options/version/tutorial001.py+4 added-1 removed
2 unmodified lines
3import typer45__version__ = "0.1.0"67app = typer.Typer()8910def version_callback(value: bool):11 if value:12 print(f"Awesome CLI Version: {__version__}")13 raise typer.Exit()141516@app.command()17def main(18 name: str = typer.Option("World"),19 version: Optional[bool] = typer.Option(20 None, "--version", callback=version_callback
2 unmodified lines
23 print(f"Hello {name}")242526if __name__ == "__main__":24 typer.run(main)27 app()
modified:docs_src/options/version/tutorial002_an.py+4 added-1 removed
3 unmodified lines
4from typing_extensions import Annotated56__version__ = "0.1.0"78app = typer.Typer()91011def version_callback(value: bool):12 if value:13 print(f"Awesome CLI Version: {__version__}")14 raise typer.Exit()
3 unmodified lines
18 if name != "Camila":19 raise typer.BadParameter("Only Camila is allowed")202122@app.command()23def main(24 name: Annotated[str, typer.Option(callback=name_callback)],25 version: Annotated[26 Optional[bool], typer.Option("--version", callback=version_callback)
2 unmodified lines
29 print(f"Hello {name}")303132if __name__ == "__main__":30 typer.run(main)33 app()
modified:docs_src/options/version/tutorial002.py+4 added-1 removed
2 unmodified lines
3import typer45__version__ = "0.1.0"67app = typer.Typer()8910def version_callback(value: bool):11 if value:12 print(f"Awesome CLI Version: {__version__}")13 raise typer.Exit()
3 unmodified lines
17 if name != "Camila":18 raise typer.BadParameter("Only Camila is allowed")192021@app.command()22def main(23 name: str = typer.Option(..., callback=name_callback),24 version: Optional[bool] = typer.Option(25 None, "--version", callback=version_callback
2 unmodified lines
28 print(f"Hello {name}")293031if __name__ == "__main__":29 typer.run(main)32 app()
modified:docs_src/options/version/tutorial003_an.py+4 added-1 removed
3 unmodified lines
4from typing_extensions import Annotated56__version__ = "0.1.0"78app = typer.Typer()91011def version_callback(value: bool):12 if value:13 print(f"Awesome CLI Version: {__version__}")14 raise typer.Exit()
4 unmodified lines
19 raise typer.BadParameter("Only Camila is allowed")20 return name212223@app.command()24def main(25 name: Annotated[str, typer.Option(callback=name_callback)],26 version: Annotated[27 Optional[bool],
3 unmodified lines
31 print(f"Hello {name}")323334if __name__ == "__main__":32 typer.run(main)35 app()
modified:docs_src/options/version/tutorial003.py+4 added-1 removed
2 unmodified lines
3import typer45__version__ = "0.1.0"67app = typer.Typer()8910def version_callback(value: bool):11 if value:12 print(f"Awesome CLI Version: {__version__}")13 raise typer.Exit()
4 unmodified lines
18 raise typer.BadParameter("Only Camila is allowed")19 return name202122@app.command()23def main(24 name: str = typer.Option(..., callback=name_callback),25 version: Optional[bool] = typer.Option(26 None, "--version", callback=version_callback, is_eager=True
2 unmodified lines
29 print(f"Hello {name}")303132if __name__ == "__main__":30 typer.run(main)33 app()
modified:docs_src/parameter_types/bool/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(force: Annotated[bool, typer.Option("--force")] = False):9 if force:10 print("Forcing operation")11 else:12 print("Not forcing")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/parameter_types/bool/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(force: bool = typer.Option(False, "--force")):8 if force:9 print("Forcing operation")10 else:11 print("Not forcing")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/parameter_types/bool/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(accept: Annotated[Optional[bool], typer.Option("--accept/--reject")] = None):11 if accept is None:12 print("I don't know what you want yet")13 elif accept:
2 unmodified lines
16 print("Rejecting!")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/parameter_types/bool/tutorial002.py+4 added-1 removed
1from typing import Optional23import typer45app = typer.Typer()678@app.command()9def main(accept: Optional[bool] = typer.Option(None, "--accept/--reject")):10 if accept is None:11 print("I don't know what you want yet")12 elif accept:
2 unmodified lines
15 print("Rejecting!")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/parameter_types/bool/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(force: Annotated[bool, typer.Option("--force/--no-force", "-f/-F")] = False):9 if force:10 print("Forcing operation")11 else:12 print("Not forcing")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/parameter_types/bool/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(force: bool = typer.Option(False, "--force/--no-force", "-f/-F")):8 if force:9 print("Forcing operation")10 else:11 print("Not forcing")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/parameter_types/bool/tutorial004_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(in_prod: Annotated[bool, typer.Option(" /--demo", " /-d")] = True):9 if in_prod:10 print("Running in production")11 else:12 print("Running demo")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/parameter_types/bool/tutorial004.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(in_prod: bool = typer.Option(True, " /--demo", " /-d")):8 if in_prod:9 print("Running in production")10 else:11 print("Running demo")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/parameter_types/custom_types/tutorial001_an.py+5 added-1 removed
12 unmodified lines
13def parse_custom_class(value: str):14 return CustomClass(value * 2)151617app = typer.Typer()181920@app.command()21def main(22 custom_arg: Annotated[CustomClass, typer.Argument(parser=parse_custom_class)],23 custom_opt: Annotated[CustomClass, typer.Option(parser=parse_custom_class)] = "Foo",24):
1 unmodified line
26 print(f"--custom-opt is {custom_opt}")272829if __name__ == "__main__":26 typer.run(main)30 app()
modified:docs_src/parameter_types/custom_types/tutorial001.py+5 added-1 removed
11 unmodified lines
12def parse_custom_class(value: str):13 return CustomClass(value * 2)141516app = typer.Typer()171819@app.command()20def main(21 custom_arg: CustomClass = typer.Argument(parser=parse_custom_class),22 custom_opt: CustomClass = typer.Option("Foo", parser=parse_custom_class),23):
1 unmodified line
25 print(f"--custom-opt is {custom_opt}")262728if __name__ == "__main__":25 typer.run(main)29 app()
modified:docs_src/parameter_types/custom_types/tutorial002_an.py+5 added-1 removed
16 unmodified lines
17 def convert(self, value, param, ctx):18 return CustomClass(value * 3)192021app = typer.Typer()222324@app.command()25def main(26 custom_arg: Annotated[CustomClass, typer.Argument(click_type=CustomClassParser())],27 custom_opt: Annotated[28 CustomClass, typer.Option(click_type=CustomClassParser())
3 unmodified lines
32 print(f"--custom-opt is {custom_opt}")333435if __name__ == "__main__":32 typer.run(main)36 app()
modified:docs_src/parameter_types/custom_types/tutorial002.py+5 added-1 removed
15 unmodified lines
16 def convert(self, value, param, ctx):17 return CustomClass(value * 3)181920app = typer.Typer()212223@app.command()24def main(25 custom_arg: CustomClass = typer.Argument(click_type=CustomClassParser()),26 custom_opt: CustomClass = typer.Option("Foo", click_type=CustomClassParser()),27):
1 unmodified line
29 print(f"--custom-opt is {custom_opt}")303132if __name__ == "__main__":29 typer.run(main)33 app()
modified:docs_src/parameter_types/datetime/tutorial001.py+4 added-1 removed
1from datetime import datetime23import typer45app = typer.Typer()678@app.command()9def main(birth: datetime):10 print(f"Interesting day to be born: {birth}")11 print(f"Birth hour: {birth.hour}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/parameter_types/datetime/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(11 launch_date: Annotated[12 datetime,13 typer.Argument(
4 unmodified lines
18 print(f"Launch will be at: {launch_date}")192021if __name__ == "__main__":19 typer.run(main)22 app()
modified:docs_src/parameter_types/datetime/tutorial002.py+4 added-1 removed
1from datetime import datetime23import typer45app = typer.Typer()678@app.command()9def main(10 launch_date: datetime = typer.Argument(11 ..., formats=["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]12 ),
1 unmodified line
14 print(f"Launch will be at: {launch_date}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/parameter_types/enum/tutorial001.py+5 added-1 removed
7 unmodified lines
8 conv = "conv"9 lstm = "lstm"101112app = typer.Typer()131415@app.command()16def main(network: NeuralNetwork = NeuralNetwork.simple):17 print(f"Training neural network of type: {network.value}")181920if __name__ == "__main__":17 typer.run(main)21 app()
modified:docs_src/parameter_types/enum/tutorial002_an.py+5 added-1 removed
8 unmodified lines
9 conv = "conv"10 lstm = "lstm"111213app = typer.Typer()141516@app.command()17def main(18 network: Annotated[19 NeuralNetwork, typer.Option(case_sensitive=False)20 ] = NeuralNetwork.simple,
1 unmodified line
22 print(f"Training neural network of type: {network.value}")232425if __name__ == "__main__":22 typer.run(main)26 app()
modified:docs_src/parameter_types/enum/tutorial002.py+5 added-1 removed
7 unmodified lines
8 conv = "conv"9 lstm = "lstm"101112app = typer.Typer()131415@app.command()16def main(17 network: NeuralNetwork = typer.Option(NeuralNetwork.simple, case_sensitive=False),18):19 print(f"Training neural network of type: {network.value}")202122if __name__ == "__main__":19 typer.run(main)23 app()
modified:docs_src/parameter_types/enum/tutorial003_an.py+5 added-1 removed
9 unmodified lines
10 food_2 = "Bacon"11 food_3 = "Cheese"121314app = typer.Typer()151617@app.command()18def main(groceries: Annotated[List[Food], typer.Option()] = [Food.food_1, Food.food_3]):19 print(f"Buying groceries: {', '.join([f.value for f in groceries])}")202122if __name__ == "__main__":19 typer.run(main)23 app()
modified:docs_src/parameter_types/enum/tutorial003.py+5 added-1 removed
8 unmodified lines
9 food_2 = "Bacon"10 food_3 = "Cheese"111213app = typer.Typer()141516@app.command()17def main(groceries: List[Food] = typer.Option([Food.food_1, Food.food_3])):18 print(f"Buying groceries: {', '.join([f.value for f in groceries])}")192021if __name__ == "__main__":18 typer.run(main)22 app()
modified:docs_src/parameter_types/enum/tutorial004_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated, Literal34app = typer.Typer()567@app.command()8def main(9 network: Annotated[Literal["simple", "conv", "lstm"], typer.Option()] = "simple",10):11 print(f"Training neural network of type: {network}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/parameter_types/enum/tutorial004.py+4 added-1 removed
1import typer2from typing_extensions import Literal34app = typer.Typer()567@app.command()8def main(network: Literal["simple", "conv", "lstm"] = typer.Option("simple")):9 print(f"Training neural network of type: {network}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/parameter_types/file/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(config: Annotated[typer.FileText, typer.Option()]):9 for line in config:10 print(f"Config line: {line}")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/parameter_types/file/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(config: typer.FileText = typer.Option(...)):8 for line in config:9 print(f"Config line: {line}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/parameter_types/file/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(config: Annotated[typer.FileTextWrite, typer.Option()]):9 config.write("Some config written by the app")10 print("Config written")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/parameter_types/file/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(config: typer.FileTextWrite = typer.Option(...)):8 config.write("Some config written by the app")9 print("Config written")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/parameter_types/file/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):9 processed_total = 010 for bytes_chunk in file:11 # Process the bytes in bytes_chunk
1 unmodified line
13 print(f"Processed bytes total: {processed_total}")141516if __name__ == "__main__":14 typer.run(main)17 app()
modified:docs_src/parameter_types/file/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(file: typer.FileBinaryRead = typer.Option(...)):8 processed_total = 09 for bytes_chunk in file:10 # Process the bytes in bytes_chunk
1 unmodified line
12 print(f"Processed bytes total: {processed_total}")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/parameter_types/file/tutorial004_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]):9 first_line_str = "some settings\n"10 # You cannot write str directly to a binary file, you have to encode it to get bytes11 first_line_bytes = first_line_str.encode("utf-8")
5 unmodified lines
17 print("Binary file written")181920if __name__ == "__main__":18 typer.run(main)21 app()
modified:docs_src/parameter_types/file/tutorial004.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(file: typer.FileBinaryWrite = typer.Option(...)):8 first_line_str = "some settings\n"9 # You cannot write str directly to a binary file, you have to encode it to get bytes10 first_line_bytes = first_line_str.encode("utf-8")
5 unmodified lines
16 print("Binary file written")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/parameter_types/file/tutorial005_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):9 config.write("This is a single line\n")10 print("Config line written")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/parameter_types/file/tutorial005.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(config: typer.FileText = typer.Option(..., mode="a")):8 config.write("This is a single line\n")9 print("Config line written")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/parameter_types/index/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str, age: int = 20, height_meters: float = 1.89, female: bool = True):8 print(f"NAME is {name}, of type: {type(name)}")9 print(f"--age is {age}, of type: {type(age)}")10 print(f"--height-meters is {height_meters}, of type: {type(height_meters)}")11 print(f"--female is {female}, of type: {type(female)}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/parameter_types/number/tutorial001_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 id: Annotated[int, typer.Argument(min=0, max=1000)],10 age: Annotated[int, typer.Option(min=18)] = 20,11 score: Annotated[float, typer.Option(max=100)] = 0,
3 unmodified lines
15 print(f"--score is {score}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/parameter_types/number/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 id: int = typer.Argument(..., min=0, max=1000),9 age: int = typer.Option(20, min=18),10 score: float = typer.Option(0, max=100),
3 unmodified lines
14 print(f"--score is {score}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/parameter_types/number/tutorial002_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(9 id: Annotated[int, typer.Argument(min=0, max=1000)],10 rank: Annotated[int, typer.Option(max=10, clamp=True)] = 0,11 score: Annotated[float, typer.Option(min=0, max=100, clamp=True)] = 0,
3 unmodified lines
15 print(f"--score is {score}")161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/parameter_types/number/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(8 id: int = typer.Argument(..., min=0, max=1000),9 rank: int = typer.Option(0, max=10, clamp=True),10 score: float = typer.Option(0, min=0, max=100, clamp=True),
3 unmodified lines
14 print(f"--score is {score}")151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/parameter_types/number/tutorial003_an.py+4 added-1 removed
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):9 print(f"Verbose level is {verbose}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/parameter_types/number/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(verbose: int = typer.Option(0, "--verbose", "-v", count=True)):8 print(f"Verbose level is {verbose}")91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/parameter_types/path/tutorial001_an.py+4 added-1 removed
2 unmodified lines
34import typer5from typing_extensions import Annotated67app = typer.Typer()8910@app.command()11def main(config: Annotated[Optional[Path], typer.Option()] = None):12 if config is None:13 print("No config file")14 raise typer.Abort()
6 unmodified lines
21 print("The config doesn't exist")222324if __name__ == "__main__":22 typer.run(main)25 app()
modified:docs_src/parameter_types/path/tutorial001.py+4 added-1 removed
1 unmodified line
2from typing import Optional34import typer56app = typer.Typer()789@app.command()10def main(config: Optional[Path] = typer.Option(None)):11 if config is None:12 print("No config file")13 raise typer.Abort()
6 unmodified lines
20 print("The config doesn't exist")212223if __name__ == "__main__":21 typer.run(main)24 app()
modified:docs_src/parameter_types/path/tutorial002_an.py+4 added-1 removed
1 unmodified line
23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(11 config: Annotated[12 Path,13 typer.Option(
10 unmodified lines
24 print(f"Config file contents: {text}")252627if __name__ == "__main__":25 typer.run(main)28 app()
modified:docs_src/parameter_types/path/tutorial002.py+4 added-1 removed
1from pathlib import Path23import typer45app = typer.Typer()678@app.command()9def main(10 config: Path = typer.Option(11 ...,12 exists=True,
8 unmodified lines
21 print(f"Config file contents: {text}")222324if __name__ == "__main__":22 typer.run(main)25 app()
modified:docs_src/parameter_types/uuid/tutorial001.py+4 added-1 removed
1from uuid import UUID23import typer45app = typer.Typer()678@app.command()9def main(user_id: UUID):10 print(f"USER_ID is {user_id}")11 print(f"UUID version is: {user_id.version}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/printing/tutorial001.py+4 added-1 removed
7 unmodified lines
8 "active": True,9 "affiliation": None,10}1112app = typer.Typer()131415@app.command()16def main():17 print("Here's the data")18 print(data)192021if __name__ == "__main__":19 typer.run(main)22 app()
modified:docs_src/printing/tutorial002.py+4 added-1 removed
1import typer2from rich import print34app = typer.Typer()567@app.command()8def main():9 print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/printing/tutorial003.py+4 added-1 removed
2 unmodified lines
3from rich.table import Table45console = Console()67app = typer.Typer()8910@app.command()11def main():12 table = Table("Name", "Item")13 table.add_row("Rick", "Portal Gun")14 table.add_row("Morty", "Plumbus")15 console.print(table)161718if __name__ == "__main__":16 typer.run(main)19 app()
modified:docs_src/printing/tutorial004.py+4 added-1 removed
1 unmodified line
2from rich.console import Console34err_console = Console(stderr=True)56app = typer.Typer()789@app.command()10def main():11 err_console.print("Here is something written to standard error")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/printing/tutorial005.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(good: bool = True):8 message_start = "everything is "9 if good:10 ending = typer.style("good", fg=typer.colors.GREEN, bold=True)
3 unmodified lines
14 typer.echo(message)151617if __name__ == "__main__":15 typer.run(main)18 app()
modified:docs_src/printing/tutorial006.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(name: str):8 typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)91011if __name__ == "__main__":9 typer.run(main)12 app()
modified:docs_src/progressbar/tutorial001.py+4 added-1 removed
1 unmodified line
23import typer4from rich.progress import track56app = typer.Typer()789@app.command()10def main():11 total = 012 for value in track(range(100), description="Processing..."):13 # Fake processing time
2 unmodified lines
16 print(f"Processed {total} things.")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/progressbar/tutorial002.py+4 added-1 removed
1 unmodified line
23import typer4from rich.progress import Progress, SpinnerColumn, TextColumn56app = typer.Typer()789@app.command()10def main():11 with Progress(12 SpinnerColumn(),13 TextColumn("[progress.description]{task.description}"),
5 unmodified lines
19 print("Done!")202122if __name__ == "__main__":20 typer.run(main)23 app()
modified:docs_src/progressbar/tutorial003.py+4 added-1 removed
1import time23import typer45app = typer.Typer()678@app.command()9def main():10 total = 011 with typer.progressbar(range(100)) as progress:12 for value in progress:
3 unmodified lines
16 print(f"Processed {total} things.")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/progressbar/tutorial004.py+5 added-1 removed
7 unmodified lines
8 for i in range(100):9 yield i101112app = typer.Typer()131415@app.command()16def main():17 total = 018 with typer.progressbar(iterate_user_ids(), length=100) as progress:19 for value in progress:
3 unmodified lines
23 print(f"Processed {total} user IDs.")242526if __name__ == "__main__":23 typer.run(main)27 app()
modified:docs_src/progressbar/tutorial005.py+4 added-1 removed
1import time23import typer45app = typer.Typer()678@app.command()9def main():10 total = 011 with typer.progressbar(range(100), label="Processing") as progress:12 for value in progress:
3 unmodified lines
16 print(f"Processed {total} things.")171819if __name__ == "__main__":17 typer.run(main)20 app()
modified:docs_src/progressbar/tutorial006.py+4 added-1 removed
1import time23import typer45app = typer.Typer()678@app.command()9def main():10 total = 100011 with typer.progressbar(length=total) as progress:12 for batch in range(4):
5 unmodified lines
18 print(f"Processed {total} things in batches.")192021if __name__ == "__main__":19 typer.run(main)22 app()
modified:docs_src/prompt/tutorial001.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main():8 person_name = typer.prompt("What's your name?")9 print(f"Hello {person_name}")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/prompt/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main():8 delete = typer.confirm("Are you sure you want to delete it?")9 if not delete:10 print("Not deleting")
1 unmodified line
12 print("Deleting it!")131415if __name__ == "__main__":13 typer.run(main)16 app()
modified:docs_src/prompt/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main():8 delete = typer.confirm("Are you sure you want to delete it?", abort=True)9 print("Deleting it!")101112if __name__ == "__main__":10 typer.run(main)13 app()
modified:docs_src/prompt/tutorial004.py+4 added-1 removed
1import typer2from rich.prompt import Prompt34app = typer.Typer()567@app.command()8def main():9 name = Prompt.ask("Enter your name :sunglasses:")10 print(f"Hey there {name}!")111213if __name__ == "__main__":11 typer.run(main)14 app()
modified:docs_src/terminating/tutorial001.py+5 added-1 removed
14 unmodified lines
15 # Somehow send a notification here for the new user, maybe an email16 print(f"Notification sent for new user: {username}")171819app = typer.Typer()202122@app.command()23def main(username: str):24 maybe_create_user(username=username)25 send_new_user_notification(username=username)262728if __name__ == "__main__":25 typer.run(main)29 app()
modified:docs_src/terminating/tutorial002.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(username: str):8 if username == "root":9 print("The root user is reserved")10 raise typer.Exit(code=1)11 print(f"New user created: {username}")121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:docs_src/terminating/tutorial003.py+4 added-1 removed
1import typer23app = typer.Typer()456@app.command()7def main(username: str):8 if username == "root":9 print("The root user is reserved")10 raise typer.Abort()11 print(f"New user created: {username}")121314if __name__ == "__main__":12 typer.run(main)15 app()
added:docs_src/typer_app/tutorial001.py+12 added
1import typer23app = typer.Typer()456@app.command()7def main(name: str):8 print(f"Hello {name}")91011if __name__ == "__main__":12 app()
modified:tests/assets/type_error_no_rich.py+4 added-1 removed
1 unmodified line
2import typer.main34typer.main.HAS_RICH = False56app = typer.Typer()789@app.command()10def main(name: str = "morty"):11 print(name + 3)121314if __name__ == "__main__":12 typer.run(main)15 app()
modified:tests/test_completion/test_completion_install.py+1 added-1 removed
6 unmodified lines
7import shellingham8import typer9from typer.testing import CliRunner1011from docs_src.commands.index import tutorial001 as mod11from docs_src.typer_app import tutorial001 as mod1213from ..utils import requires_completion_permission1415runner = CliRunner()
157 unmodified lines
modified:tests/test_completion/test_completion_show.py+1 added-1 removed
5 unmodified lines
6import shellingham7import typer8from typer.testing import CliRunner910from docs_src.commands.index import tutorial001 as mod10from docs_src.typer_app import tutorial001 as mod1112runner = CliRunner()13app = typer.Typer()14app.command()(mod.main)
135 unmodified lines
modified:tests/test_completion/test_completion.py+1 added-1 removed
1 unmodified line
2import subprocess3import sys4from pathlib import Path56from docs_src.commands.index import tutorial001 as mod6from docs_src.typer_app import tutorial001 as mod78from ..utils import needs_bash, needs_linux, requires_completion_permission910
154 unmodified lines
deleted:tests/test_tutorial/test_commands/test_index/test_tutorial001.py-31 removed
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.commands.index import tutorial001 as mod78app = mod.app910runner = CliRunner()111213def test_no_arg():14 result = runner.invoke(app)15 assert result.exit_code != 016 assert "Missing argument 'NAME'." in result.output171819def test_arg():20 result = runner.invoke(app, ["Camila"])21 assert result.exit_code == 022 assert "Hello Camila" in result.output232425def test_script():26 result = subprocess.run(27 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],28 capture_output=True,29 encoding="utf-8",30 )31 assert "Usage" in result.stdout
modified:tests/test_tutorial/test_exceptions/test_tutorial001.py+2 added-2 removed
18 unmodified lines
19 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},20 )21 assert "return get_command(self)(*args, **kwargs)" not in result.stderr2223 assert "typer.run(main)" not in result.stderr23 assert "app()" not in result.stderr24 assert "print(name + 3)" in result.stderr25 assert 'TypeError: can only concatenate str (not "int") to str' in result.stderr26 assert "name = 'morty'" in result.stderr27
7 unmodified lines
35 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": "1"},36 )37 assert "return get_command(self)(*args, **kwargs)" in result.stderr3839 assert "typer.run(main)" in result.stderr39 assert "app()" in result.stderr40 assert "print(name + 3)" in result.stderr41 assert 'TypeError: can only concatenate str (not "int") to str' in result.stderr42 assert "name = 'morty'" not in result.stderr43
8 unmodified lines
added:tests/test_tutorial/test_typer_app/__init__.py
added:tests/test_tutorial/test_typer_app/test_tutorial001.py+31 added
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.typer_app import tutorial001 as mod78app = mod.app910runner = CliRunner()111213def test_no_arg():14 result = runner.invoke(app)15 assert result.exit_code != 016 assert "Missing argument 'NAME'." in result.output171819def test_arg():20 result = runner.invoke(app, ["Camila"])21 assert result.exit_code == 022 assert "Hello Camila" in result.output232425def test_script():26 result = subprocess.run(27 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],28 capture_output=True,29 encoding="utf-8",30 )31 assert "Usage" in result.stdout
modified:tests/test_tracebacks.py+1 added-1 removed
12 unmodified lines
13 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},14 )15 assert "return get_command(self)(*args, **kwargs)" not in result.stderr1617 assert "typer.run(main)" in result.stderr17 assert "app()" in result.stderr18 assert "print(name + 3)" in result.stderr19 assert 'TypeError: can only concatenate str (not "int") to str' in result.stderr2021
31 unmodified lines
modified:mkdocs.yml+1 added
75 unmodified lines
76 - environment-variables.md77 - virtual-environments.md78 - tutorial/install.md79 - tutorial/first-steps.md80 - tutorial/typer-app.md81 - tutorial/printing.md82 - tutorial/terminating.md83 - CLI Arguments:84 - tutorial/arguments/index.md
145 unmodified lines