📝 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
Provenance
- Commit
df2cb14- Tree
a0e901a- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
ae80129
199 files changed+917 added−432 removed
modified:.github/DISCUSSION_TEMPLATE/questions.yml+3 added-1 removed
62 unmodified lines63646566676869707172737473757677787966 unmodified lines62 unmodified lines
placeholder: | import typer
app = typer.Typer()
@app.command() def main(name: str): typer.echo(f"Hello {name}")
if __name__ == "__main__": typer.run(main) app() render: python validations: required: true - type: textarea66 unmodified linesmodified:docs/tutorial/arguments/default.md+2 added-2 removed
6 unmodified lines7 ## An optional *CLI argument* with a default8 9 We can also use `typer.Argument()` to make a *CLI argument* have a default value other than `None`:10 11-{* docs_src/arguments/default/tutorial001_an.py hl[5] *}11+{* docs_src/arguments/default/tutorial001_an.py hl[8] *}12 13 /// tip14 15 Because 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 lines51 ## Dynamic default value52 53 And we can even make the default value be dynamically generated by passing a function as the `default_factory` argument:54 55-{* docs_src/arguments/default/tutorial002_an.py hl[7:8,11] *}55+{* docs_src/arguments/default/tutorial002_an.py hl[10:11,14] *}56 57 In this case, we created the function `get_name` that will just return a random `str` each time.58 59 And we pass it as the first function argument to `typer.Argument()`.43 unmodified linesmodified:docs/tutorial/arguments/envvar.md+3 added-3 removed
8 unmodified lines9 ///10 11 To do that, use the `envvar` parameter for `typer.Argument()`:12 13-{* docs_src/arguments/envvar/tutorial001_an.py hl[5] *}13+{* docs_src/arguments/envvar/tutorial001_an.py hl[8] *}14 15 In 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:16 17 <div class="termy">36 unmodified lines54 ## Multiple environment variables55 56 You 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:57 58-{* docs_src/arguments/envvar/tutorial002_an.py hl[6] *}58+{* docs_src/arguments/envvar/tutorial002_an.py hl[9] *}59 60 Check it:61 62 <div class="termy">26 unmodified lines89 ## Hide an env var from the help text90 91 By default, environment variables used will be shown in the help text, but you can disable them with `show_envvar=False`:92 93-{* docs_src/arguments/envvar/tutorial003_an.py hl[7] *}93+{* docs_src/arguments/envvar/tutorial003_an.py hl[10] *}94 95 Check it:96 97 <div class="termy">29 unmodified linesmodified:docs/tutorial/arguments/help.md+8 added-8 removed
10 unmodified lines11 ## Add a `help` text for a *CLI argument*12 13 You can use the `help` parameter to add a help text for a *CLI argument*:14 15-{* docs_src/arguments/help/tutorial001_an.py hl[5] *}15+{* docs_src/arguments/help/tutorial001_an.py hl[8] *}16 17 And it will be used in the automatic `--help` option:18 19 <div class="termy">16 unmodified lines36 ## Combine help text and docstrings37 38 And 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>:39 40-{* docs_src/arguments/help/tutorial002_an.py hl[5:8] *}40+{* docs_src/arguments/help/tutorial002_an.py hl[8:11] *}41 42 And the `--help` option will combine all the information:43 44 <div class="termy">18 unmodified lines63 ## Help with defaults64 65 If you have a *CLI argument* with a default value, like `"World"`:66 67-{* docs_src/arguments/help/tutorial003_an.py hl[5] *}67+{* docs_src/arguments/help/tutorial003_an.py hl[8] *}68 69 It will show that default value in the help text:70 71 <div class="termy">16 unmodified lines88 </div>89 90 But you can disable that if you want to, with `show_default=False`:91 92-{* docs_src/arguments/help/tutorial004_an.py hl[7] *}92+{* docs_src/arguments/help/tutorial004_an.py hl[10] *}93 94 And then it won't show the default value:95 96 <div class="termy">26 unmodified lines123 ## Custom default string124 125 You 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:126 127-{* docs_src/arguments/help/tutorial005_an.py hl[9] *}127+{* docs_src/arguments/help/tutorial005_an.py hl[12] *}128 129 And it will be used in the help text:130 131 <div class="termy">36 unmodified lines168 But you can customize it with the `metavar` parameter for `typer.Argument()`.169 170 For 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:171 172-{* docs_src/arguments/help/tutorial006_an.py hl[5] *}172+{* docs_src/arguments/help/tutorial006_an.py hl[8] *}173 174 Now the generated help text will have `✨username✨` instead of `NAME`:175 176 <div class="termy">17 unmodified lines194 You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.195 196 If 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:197 198-{* docs_src/arguments/help/tutorial007_an.py hl[8,12] *}198+{* docs_src/arguments/help/tutorial007_an.py hl[11,15] *}199 200 Then, 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`.201 202 And next you will see other panels for the *CLI arguments* that have a custom panel set in the `rich_help_panel` parameter:34 unmodified lines237 If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.238 239 You will probably not want to do this normally, but it's possible:240 241-{* docs_src/arguments/help/tutorial008_an.py hl[5] *}241+{* docs_src/arguments/help/tutorial008_an.py hl[8] *}242 243 Check it:244 245 <div class="termy">48 unmodified linesmodified:docs/tutorial/arguments/optional.md+11 added-8 removed
37 unmodified lines38 {* docs_src/first_steps/tutorial002.py hl[4] *}39 40 Now let's see an alternative way to create the same *CLI argument*:41 42+{* docs_src/arguments/optional/tutorial000.py hl[4] *}43 43-{* docs_src/arguments/optional/tutorial001_an.py hl[5] *}44+Or, using an explicit `Typer()` instance creation:45 46+{* docs_src/arguments/optional/tutorial001_an.py hl[8] *}47+48 /// info49 50 Typer added support for `Annotated` (and started recommending it) in version 0.9.0.51 61 unmodified lines113 Now, finally what we came for, an optional *CLI argument*.114 115 To make a *CLI argument* optional, use `typer.Argument()` and make sure to provide a "default" value, for example `"World"`:116 114-{* docs_src/arguments/optional/tutorial002_an.py hl[5] *}117+{* docs_src/arguments/optional/tutorial002_an.py hl[8] *}118 119 Now we have:120 121 ```Python58 unmodified lines180 **Typer** also supports another older alternative syntax for declaring *CLI arguments* with additional metadata.181 182 Instead of using `Annotated`, you can use `typer.Argument()` as the default value:183 181-{* docs_src/arguments/optional/tutorial001.py hl[4] *}184+{* docs_src/arguments/optional/tutorial001.py hl[7] *}185 186 /// tip187 188 Prefer to use the `Annotated` version if possible.25 unmodified lines214 If 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>.215 216 ///217 215-{* docs_src/arguments/optional/tutorial003.py hl[4] *}218+{* docs_src/arguments/optional/tutorial003.py hl[7] *}219 217-And the same way, you can make it optional by passing a different `default` value, for example `None`:220+And the same way, you can make it optional by passing a different `default` value, for example `"World"`:221 219-{* docs_src/arguments/optional/tutorial002.py hl[6] *}222+{* docs_src/arguments/optional/tutorial002.py hl[7] *}223 221-Because 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`.224+Because 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"`.225 226 The `default` argument is the first one, so it's possible that you see code that passes the value without explicitly using `default=`, like:227 228 ```Python2 unmodified lines231 232 ...or like:233 234 ```Python232-name: str = typer.Argument(None)235+name: str = typer.Argument("World")236 ```237 238 ...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 lines45 Have that in mind so you don't get confused.46 47 Here 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.48 49-## Explicit application50-51-Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.52-53-In the *CLI options* and *CLI argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.54-55-For example:56-57-{* docs_src/first_steps/tutorial002.py hl[9] *}58-59-But 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()`.60-61-There's also a more explicit way to achieve the same:62-63-{* docs_src/commands/index/tutorial001.py hl[3,6,12] *}64-65-When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:66-67-* 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()`".70-71-/// info | `@decorator` Info72-73-That `@something` syntax in Python is called a "decorator".74-75-You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).76-77-A "decorator" takes the function below and does something with it.78-79-In our case, this decorator tells **Typer** that the function below is a "`command`".80-81-///82-83-Both ways, with `typer.run()` and creating the explicit application, achieve almost the same.84-85-/// tip86-87-If 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.88-89-You might want to do that later when your app needs the extra features, but if it doesn't need them yet, that's fine.90-91-///92-93-If you run the second example, with the explicit `app`, it works exactly the same:94-95-<div class="termy">96-97-```console98-// Without a CLI argument99-$ python main.py100-101-Usage: main.py [OPTIONS] NAME102-Try "main.py --help" for help.103-104-Error: Missing argument 'NAME'.105-106-// With the NAME CLI argument107-$ python main.py Camila108-109-Hello Camila110-111-// Asking for help112-$ python main.py --help113-114-Usage: main.py [OPTIONS] NAME115-116-Options: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-```121-122-</div>123-124-## CLI application completion125-126-There's a little detail that is worth noting here.127-128-Now the help shows two new *CLI options*:129-130-* `--install-completion`131-* `--show-completion`132-133-To get shell/tab completion, it's necessary to build a package that you and your users can install and **call directly**.134-135-So instead of running a Python script like:136-137-<div class="termy">138-139-```console140-$ python main.py141-142-✨ Some magic here ✨143-```144-145-</div>146-147-...It would be called like:148-149-<div class="termy">150-151-```console152-$ magic-app153-154-✨ Some magic here ✨155-```156-157-</div>158-159-Having a standalone program like that allows setting up shell/tab completion.160-161-The first step to be able to create an installable package like that is to use an explicit `typer.Typer()` app.162-163-Later you can learn all the process to create a standalone CLI application and [Build a Package](../package.md){.internal-link target=_blank}.164-165-But for now, it's just good to know that you are on that path. 😎166-49 ## A CLI application with multiple commands50 169-Coming 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.52 53 Now that you know how to create an explicit `typer.Typer()` application and add one command, let's see how to add multiple commands.54 55 Let's say that we have a CLI application to manage users.136 unmodified linesmodified:docs/tutorial/commands/one-or-multiple.md+2 added-2 removed
1 # One or Multiple Commands2 3-You might have noticed that if you create a single command, as in the first example:3+You might have noticed that if you create a single command, as in the following example:4 5-{* docs_src/commands/index/tutorial001.py hl[3,6,12] *}5+{* docs_src/typer_app/tutorial001.py hl[3,6,12] *}6 7 **Typer** is smart enough to create a CLI application with that single function as the main CLI application, not as a command/subcommand:8 9 <div class="termy">139 unmodified linesmodified:docs/tutorial/multiple-values/arguments-with-multiple-values.md+2 added-2 removed
2 unmodified lines3 *CLI arguments* can also receive multiple values.4 5 You can define the type of a *CLI argument* using `typing.List`.6 7-{* 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] *}8 9 And then you can pass it as many *CLI arguments* of that type as you want:10 11 <div class="termy">24 unmodified lines36 ## *CLI arguments* with tuples37 38 If you want a specific number of values and types, you can use a tuple, and it can even have default values:39 40-{* 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] *}41 42 Check it:43 44 <div class="termy">34 unmodified linesmodified:docs/tutorial/multiple-values/multiple-options.md+2 added-2 removed
4 unmodified lines5 For example, let's say you want to accept several users in a single execution.6 7 For this, use the standard Python `typing.List` to declare it as a `list` of `str`:8 9-{* 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] *}10 11 You will receive the values as you declared them, as a `list` of `str`.12 13 Check it:25 unmodified lines39 ## Multiple `float`40 41 The same way, you can use other types and they will be converted by **Typer** to their declared type:42 43-{* docs_src/multiple_values/multiple_options/tutorial002_an.py hl[7] *}43+{* docs_src/multiple_values/multiple_options/tutorial002_an.py hl[10] *}44 45 Check it:46 47 <div class="termy">18 unmodified linesmodified:docs/tutorial/multiple-values/options-with-multiple-values.md+1 added-1 removed
4 unmodified lines5 You can set the number of values and types to anything you want, but it has to be a fixed number of values.6 7 For this, use the standard Python `typing.Tuple`:8 9-{* 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] *}10 11 Each of the internal types defines the type of each value in the tuple.12 13 So:80 unmodified linesmodified:docs/tutorial/options/callback-and-context.md+4 added-4 removed
6 unmodified lines7 ## Validate *CLI parameters*8 9 For example, you could do some validation before the rest of the code is executed.10 11-{* docs_src/options/callback/tutorial001_an.py hl[7:10,13] *}11+{* docs_src/options/callback/tutorial001_an.py hl[9:12,16] *}12 13 Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.14 15 The function receives the value from the command line. It can do anything with it, and then return the value.77 unmodified lines93 ### Breaking completion in a callback94 95 Let's say that when the callback is running, we want to show a message saying that it's validating the name:96 97-{* docs_src/options/callback/tutorial002_an.py hl[8] *}97+{* docs_src/options/callback/tutorial002_an.py hl[10] *}98 99 And 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.100 101 It will look something like:26 unmodified lines128 But you can access the context by declaring a function parameter of type `typer.Context`.129 130 The "context" has some additional data about the current execution of your program:131 132-{* docs_src/options/callback/tutorial003_an.py hl[7:9] *}132+{* docs_src/options/callback/tutorial003_an.py hl[9:11] *}133 134 The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.135 136 But it will be `False` when calling the program normally. So you can continue the execution of your previous code.23 unmodified lines160 ## Using the `CallbackParam` object161 162 The 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.163 164-{* docs_src/options/callback/tutorial004_an.py hl[7,10] *}164+{* docs_src/options/callback/tutorial004_an.py hl[9,12] *}165 166 It's probably not very common, but you could do it if you need it.167 168 For 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 linesmodified:docs/tutorial/options/help.md+4 added-4 removed
2 unmodified lines3 You already saw how to add a help text for *CLI arguments* with the `help` parameter.4 5 Let's now do the same for *CLI options*:6 7-{* docs_src/options/help/tutorial001_an.py hl[7:8] *}7+{* docs_src/options/help/tutorial001_an.py hl[10:11] *}8 9 The same way as with `typer.Argument()`, we can put `typer.Option()` inside of `Annotated`.10 11 We can then pass the `help` keyword parameter:43 unmodified lines55 The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.56 57 If 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*:58 59-{* docs_src/options/help/tutorial002_an.py hl[11,17] *}59+{* docs_src/options/help/tutorial002_an.py hl[14,20] *}60 61 Now, 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`.62 63 And below you will see other panels for the *CLI options* that have a custom panel set in the `rich_help_panel` parameter:37 unmodified lines101 ## Hide default from help102 103 You can tell Typer to not show the default value in the help text with `show_default=False`:104 105-{* docs_src/options/help/tutorial003_an.py hl[5] *}105+{* docs_src/options/help/tutorial003_an.py hl[8] *}106 107 And it will no longer show the default value in the help text:108 109 <div class="termy">28 unmodified lines138 ## Custom default string139 140 You 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:141 142-{* docs_src/options/help/tutorial004_an.py hl[7] *}142+{* docs_src/options/help/tutorial004_an.py hl[10] *}143 144 And it will be used in the help text:145 146 <div class="termy">19 unmodified linesmodified:docs/tutorial/options/name.md+5 added-5 removed
26 unmodified lines27 Let's say the function parameter name is `user_name` as above, but you want the *CLI option* to be just `--name`.28 29 You can pass the *CLI option* name that you want to have in the following positional argument passed to `typer.Option()`:30 31-{* docs_src/options/name/tutorial001_an.py hl[5] *}31+{* docs_src/options/name/tutorial001_an.py hl[8] *}32 33 /// info34 35 "<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 lines184 You can overwrite the *CLI option* name to use as in the previous example, but you can also declare extra alternatives, including short names.185 186 For example, extending the previous example, let's add a *CLI option* short name `-n`:187 188-{* docs_src/options/name/tutorial002_an.py hl[5] *}188+{* docs_src/options/name/tutorial002_an.py hl[8] *}189 190 Here 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`.191 192 Check it:22 unmodified lines215 ### *CLI option* only short name216 217 If 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.218 219-{* docs_src/options/name/tutorial003_an.py hl[5] *}219+{* docs_src/options/name/tutorial003_an.py hl[8] *}220 221 Check it:222 223 <div class="termy">19 unmodified lines243 ### *CLI option* short name and default244 245 Continuing 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:246 247-{* docs_src/options/name/tutorial004_an.py hl[5] *}247+{* docs_src/options/name/tutorial004_an.py hl[8] *}248 249 Check it:250 251 <div class="termy">25 unmodified lines277 You can create multiple short names and use them together.278 279 You don't have to do anything special for it to work (apart from declaring those short versions):280 281-{* docs_src/options/name/tutorial005_an.py hl[6:7] *}281+{* docs_src/options/name/tutorial005_an.py hl[9:10] *}282 283 /// tip284 285 Notice that, again, we are declaring the long and short version of the *CLI option* names.32 unmodified linesmodified:docs/tutorial/options/password.md+2 added-2 removed
1 # Password CLI Option and Confirmation Prompt2 3 Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:4 5-{* docs_src/options/password/tutorial001_an.py hl[7] *}5+{* docs_src/options/password/tutorial001_an.py hl[10] *}6 7 And the CLI program will ask for confirmation:8 9 <div class="termy">19 unmodified lines29 You can achieve the same using `hide_input=True`.30 31 And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:32 33-{* docs_src/options/password/tutorial002_an.py hl[8] *}33+{* docs_src/options/password/tutorial002_an.py hl[11] *}34 35 Check it:36 37 <div class="termy">14 unmodified linesmodified:docs/tutorial/options/prompt.md+3 added-3 removed
1 # CLI Option Prompt2 3 It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:4 5-{* docs_src/options/prompt/tutorial001_an.py hl[5] *}5+{* docs_src/options/prompt/tutorial001_an.py hl[8] *}6 7 And then your program will ask the user for it in the terminal:8 9 <div class="termy">13 unmodified lines23 ## Customize the prompt24 25 You can also set a custom prompt, passing the string that you want to use instead of just `True`:26 27-{* docs_src/options/prompt/tutorial002_an.py hl[7] *}27+{* docs_src/options/prompt/tutorial002_an.py hl[10] *}28 29 And then your program will ask for it using with your custom prompt:30 31 <div class="termy">17 unmodified lines49 You can do it passing the parameter `confirmation_prompt=True`.50 51 Let's say it's a CLI app to delete a project:52 53-{* docs_src/options/prompt/tutorial003_an.py hl[6] *}53+{* docs_src/options/prompt/tutorial003_an.py hl[9] *}54 55 And it will prompt the user for a value and then for the confirmation:56 57 <div class="termy">27 unmodified linesmodified:docs/tutorial/options/required.md+3 added-3 removed
11 unmodified lines12 To make a *CLI option* required, you can put `typer.Option()` inside of `Annotated` and leave the parameter without a default value.13 14 Let's make `--lastname` a required *CLI option*:15 16-{* docs_src/options/required/tutorial001_an.py hl[5] *}16+{* docs_src/options/required/tutorial001_an.py hl[8] *}17 18 The 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.19 20-{* docs_src/options/required/tutorial001.py hl[4] *}20+{* docs_src/options/required/tutorial001.py hl[7] *}21 22 Or you can explicitly pass `...` to `typer.Option(default=...)`:23 24-{* docs_src/options/required/tutorial002.py hl[4] *}24+{* docs_src/options/required/tutorial002.py hl[7] *}25 26 /// info27 28 If 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 linesmodified:docs/tutorial/options/version.md+3 added-3 removed
6 unmodified lines7 ## First version of `--version`8 9 Let's see a first version of how it could look like:10 11-{* 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] *}12 13 /// tip14 15 Notice 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 lines56 ## Previous parameters and `is_eager`57 58 But 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:59 60-{* 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] *}61 62 Then 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:63 64 <div class="termy">30 unmodified lines95 For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.96 97 That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:98 99-{* docs_src/options/version/tutorial003_an.py hl[23:26] *}99+{* docs_src/options/version/tutorial003_an.py hl[26:29] *}100 101 Check it:102 103 <div class="termy">9 unmodified linesmodified:docs/tutorial/parameter-types/bool.md+4 added-4 removed
8 unmodified lines9 Let's say that we want a `--force` *CLI option* only, we want to discard `--no-force`.10 11 We can do that by specifying the exact name we want:12 13-{* docs_src/parameter_types/bool/tutorial001_an.py hl[5] *}13+{* docs_src/parameter_types/bool/tutorial001_an.py hl[8] *}14 15 Now there's only a `--force` *CLI option*:16 17 <div class="termy">39 unmodified lines57 We might want to instead have `--accept` and `--reject`.58 59 We can do that by passing a single `str` with the 2 names for the `bool` *CLI option* separated by `/`:60 61-{* docs_src/parameter_types/bool/tutorial002_an.py hl[7] *}61+{* docs_src/parameter_types/bool/tutorial002_an.py hl[10] *}62 63 Check it:64 65 <div class="termy">32 unmodified lines98 The same way, you can declare short versions of the names for these *CLI options*.99 100 For example, let's say we want `-f` for `--force` and `-F` for `--no-force`:101 102-{* docs_src/parameter_types/bool/tutorial003_an.py hl[5] *}102+{* docs_src/parameter_types/bool/tutorial003_an.py hl[8] *}103 104 Check it:105 106 <div class="termy">27 unmodified lines134 If you want to (although it might not be a good idea), you can declare only *CLI option* names to set the `False` value.135 136 To do that, use a space and a single `/` and pass the negative name after:137 138-{* docs_src/parameter_types/bool/tutorial004_an.py hl[5] *}138+{* docs_src/parameter_types/bool/tutorial004_an.py hl[8] *}139 140 /// tip141 142 Have in mind that it's a string with a preceding space and then a `/`.37 unmodified linesmodified:docs/tutorial/parameter-types/custom-types.md+2 added-2 removed
11 unmodified lines12 ## Type Parser13 14 `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>.15 16-{* 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] *}17 18 The 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.19 20 ## Click Custom Type21 22 If 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.23 24-{* 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 lines3 You 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>.4 5 Your function will receive a standard Python `datetime` object, and again, your editor will give you completion, etc.6 7-{* 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] *}8 9 Typer will accept any string from the following formats:10 11 * `%Y-%m-%d`45 unmodified lines57 * separated with "`/`"58 59 ...It's a crazy example, but let's say you also needed that strange format:60 61-{* docs_src/parameter_types/datetime/tutorial002_an.py hl[11] *}61+{* docs_src/parameter_types/datetime/tutorial002_an.py hl[14] *}62 63 /// tip64 65 Notice the last string in `formats`: `"%m/%d/%Y"`.20 unmodified linesmodified:docs/tutorial/parameter-types/enum.md+4 added-4 removed
1 # Enum - Choices2 3 To 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>:4 5-{* 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] *}6 7 /// tip8 9 Notice that the function parameter `network` will be an `Enum`, not a `str`.43 unmodified lines53 ### Case insensitive Enum choices54 55 You can make an `Enum` (choice) *CLI parameter* be case-insensitive with the `case_sensitive` parameter:56 57-{* docs_src/parameter_types/enum/tutorial002_an.py hl[15] *}57+{* docs_src/parameter_types/enum/tutorial002_an.py hl[19] *}58 59 And then the values of the `Enum` will be checked no matter if lower case, upper case, or a mix:60 61 <div class="termy">15 unmodified lines77 ### List of Enum values78 79 A *CLI parameter* can also take a list of `Enum` values:80 81-{* docs_src/parameter_types/enum/tutorial003_an.py hl[14] *}81+{* docs_src/parameter_types/enum/tutorial003_an.py hl[18] *}82 83 This works just like any other parameter value taking a list of things:84 85 <div class="termy">29 unmodified lines115 ### Literal choices116 117 You can also use `Literal` to represent a set of possible predefined choices, without having to use an `Enum`:118 119-{* docs_src/parameter_types/enum/tutorial004_an.py hl[6] *}119+{* docs_src/parameter_types/enum/tutorial004_an.py hl[9] *}120 121 <div class="termy">122 123 ```console24 unmodified linesmodified:docs/tutorial/parameter-types/file.md+5 added-5 removed
45 unmodified lines46 ```47 48 You will get all the correct editor support, attributes, methods, etc for the file-like object:`49 50-{* docs_src/parameter_types/file/tutorial001_an.py hl[5] *}50+{* docs_src/parameter_types/file/tutorial001_an.py hl[8] *}51 52 Check it:53 54 <div class="termy">18 unmodified lines73 ## `FileTextWrite`74 75 For writing text, you can use `typer.FileTextWrite`:76 77-{* docs_src/parameter_types/file/tutorial002_an.py hl[5:6] *}77+{* docs_src/parameter_types/file/tutorial002_an.py hl[8:9] *}78 79 This would be for writing human text, like:80 81 ```35 unmodified lines117 You will receive `bytes` from it.118 119 It's useful for reading binary files like images:120 121-{* docs_src/parameter_types/file/tutorial003_an.py hl[5] *}121+{* docs_src/parameter_types/file/tutorial003_an.py hl[8] *}122 123 Check it:124 125 <div class="termy">20 unmodified lines146 Have in mind that you have to pass `bytes` to its `.write()` method, not `str`.147 148 If you have a `str`, you have to encode it first to get `bytes`.149 150-{* docs_src/parameter_types/file/tutorial004_an.py hl[5] *}150+{* docs_src/parameter_types/file/tutorial004_an.py hl[8] *}151 152 <div class="termy">153 154 ```console41 unmodified lines196 You can override the `mode` from the defaults above.197 198 For example, you could use `mode="a"` to write "appending" to the same file:199 200-{* docs_src/parameter_types/file/tutorial005_an.py hl[5] *}200+{* docs_src/parameter_types/file/tutorial005_an.py hl[8] *}201 202 /// tip203 204 As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.48 unmodified linesmodified:docs/tutorial/parameter-types/index.md+1 added-1 removed
6 unmodified lines7 When you declare a *CLI parameter* with some type **Typer** will convert the data received in the command line to that data type.8 9 For example:10 11-{* docs_src/parameter_types/index/tutorial001.py hl[4] *}11+{* docs_src/parameter_types/index/tutorial001.py hl[7] *}12 13 In this example, the value received for the *CLI argument* `NAME` will be treated as `str`.14 15 The value for the *CLI option* `--age` will be converted to an `int` and `--height-meters` will be converted to a `float`.54 unmodified linesmodified:docs/tutorial/parameter-types/number.md+3 added-3 removed
1 # Number2 3 You can define numeric validations with `max` and `min` values for `int` and `float` *CLI parameters*:4 5-{* docs_src/parameter_types/number/tutorial001_an.py hl[6:8] *}5+{* docs_src/parameter_types/number/tutorial001_an.py hl[9:11] *}6 7 *CLI arguments* and *CLI options* can both use these validations.8 9 You can specify `min`, `max` or both.62 unmodified lines72 You might want to, instead of showing an error, use the closest minimum or maximum valid values.73 74 You can do it with the `clamp` parameter:75 76-{* docs_src/parameter_types/number/tutorial002_an.py hl[6:8] *}76+{* docs_src/parameter_types/number/tutorial002_an.py hl[9:11] *}77 78 And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:79 80 <div class="termy">20 unmodified lines101 ## Counter *CLI options*102 103 You can make a *CLI option* work as a counter with the `count` parameter:104 105-{* docs_src/parameter_types/number/tutorial003_an.py hl[5] *}105+{* docs_src/parameter_types/number/tutorial003_an.py hl[8] *}106 107 It means that the *CLI option* will be like a boolean flag, e.g. `--verbose`.108 109 And the value you receive in the function will be the amount of times that `--verbose` was added:36 unmodified linesmodified:docs/tutorial/parameter-types/path.md+2 added-2 removed
2 unmodified lines3 You 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>.4 5 This is what you would do for directory paths, file paths, etc:6 7-{* docs_src/parameter_types/path/tutorial001_an.py hl[1,8] *}7+{* docs_src/parameter_types/path/tutorial001_an.py hl[1,11] *}8 9 And 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.10 11 Check it:52 unmodified lines64 ///65 66 For example:67 68-{* docs_src/parameter_types/path/tutorial002_an.py hl[11:16] *}68+{* docs_src/parameter_types/path/tutorial002_an.py hl[14:19] *}69 70 Check it:71 72 <div class="termy">40 unmodified linesmodified:docs/tutorial/parameter-types/uuid.md+1 added-1 removed
20 unmodified lines21 ///22 23 You can declare a *CLI parameter* as a UUID:24 25-{* docs_src/parameter_types/uuid/tutorial001.py hl[1,6,7,8] *}25+{* docs_src/parameter_types/uuid/tutorial001.py hl[1,9:11] *}26 27 Your 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.28 29 Check it:20 unmodified linesmodified:docs/tutorial/app-dir.md+1 added-1 removed
1 # CLI Application Directory2 3 You can get the application directory where you can, for example, save configuration files with `typer.get_app_dir()`:4 5-{* docs_src/app_dir/tutorial001.py hl[9] *}5+{* docs_src/app_dir/tutorial001.py hl[12] *}6 7 It will give you a directory for storing configurations appropriate for your CLI program for the current user in each operating system.8 9 Check it:34 unmodified linesmodified:docs/tutorial/exceptions.md+11 added-11 removed
6 unmodified lines7 ## Example Broken App8 9 Let's take this example broken app:10 11-{* docs_src/exceptions/tutorial001.py hl[5] *}11+{* docs_src/exceptions/tutorial001.py hl[8] *}12 13 This code is broken because you can't sum a string and a number (`name + 3`).14 15 ## Exceptions with Rich9 unmodified lines25 ```console26 $ python main.py27 28 <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">"morty"</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">"__main__"</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">"morty"</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">"__main__"</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">'morty'</font> <font color="#F4BF75">│</font> <font color="#F92672">│</font>41 <font color="#F92672">│</font> <font color="#F4BF75">╰────────────────╯</font> <font color="#F92672">│</font>14 unmodified lines56 57 Traceback (most recent call last):58 59 File "main.py", line 12, in <module>60- typer.run(main)60+ app()61 62 File "main.py", line 8, in main63 print(name + 3)64 17 unmodified lines82 In this case, `name` is a local variable, it comes from a parameter passed to the function.83 84 But if it was something like a password, you would have liked to hide it.85 86-In that case, you can create the `typer.Typer()` application explicitly and set the parameter `pretty_exceptions_show_locals=False`:86+In that case, you can set the parameter `pretty_exceptions_show_locals=False` when creating the `typer.Typer()` application:87 88 {* docs_src/exceptions/tutorial002.py hl[3] *}89 90 And now when you run it, you will see the error without the local variables:183 unmodified linesmodified:docs/tutorial/launch.md+2 added-2 removed
2 unmodified lines3 You can launch applications from your CLI program with `typer.launch()`.4 5 It will launch the appropriate application depending on the URL or file type you pass it:6 7-{* docs_src/launch/tutorial001.py hl[6] *}7+{* docs_src/launch/tutorial001.py hl[9] *}8 9 Check it:10 11 <div class="termy">11 unmodified lines23 ## Locating a file24 25 You can also make the operating system open the file browser indicating where a file is located with `locate=True`:26 27-{* docs_src/launch/tutorial002.py hl[17] *}27+{* docs_src/launch/tutorial002.py hl[20] *}28 29 /// tip30 31 The rest of the code in this example is just making sure the app directory exists and creating the config file.18 unmodified linesmodified:docs/tutorial/printing.md+8 added-8 removed
1 # Printing and Colors2 3 You can use the normal `print()` to show information on the screen:4 5-{* docs_src/first_steps/tutorial001.py hl[5] *}5+{* docs_src/typer_app/tutorial001.py hl[8] *}6 7 It will show the output normally:8 9 <div class="termy">10 11 ```console12-$ python main.py12+$ python main.py World13 14 Hello World15 ```16 6 unmodified lines23 ### Use Rich `print`24 25 For the simplest cases, you can just import `print` from `rich` and use it instead of the standard `print`:26 27-{* docs_src/printing/tutorial001.py hl[2,15] *}27+{* docs_src/printing/tutorial001.py hl[2,18] *}28 29 Just with that, **Rich** will be able to print your data with nice colors and structure:30 31 <div class="termy">19 unmodified lines51 ### Rich Markup52 53 Rich 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:54 55-{* docs_src/printing/tutorial002.py hl[6] *}55+{* docs_src/printing/tutorial002.py hl[9] *}56 57 <div class="termy">58 59 ```console15 unmodified lines75 When you call Rich's `print`, it automatically creates this object and uses it.76 77 But for advanced use cases, you could create a `Console` yourself.78 79-{* docs_src/printing/tutorial003.py hl[2:3,5,9:12] *}79+{* docs_src/printing/tutorial003.py hl[2:3,5,12:15] *}80 81 In this example, we create a `Console`, and a `Table`. And then we can add some rows to the table, and print it.82 83 If you run it, you will see a nicely formatted table:67 unmodified lines151 ///152 153 Using `stderr=True` tells **Rich** that the output should be shown in "standard error".154 155-{* docs_src/printing/tutorial004.py hl[4,8] *}155+{* docs_src/printing/tutorial004.py hl[4,11] *}156 157 When you try it in the terminal, it will probably just look the same:158 159 <div class="termy">67 unmodified lines227 ///228 229 You 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()`:230 231-{* docs_src/printing/tutorial005.py hl[7,9] *}231+{* docs_src/printing/tutorial005.py hl[10,12] *}232 233 /// tip234 235 The 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 lines273 ///274 275 There'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()`:276 277-{* docs_src/printing/tutorial006.py hl[5] *}277+{* docs_src/printing/tutorial006.py hl[8] *}278 279 Check it:280 281 <div class="use-termynal" data-termynal>3 unmodified linesmodified:docs/tutorial/progressbar.md+6 added-6 removed
4 unmodified lines5 ## Progress Bar6 7 You 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:8 9-{* docs_src/progressbar/tutorial001.py hl[4,9] *}9+{* docs_src/progressbar/tutorial001.py hl[4,12] *}10 11 You put the thing that you want to iterate over inside of Rich's `track()`, and then iterate over that.12 13 Check it:31 unmodified lines45 Rich allows you to display many things in complex and advanced ways.46 47 For example, this will show two spinners:48 49-{* docs_src/progressbar/tutorial002.py hl[4,8:15] *}49+{* docs_src/progressbar/tutorial002.py hl[4,11:18] *}50 51 I can't show you the beautiful animation here in the docs. 😅52 53 But at some point in time it will look like this (imagine it's spinning). 🤓45 unmodified lines99 ```100 101 And you pass as function argument to `typer.progressbar()` the thing that you would normally iterate over.102 103-{* docs_src/progressbar/tutorial003.py hl[8] *}103+{* docs_src/progressbar/tutorial003.py hl[11] *}104 105 So, if you have a list of users, this could be:106 107 ```Python54 unmodified lines162 The progress bar is generated from the length of the iterable (e.g. the list of users).163 164 But 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()`.165 166-{* docs_src/progressbar/tutorial004.py hl[14] *}166+{* docs_src/progressbar/tutorial004.py hl[18] *}167 168 Check it:169 170 <div class="termy">39 unmodified lines210 ///211 212 You can also set a `label`:213 214-{* docs_src/progressbar/tutorial005.py hl[8] *}214+{* docs_src/progressbar/tutorial005.py hl[11] *}215 216 Check it:217 218 <div class="use-termynal">7 unmodified lines226 If 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()`.227 228 And then calling the `.update()` method in the object from the `with` statement:229 230-{* docs_src/progressbar/tutorial006.py hl[8,12] *}230+{* docs_src/progressbar/tutorial006.py hl[11,17] *}231 232 Check it:233 234 <div class="use-termynal">4 unmodified linesmodified:docs/tutorial/prompt.md+4 added-4 removed
2 unmodified lines3 When 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).4 5 But if you absolutely need to ask for interactive information without using a *CLI option*, you can use `typer.prompt()`:6 7-{* docs_src/prompt/tutorial001.py hl[5] *}7+{* docs_src/prompt/tutorial001.py hl[8] *}8 9 Check it:10 11 <div class="termy">11 unmodified lines23 ## Confirm24 25 There'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}:26 27-{* docs_src/prompt/tutorial002.py hl[5] *}27+{* docs_src/prompt/tutorial002.py hl[8] *}28 29 Check it:30 31 <div class="termy">19 unmodified lines51 ## Confirm or abort52 53 As it's very common to abort if the user doesn't confirm, there's an integrated parameter `abort` that does it automatically:54 55-{* docs_src/prompt/tutorial003.py hl[5] *}55+{* docs_src/prompt/tutorial003.py hl[8] *}56 57 <div class="termy">58 59 ```console16 unmodified lines76 ## Prompt with Rich77 78 If 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:79 80-{* docs_src/prompt/tutorial004.py hl[2,6] *}80+{* docs_src/prompt/tutorial004.py hl[2,9] *}81 82 And when you run it, it will look like:83 84 <div class="termy">10 unmodified linesmodified:docs/tutorial/terminating.md+2 added-2 removed
54 unmodified lines55 `typer.Exit()` takes an optional `code` parameter. By default, `code` is `0`, meaning there was no error.56 57 You 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:58 59-{* docs_src/terminating/tutorial002.py hl[7] *}59+{* docs_src/terminating/tutorial002.py hl[10] *}60 61 Check it:62 63 <div class="termy">34 unmodified lines98 There's a special exception that you can use to "abort" a program.99 100 It 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:101 102-{* docs_src/terminating/tutorial003.py hl[7] *}102+{* docs_src/terminating/tutorial003.py hl[10] *}103 104 Check it:105 106 <div class="termy">14 unmodified linesadded:docs/tutorial/typer-app.md+118 added
1+# Typer App2+3+## Explicit application4+5+So far, you have seen how to create a single function and then pass that function to `typer.run()`.6+7+For example:8+9+{* docs_src/first_steps/tutorial002.py hl[9] *}10+11+But 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()`.12+13+There's also a more explicit way to achieve the same:14+15+{* docs_src/typer_app/tutorial001.py hl[3,6,12] *}16+17+When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:18+19+* 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()`".22+23+/// info | `@decorator` Info24+25+That `@something` syntax in Python is called a "decorator".26+27+You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).28+29+A "decorator" takes the function below and does something with it.30+31+In our case, this decorator tells **Typer** that the function below is a "`command`".32+You will learn more about commands later in the section [commands](./commands/index.md){.internal-link target=_blank}.33+34+///35+36+Both ways, with `typer.run()` and creating the explicit application, achieve almost the same.37+38+/// tip39+40+If 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.41+42+You might want to do that later when your app needs extra features, but if it doesn't need them yet, that's fine.43+44+///45+46+If you run the second example, with the explicit `app`, it works exactly the same:47+48+<div class="termy">49+50+```console51+// Without a CLI argument52+$ python main.py53+54+Usage: main.py [OPTIONS] NAME55+Try "main.py --help" for help.56+57+Error: Missing argument 'NAME'.58+59+// With the NAME CLI argument60+$ python main.py Camila61+62+Hello Camila63+64+// Asking for help65+$ python main.py --help66+67+Usage: main.py [OPTIONS] NAME68+69+Options: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+```74+75+</div>76+77+## CLI application completion78+79+There's a little detail that is worth noting here.80+81+Now the help shows two new *CLI options*:82+83+* `--install-completion`84+* `--show-completion`85+86+To get shell/tab completion, it's necessary to build a package that you and your users can install and **call directly**.87+88+So instead of running a Python script like:89+90+<div class="termy">91+92+```console93+$ python main.py94+95+✨ Some magic here ✨96+```97+98+</div>99+100+...It would be called like:101+102+<div class="termy">103+104+```console105+$ magic-app106+107+✨ Some magic here ✨108+```109+110+</div>111+112+Having a standalone program like that allows setting up shell/tab completion.113+114+The first step to be able to create an installable package like that is to use an explicit `typer.Typer()` app.115+116+Later you can learn all the process to create a standalone CLI application and [Build a Package](./package.md){.internal-link target=_blank}.117+118+But 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 lines3 import typer4 5 APP_NAME = "my-super-cli-app"6 7+app = typer.Typer()8 9+10+@app.command()11 def 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")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/arguments/default/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: Annotated[str, typer.Argument()] = "Wade Wilson"):9 print(f"Hello {name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/arguments/default/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument("Wade Wilson")):8 print(f"Hello {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/default/tutorial002_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def get_name():11 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])12 13 1 unmodified line15 print(f"Hello {name}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/arguments/default/tutorial002.py+4 added-1 removed
1 import random2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def get_name():10 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])11 12 1 unmodified line14 print(f"Hello {name}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/arguments/envvar/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: Annotated[str, typer.Argument(envvar="AWESOME_NAME")] = "World"):9 print(f"Hello Mr. {name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/arguments/envvar/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument("World", envvar="AWESOME_NAME")):8 print(f"Hello Mr. {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/envvar/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: Annotated[str, typer.Argument(envvar=["AWESOME_NAME", "GOD_NAME"])] = "World",10 ):11 print(f"Hello Mr. {name}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/arguments/envvar/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument("World", envvar=["AWESOME_NAME", "GOD_NAME"])):8 print(f"Hello Mr. {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/envvar/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: Annotated[10 str, typer.Argument(envvar="AWESOME_NAME", show_envvar=False)11 ] = "World",1 unmodified line13 print(f"Hello Mr. {name}")14 15 16 if __name__ == "__main__":14- typer.run(main)17+ app()modified:docs_src/arguments/envvar/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument("World", envvar="AWESOME_NAME", show_envvar=False)):8 print(f"Hello Mr. {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/help/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):9 print(f"Hello {name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/arguments/help/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument(..., help="The name of the user to greet")):8 print(f"Hello {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/help/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/arguments/help/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/arguments/help/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/arguments/help/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/arguments/help/tutorial004_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: Annotated[10 str, typer.Argument(help="Who to greet", show_default=False)11 ] = "World",4 unmodified lines16 print(f"Hello {name}")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/arguments/help/tutorial004.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/arguments/help/tutorial005_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: Annotated[10 str,11 typer.Argument(4 unmodified lines16 print(f"Hello {name}")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/arguments/help/tutorial005.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 name: str = typer.Argument(9 "Wade Wilson", help="Who to greet", show_default="Deadpoolio the amazing's name"10 ),1 unmodified line12 print(f"Hello {name}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/arguments/help/tutorial006_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: Annotated[str, typer.Argument(metavar="✨username✨")] = "World"):9 print(f"Hello {name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/arguments/help/tutorial006.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument("World", metavar="✨username✨")):8 print(f"Hello {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/help/tutorial007_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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 lines21 print(f"Hello {name}")22 23 24 if __name__ == "__main__":22- typer.run(main)25+ app()modified:docs_src/arguments/help/tutorial007.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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 lines19 print(f"Hello {name}")20 21 22 if __name__ == "__main__":20- typer.run(main)23+ app()modified:docs_src/arguments/help/tutorial008_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/arguments/help/tutorial008.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument("World", hidden=True)):8 """9 Say hi to NAME very gently, like Dirk.10 """11 print(f"Hello {name}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()added:docs_src/arguments/optional/tutorial000.py+9 added
1+import typer2+3+4+def main(name: str = typer.Argument()):5+ print(f"Hello {name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)modified:docs_src/arguments/optional/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: Annotated[str, typer.Argument()]):9 print(f"Hello {name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/arguments/optional/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument()):8 print(f"Hello {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/optional/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: Annotated[str, typer.Argument()] = "World"):9 print(f"Hello {name}!")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/arguments/optional/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument(default="World")):8 print(f"Hello {name}!")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/arguments/optional/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = typer.Argument(default=...)):8 print(f"Hello {name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()deleted:docs_src/commands/index/tutorial001.py-12 removed
1-import typer2-3-app = typer.Typer()4-5-6-@app.command()7-def main(name: str):8- print(f"Hello {name}")9-10-11-if __name__ == "__main__":12- app()modified:docs_src/exceptions/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str = "morty"):8 print(name + 3)9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/launch/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main():8 print("Opening Typer's docs")9 typer.launch("https://typer.tiangolo.com")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/launch/tutorial002.py+4 added-1 removed
2 unmodified lines3 import typer4 5 APP_NAME = "my-super-cli-app"6 7+app = typer.Typer()8 9+10+@app.command()11 def 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 lines20 typer.launch(config_file_str, locate=True)21 22 23 if __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 line2 from typing import List3 4 import typer5 6+app = typer.Typer()7 8+9+@app.command()10 def 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)15 16 17 if __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 line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def main(11 names: Annotated[12 Tuple[str, str, str], typer.Argument(help="Select 3 characters to play with")13 ] = ("Harry", "Hermione", "Ron"),2 unmodified lines16 print(f"Hello {name}")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py+4 added-1 removed
1 from typing import Tuple2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main(10 names: Tuple[str, str, str] = typer.Argument(11 ("Harry", "Hermione", "Ron"), help="Select 3 characters to play with"12 ),2 unmodified lines15 print(f"Hello {name}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/multiple_values/multiple_options/tutorial001_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def 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 line15 print(f"Processing user: {u}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/multiple_values/multiple_options/tutorial001.py+4 added-1 removed
1 from typing import List, Optional2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def 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 line14 print(f"Processing user: {u}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/multiple_values/multiple_options/tutorial002_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def main(number: Annotated[List[float], typer.Option()] = []):11 print(f"The sum is {sum(number)}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/multiple_values/multiple_options/tutorial002.py+4 added-1 removed
1 from typing import List2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main(number: List[float] = typer.Option([])):10 print(f"The sum is {sum(number)}")11 12 13 if __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 line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def 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 lines17 print("And this user is a wizard!")18 19 20 if __name__ == "__main__":18- typer.run(main)21+ app()modified:docs_src/multiple_values/options_with_multiple_values/tutorial001.py+4 added-1 removed
1 from typing import Tuple2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def 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 lines16 print("And this user is a wizard!")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/options/callback/tutorial001_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9 def name_callback(value: str):10 if value != "Camila":11 raise typer.BadParameter("Only Camila is allowed")12 return value13 14 15+@app.command()16 def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):17 print(f"Hello {name}")18 19 20 if __name__ == "__main__":18- typer.run(main)21+ app()modified:docs_src/options/callback/tutorial001.py+4 added-1 removed
1 from typing import Optional2 3 import typer4 5+app = typer.Typer()6 7+8 def name_callback(value: str):9 if value != "Camila":10 raise typer.BadParameter("Only Camila is allowed")11 return value12 13 14+@app.command()15 def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):16 print(f"Hello {name}")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/options/callback/tutorial002_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9 def name_callback(value: str):10 print("Validating name")11 if value != "Camila":12 raise typer.BadParameter("Only Camila is allowed")13 return value14 15 16+@app.command()17 def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):18 print(f"Hello {name}")19 20 21 if __name__ == "__main__":19- typer.run(main)22+ app()modified:docs_src/options/callback/tutorial002.py+4 added-1 removed
1 from typing import Optional2 3 import typer4 5+app = typer.Typer()6 7+8 def name_callback(value: str):9 print("Validating name")10 if value != "Camila":11 raise typer.BadParameter("Only Camila is allowed")12 return value13 14 15+@app.command()16 def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):17 print(f"Hello {name}")18 19 20 if __name__ == "__main__":18- typer.run(main)21+ app()modified:docs_src/options/callback/tutorial003_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9 def name_callback(ctx: typer.Context, value: str):10 if ctx.resilient_parsing:11 return12 print("Validating name")1 unmodified line14 raise typer.BadParameter("Only Camila is allowed")15 return value16 17 18+@app.command()19 def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):20 print(f"Hello {name}")21 22 23 if __name__ == "__main__":21- typer.run(main)24+ app()modified:docs_src/options/callback/tutorial003.py+4 added-1 removed
1 from typing import Optional2 3 import typer4 5+app = typer.Typer()6 7+8 def name_callback(ctx: typer.Context, value: str):9 if ctx.resilient_parsing:10 return11 print("Validating name")1 unmodified line13 raise typer.BadParameter("Only Camila is allowed")14 return value15 16 17+@app.command()18 def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):19 print(f"Hello {name}")20 21 22 if __name__ == "__main__":20- typer.run(main)23+ app()modified:docs_src/options/callback/tutorial004_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9 def 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 line14 raise typer.BadParameter("Only Camila is allowed")15 return value16 17 18+@app.command()19 def main(name: Annotated[Optional[str], typer.Option(callback=name_callback)] = None):20 print(f"Hello {name}")21 22 23 if __name__ == "__main__":21- typer.run(main)24+ app()modified:docs_src/options/callback/tutorial004.py+4 added-1 removed
1 from typing import Optional2 3 import typer4 5+app = typer.Typer()6 7+8 def 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 line13 raise typer.BadParameter("Only Camila is allowed")14 return value15 16 17+@app.command()18 def main(name: Optional[str] = typer.Option(default=None, callback=name_callback)):19 print(f"Hello {name}")20 21 22 if __name__ == "__main__":20- typer.run(main)23+ app()modified:docs_src/options/help/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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 lines21 print(f"Hello {name} {lastname}")22 23 24 if __name__ == "__main__":22- typer.run(main)25+ app()modified:docs_src/options/help/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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 lines20 print(f"Hello {name} {lastname}")21 22 23 if __name__ == "__main__":21- typer.run(main)24+ app()modified:docs_src/options/help/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: str,10 lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",11 formal: Annotated[20 unmodified lines32 print(f"Hello {name} {lastname}")33 34 35 if __name__ == "__main__":33- typer.run(main)36+ app()modified:docs_src/options/help/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 name: str,9 lastname: str = typer.Option("", help="Last name of person to greet."),10 formal: bool = typer.Option(14 unmodified lines25 print(f"Hello {name} {lastname}")26 27 28 if __name__ == "__main__":26- typer.run(main)29+ app()modified:docs_src/options/help/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(fullname: Annotated[str, typer.Option(show_default=False)] = "Wade Wilson"):9 print(f"Hello {fullname}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/help/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(fullname: str = typer.Option("Wade Wilson", show_default=False)):8 print(f"Hello {fullname}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/help/tutorial004_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 fullname: Annotated[10 str, typer.Option(show_default="Deadpoolio the amazing's name")11 ] = "Wade Wilson",1 unmodified line13 print(f"Hello {fullname}")14 15 16 if __name__ == "__main__":14- typer.run(main)17+ app()modified:docs_src/options/help/tutorial004.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 fullname: str = typer.Option(9 "Wade Wilson", show_default="Deadpoolio the amazing's name"10 ),1 unmodified line12 print(f"Hello {fullname}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/options/name/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(user_name: Annotated[str, typer.Option("--name")]):9 print(f"Hello {user_name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/name/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(user_name: str = typer.Option(..., "--name")):8 print(f"Hello {user_name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/name/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(user_name: Annotated[str, typer.Option("--name", "-n")]):9 print(f"Hello {user_name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/name/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(user_name: str = typer.Option(..., "--name", "-n")):8 print(f"Hello {user_name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/name/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(user_name: Annotated[str, typer.Option("-n")]):9 print(f"Hello {user_name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/name/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(user_name: str = typer.Option(..., "-n")):8 print(f"Hello {user_name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/name/tutorial004_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(user_name: Annotated[str, typer.Option("--user-name", "-n")]):9 print(f"Hello {user_name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/name/tutorial004.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(user_name: str = typer.Option(..., "--user-name", "-n")):8 print(f"Hello {user_name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/name/tutorial005_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: Annotated[str, typer.Option("--name", "-n")],10 formal: Annotated[bool, typer.Option("--formal", "-f")] = False,11 ):3 unmodified lines15 print(f"Hello {name}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/options/name/tutorial005.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 name: str = typer.Option(..., "--name", "-n"),9 formal: bool = typer.Option(False, "--formal", "-f"),10 ):3 unmodified lines14 print(f"Hello {name}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/options/password/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/options/password/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 name: str, email: str = typer.Option(..., prompt=True, confirmation_prompt=True)9 ):10 print(f"Hello {name}, your email is {email}")11 12 13 if __name__ == "__main__":11- typer.run(main)14+ app()modified:docs_src/options/password/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: str,10 password: Annotated[11 str, typer.Option(prompt=True, confirmation_prompt=True, hide_input=True)3 unmodified lines15 print(f"...just kidding, here it is, very insecure: {password}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/options/password/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 name: str,9 password: str = typer.Option(10 ..., prompt=True, confirmation_prompt=True, hide_input=True3 unmodified lines14 print(f"...just kidding, here it is, very insecure: {password}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/options/prompt/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):9 print(f"Hello {name} {lastname}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/prompt/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str, lastname: str = typer.Option(..., prompt=True)):8 print(f"Hello {name} {lastname}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/prompt/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 name: str,10 lastname: Annotated[str, typer.Option(prompt="Please tell me your last name")],11 ):12 print(f"Hello {name} {lastname}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/options/prompt/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(8 name: str, lastname: str = typer.Option(..., prompt="Please tell me your last name")9 ):10 print(f"Hello {name} {lastname}")11 12 13 if __name__ == "__main__":11- typer.run(main)14+ app()modified:docs_src/options/prompt/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 project_name: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)],10 ):11 print(f"Deleting project {project_name}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/options/prompt/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(project_name: str = typer.Option(..., prompt=True, confirmation_prompt=True)):8 print(f"Deleting project {project_name}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/required/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(name: str, lastname: Annotated[str, typer.Option()]):9 print(f"Hello {name} {lastname}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/options/required/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str, lastname: str = typer.Option()):8 print(f"Hello {name} {lastname}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/required/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str, lastname: str = typer.Option(default=...)):8 print(f"Hello {name} {lastname}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/options/version/tutorial001_an.py+4 added-1 removed
3 unmodified lines4 from typing_extensions import Annotated5 6 __version__ = "0.1.0"7 8+app = typer.Typer()9 10+11 def version_callback(value: bool):12 if value:13 print(f"Awesome CLI Version: {__version__}")14 raise typer.Exit()15 16 17+@app.command()18 def main(19 name: Annotated[str, typer.Option()] = "World",20 version: Annotated[21 Optional[bool], typer.Option("--version", callback=version_callback)2 unmodified lines24 print(f"Hello {name}")25 26 27 if __name__ == "__main__":25- typer.run(main)28+ app()modified:docs_src/options/version/tutorial001.py+4 added-1 removed
2 unmodified lines3 import typer4 5 __version__ = "0.1.0"6 7+app = typer.Typer()8 9+10 def version_callback(value: bool):11 if value:12 print(f"Awesome CLI Version: {__version__}")13 raise typer.Exit()14 15 16+@app.command()17 def main(18 name: str = typer.Option("World"),19 version: Optional[bool] = typer.Option(20 None, "--version", callback=version_callback2 unmodified lines23 print(f"Hello {name}")24 25 26 if __name__ == "__main__":24- typer.run(main)27+ app()modified:docs_src/options/version/tutorial002_an.py+4 added-1 removed
3 unmodified lines4 from typing_extensions import Annotated5 6 __version__ = "0.1.0"7 8+app = typer.Typer()9 10+11 def version_callback(value: bool):12 if value:13 print(f"Awesome CLI Version: {__version__}")14 raise typer.Exit()3 unmodified lines18 if name != "Camila":19 raise typer.BadParameter("Only Camila is allowed")20 21 22+@app.command()23 def main(24 name: Annotated[str, typer.Option(callback=name_callback)],25 version: Annotated[26 Optional[bool], typer.Option("--version", callback=version_callback)2 unmodified lines29 print(f"Hello {name}")30 31 32 if __name__ == "__main__":30- typer.run(main)33+ app()modified:docs_src/options/version/tutorial002.py+4 added-1 removed
2 unmodified lines3 import typer4 5 __version__ = "0.1.0"6 7+app = typer.Typer()8 9+10 def version_callback(value: bool):11 if value:12 print(f"Awesome CLI Version: {__version__}")13 raise typer.Exit()3 unmodified lines17 if name != "Camila":18 raise typer.BadParameter("Only Camila is allowed")19 20 21+@app.command()22 def main(23 name: str = typer.Option(..., callback=name_callback),24 version: Optional[bool] = typer.Option(25 None, "--version", callback=version_callback2 unmodified lines28 print(f"Hello {name}")29 30 31 if __name__ == "__main__":29- typer.run(main)32+ app()modified:docs_src/options/version/tutorial003_an.py+4 added-1 removed
3 unmodified lines4 from typing_extensions import Annotated5 6 __version__ = "0.1.0"7 8+app = typer.Typer()9 10+11 def version_callback(value: bool):12 if value:13 print(f"Awesome CLI Version: {__version__}")14 raise typer.Exit()4 unmodified lines19 raise typer.BadParameter("Only Camila is allowed")20 return name21 22 23+@app.command()24 def main(25 name: Annotated[str, typer.Option(callback=name_callback)],26 version: Annotated[27 Optional[bool],3 unmodified lines31 print(f"Hello {name}")32 33 34 if __name__ == "__main__":32- typer.run(main)35+ app()modified:docs_src/options/version/tutorial003.py+4 added-1 removed
2 unmodified lines3 import typer4 5 __version__ = "0.1.0"6 7+app = typer.Typer()8 9+10 def version_callback(value: bool):11 if value:12 print(f"Awesome CLI Version: {__version__}")13 raise typer.Exit()4 unmodified lines18 raise typer.BadParameter("Only Camila is allowed")19 return name20 21 22+@app.command()23 def main(24 name: str = typer.Option(..., callback=name_callback),25 version: Optional[bool] = typer.Option(26 None, "--version", callback=version_callback, is_eager=True2 unmodified lines29 print(f"Hello {name}")30 31 32 if __name__ == "__main__":30- typer.run(main)33+ app()modified:docs_src/parameter_types/bool/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(force: Annotated[bool, typer.Option("--force")] = False):9 if force:10 print("Forcing operation")11 else:12 print("Not forcing")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/parameter_types/bool/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(force: bool = typer.Option(False, "--force")):8 if force:9 print("Forcing operation")10 else:11 print("Not forcing")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/parameter_types/bool/tutorial002_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def 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 lines16 print("Rejecting!")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/parameter_types/bool/tutorial002.py+4 added-1 removed
1 from typing import Optional2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def 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 lines15 print("Rejecting!")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/parameter_types/bool/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/parameter_types/bool/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(force: bool = typer.Option(False, "--force/--no-force", "-f/-F")):8 if force:9 print("Forcing operation")10 else:11 print("Not forcing")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/parameter_types/bool/tutorial004_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/parameter_types/bool/tutorial004.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(in_prod: bool = typer.Option(True, " /--demo", " /-d")):8 if in_prod:9 print("Running in production")10 else:11 print("Running demo")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/parameter_types/custom_types/tutorial001_an.py+5 added-1 removed
12 unmodified lines13 def parse_custom_class(value: str):14 return CustomClass(value * 2)15 16 17+app = typer.Typer()18+19+20+@app.command()21 def 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 line26 print(f"--custom-opt is {custom_opt}")27 28 29 if __name__ == "__main__":26- typer.run(main)30+ app()modified:docs_src/parameter_types/custom_types/tutorial001.py+5 added-1 removed
11 unmodified lines12 def parse_custom_class(value: str):13 return CustomClass(value * 2)14 15 16+app = typer.Typer()17+18+19+@app.command()20 def 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 line25 print(f"--custom-opt is {custom_opt}")26 27 28 if __name__ == "__main__":25- typer.run(main)29+ app()modified:docs_src/parameter_types/custom_types/tutorial002_an.py+5 added-1 removed
16 unmodified lines17 def convert(self, value, param, ctx):18 return CustomClass(value * 3)19 20 21+app = typer.Typer()22+23+24+@app.command()25 def main(26 custom_arg: Annotated[CustomClass, typer.Argument(click_type=CustomClassParser())],27 custom_opt: Annotated[28 CustomClass, typer.Option(click_type=CustomClassParser())3 unmodified lines32 print(f"--custom-opt is {custom_opt}")33 34 35 if __name__ == "__main__":32- typer.run(main)36+ app()modified:docs_src/parameter_types/custom_types/tutorial002.py+5 added-1 removed
15 unmodified lines16 def convert(self, value, param, ctx):17 return CustomClass(value * 3)18 19 20+app = typer.Typer()21+22+23+@app.command()24 def main(25 custom_arg: CustomClass = typer.Argument(click_type=CustomClassParser()),26 custom_opt: CustomClass = typer.Option("Foo", click_type=CustomClassParser()),27 ):1 unmodified line29 print(f"--custom-opt is {custom_opt}")30 31 32 if __name__ == "__main__":29- typer.run(main)33+ app()modified:docs_src/parameter_types/datetime/tutorial001.py+4 added-1 removed
1 from datetime import datetime2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main(birth: datetime):10 print(f"Interesting day to be born: {birth}")11 print(f"Birth hour: {birth.hour}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/parameter_types/datetime/tutorial002_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def main(11 launch_date: Annotated[12 datetime,13 typer.Argument(4 unmodified lines18 print(f"Launch will be at: {launch_date}")19 20 21 if __name__ == "__main__":19- typer.run(main)22+ app()modified:docs_src/parameter_types/datetime/tutorial002.py+4 added-1 removed
1 from datetime import datetime2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def 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 line14 print(f"Launch will be at: {launch_date}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/parameter_types/enum/tutorial001.py+5 added-1 removed
7 unmodified lines8 conv = "conv"9 lstm = "lstm"10 11 12+app = typer.Typer()13+14+15+@app.command()16 def main(network: NeuralNetwork = NeuralNetwork.simple):17 print(f"Training neural network of type: {network.value}")18 19 20 if __name__ == "__main__":17- typer.run(main)21+ app()modified:docs_src/parameter_types/enum/tutorial002_an.py+5 added-1 removed
8 unmodified lines9 conv = "conv"10 lstm = "lstm"11 12 13+app = typer.Typer()14+15+16+@app.command()17 def main(18 network: Annotated[19 NeuralNetwork, typer.Option(case_sensitive=False)20 ] = NeuralNetwork.simple,1 unmodified line22 print(f"Training neural network of type: {network.value}")23 24 25 if __name__ == "__main__":22- typer.run(main)26+ app()modified:docs_src/parameter_types/enum/tutorial002.py+5 added-1 removed
7 unmodified lines8 conv = "conv"9 lstm = "lstm"10 11 12+app = typer.Typer()13+14+15+@app.command()16 def main(17 network: NeuralNetwork = typer.Option(NeuralNetwork.simple, case_sensitive=False),18 ):19 print(f"Training neural network of type: {network.value}")20 21 22 if __name__ == "__main__":19- typer.run(main)23+ app()modified:docs_src/parameter_types/enum/tutorial003_an.py+5 added-1 removed
9 unmodified lines10 food_2 = "Bacon"11 food_3 = "Cheese"12 13 14+app = typer.Typer()15+16+17+@app.command()18 def 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])}")20 21 22 if __name__ == "__main__":19- typer.run(main)23+ app()modified:docs_src/parameter_types/enum/tutorial003.py+5 added-1 removed
8 unmodified lines9 food_2 = "Bacon"10 food_3 = "Cheese"11 12 13+app = typer.Typer()14+15+16+@app.command()17 def main(groceries: List[Food] = typer.Option([Food.food_1, Food.food_3])):18 print(f"Buying groceries: {', '.join([f.value for f in groceries])}")19 20 21 if __name__ == "__main__":18- typer.run(main)22+ app()modified:docs_src/parameter_types/enum/tutorial004_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated, Literal3 4+app = typer.Typer()5 6+7+@app.command()8 def main(9 network: Annotated[Literal["simple", "conv", "lstm"], typer.Option()] = "simple",10 ):11 print(f"Training neural network of type: {network}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/parameter_types/enum/tutorial004.py+4 added-1 removed
1 import typer2 from typing_extensions import Literal3 4+app = typer.Typer()5 6+7+@app.command()8 def main(network: Literal["simple", "conv", "lstm"] = typer.Option("simple")):9 print(f"Training neural network of type: {network}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/parameter_types/file/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(config: Annotated[typer.FileText, typer.Option()]):9 for line in config:10 print(f"Config line: {line}")11 12 13 if __name__ == "__main__":11- typer.run(main)14+ app()modified:docs_src/parameter_types/file/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(config: typer.FileText = typer.Option(...)):8 for line in config:9 print(f"Config line: {line}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/parameter_types/file/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(config: Annotated[typer.FileTextWrite, typer.Option()]):9 config.write("Some config written by the app")10 print("Config written")11 12 13 if __name__ == "__main__":11- typer.run(main)14+ app()modified:docs_src/parameter_types/file/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(config: typer.FileTextWrite = typer.Option(...)):8 config.write("Some config written by the app")9 print("Config written")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/parameter_types/file/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):9 processed_total = 010 for bytes_chunk in file:11 # Process the bytes in bytes_chunk1 unmodified line13 print(f"Processed bytes total: {processed_total}")14 15 16 if __name__ == "__main__":14- typer.run(main)17+ app()modified:docs_src/parameter_types/file/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(file: typer.FileBinaryRead = typer.Option(...)):8 processed_total = 09 for bytes_chunk in file:10 # Process the bytes in bytes_chunk1 unmodified line12 print(f"Processed bytes total: {processed_total}")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/parameter_types/file/tutorial004_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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 lines17 print("Binary file written")18 19 20 if __name__ == "__main__":18- typer.run(main)21+ app()modified:docs_src/parameter_types/file/tutorial004.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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 lines16 print("Binary file written")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/parameter_types/file/tutorial005_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):9 config.write("This is a single line\n")10 print("Config line written")11 12 13 if __name__ == "__main__":11- typer.run(main)14+ app()modified:docs_src/parameter_types/file/tutorial005.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(config: typer.FileText = typer.Option(..., mode="a")):8 config.write("This is a single line\n")9 print("Config line written")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/parameter_types/index/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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)}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/parameter_types/number/tutorial001_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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 lines15 print(f"--score is {score}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/parameter_types/number/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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 lines14 print(f"--score is {score}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/parameter_types/number/tutorial002_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def 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 lines15 print(f"--score is {score}")16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/parameter_types/number/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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 lines14 print(f"--score is {score}")15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/parameter_types/number/tutorial003_an.py+4 added-1 removed
1 import typer2 from typing_extensions import Annotated3 4+app = typer.Typer()5 6+7+@app.command()8 def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):9 print(f"Verbose level is {verbose}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/parameter_types/number/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(verbose: int = typer.Option(0, "--verbose", "-v", count=True)):8 print(f"Verbose level is {verbose}")9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/parameter_types/path/tutorial001_an.py+4 added-1 removed
2 unmodified lines3 4 import typer5 from typing_extensions import Annotated6 7+app = typer.Typer()8 9+10+@app.command()11 def main(config: Annotated[Optional[Path], typer.Option()] = None):12 if config is None:13 print("No config file")14 raise typer.Abort()6 unmodified lines21 print("The config doesn't exist")22 23 24 if __name__ == "__main__":22- typer.run(main)25+ app()modified:docs_src/parameter_types/path/tutorial001.py+4 added-1 removed
1 unmodified line2 from typing import Optional3 4 import typer5 6+app = typer.Typer()7 8+9+@app.command()10 def main(config: Optional[Path] = typer.Option(None)):11 if config is None:12 print("No config file")13 raise typer.Abort()6 unmodified lines20 print("The config doesn't exist")21 22 23 if __name__ == "__main__":21- typer.run(main)24+ app()modified:docs_src/parameter_types/path/tutorial002_an.py+4 added-1 removed
1 unmodified line2 3 import typer4 from typing_extensions import Annotated5 6+app = typer.Typer()7 8+9+@app.command()10 def main(11 config: Annotated[12 Path,13 typer.Option(10 unmodified lines24 print(f"Config file contents: {text}")25 26 27 if __name__ == "__main__":25- typer.run(main)28+ app()modified:docs_src/parameter_types/path/tutorial002.py+4 added-1 removed
1 from pathlib import Path2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main(10 config: Path = typer.Option(11 ...,12 exists=True,8 unmodified lines21 print(f"Config file contents: {text}")22 23 24 if __name__ == "__main__":22- typer.run(main)25+ app()modified:docs_src/parameter_types/uuid/tutorial001.py+4 added-1 removed
1 from uuid import UUID2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main(user_id: UUID):10 print(f"USER_ID is {user_id}")11 print(f"UUID version is: {user_id.version}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/printing/tutorial001.py+4 added-1 removed
7 unmodified lines8 "active": True,9 "affiliation": None,10 }11 12+app = typer.Typer()13 14+15+@app.command()16 def main():17 print("Here's the data")18 print(data)19 20 21 if __name__ == "__main__":19- typer.run(main)22+ app()modified:docs_src/printing/tutorial002.py+4 added-1 removed
1 import typer2 from rich import print3 4+app = typer.Typer()5 6+7+@app.command()8 def main():9 print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/printing/tutorial003.py+4 added-1 removed
2 unmodified lines3 from rich.table import Table4 5 console = Console()6 7+app = typer.Typer()8 9+10+@app.command()11 def main():12 table = Table("Name", "Item")13 table.add_row("Rick", "Portal Gun")14 table.add_row("Morty", "Plumbus")15 console.print(table)16 17 18 if __name__ == "__main__":16- typer.run(main)19+ app()modified:docs_src/printing/tutorial004.py+4 added-1 removed
1 unmodified line2 from rich.console import Console3 4 err_console = Console(stderr=True)5 6+app = typer.Typer()7 8+9+@app.command()10 def main():11 err_console.print("Here is something written to standard error")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/printing/tutorial005.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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 lines14 typer.echo(message)15 16 17 if __name__ == "__main__":15- typer.run(main)18+ app()modified:docs_src/printing/tutorial006.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main(name: str):8 typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)9 10 11 if __name__ == "__main__":9- typer.run(main)12+ app()modified:docs_src/progressbar/tutorial001.py+4 added-1 removed
1 unmodified line2 3 import typer4 from rich.progress import track5 6+app = typer.Typer()7 8+9+@app.command()10 def main():11 total = 012 for value in track(range(100), description="Processing..."):13 # Fake processing time2 unmodified lines16 print(f"Processed {total} things.")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/progressbar/tutorial002.py+4 added-1 removed
1 unmodified line2 3 import typer4 from rich.progress import Progress, SpinnerColumn, TextColumn5 6+app = typer.Typer()7 8+9+@app.command()10 def main():11 with Progress(12 SpinnerColumn(),13 TextColumn("[progress.description]{task.description}"),5 unmodified lines19 print("Done!")20 21 22 if __name__ == "__main__":20- typer.run(main)23+ app()modified:docs_src/progressbar/tutorial003.py+4 added-1 removed
1 import time2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main():10 total = 011 with typer.progressbar(range(100)) as progress:12 for value in progress:3 unmodified lines16 print(f"Processed {total} things.")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/progressbar/tutorial004.py+5 added-1 removed
7 unmodified lines8 for i in range(100):9 yield i10 11 12+app = typer.Typer()13+14+15+@app.command()16 def main():17 total = 018 with typer.progressbar(iterate_user_ids(), length=100) as progress:19 for value in progress:3 unmodified lines23 print(f"Processed {total} user IDs.")24 25 26 if __name__ == "__main__":23- typer.run(main)27+ app()modified:docs_src/progressbar/tutorial005.py+4 added-1 removed
1 import time2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main():10 total = 011 with typer.progressbar(range(100), label="Processing") as progress:12 for value in progress:3 unmodified lines16 print(f"Processed {total} things.")17 18 19 if __name__ == "__main__":17- typer.run(main)20+ app()modified:docs_src/progressbar/tutorial006.py+4 added-1 removed
1 import time2 3 import typer4 5+app = typer.Typer()6 7+8+@app.command()9 def main():10 total = 100011 with typer.progressbar(length=total) as progress:12 for batch in range(4):5 unmodified lines18 print(f"Processed {total} things in batches.")19 20 21 if __name__ == "__main__":19- typer.run(main)22+ app()modified:docs_src/prompt/tutorial001.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main():8 person_name = typer.prompt("What's your name?")9 print(f"Hello {person_name}")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/prompt/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main():8 delete = typer.confirm("Are you sure you want to delete it?")9 if not delete:10 print("Not deleting")1 unmodified line12 print("Deleting it!")13 14 15 if __name__ == "__main__":13- typer.run(main)16+ app()modified:docs_src/prompt/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def main():8 delete = typer.confirm("Are you sure you want to delete it?", abort=True)9 print("Deleting it!")10 11 12 if __name__ == "__main__":10- typer.run(main)13+ app()modified:docs_src/prompt/tutorial004.py+4 added-1 removed
1 import typer2 from rich.prompt import Prompt3 4+app = typer.Typer()5 6+7+@app.command()8 def main():9 name = Prompt.ask("Enter your name :sunglasses:")10 print(f"Hey there {name}!")11 12 13 if __name__ == "__main__":11- typer.run(main)14+ app()modified:docs_src/terminating/tutorial001.py+5 added-1 removed
14 unmodified lines15 # Somehow send a notification here for the new user, maybe an email16 print(f"Notification sent for new user: {username}")17 18 19+app = typer.Typer()20+21+22+@app.command()23 def main(username: str):24 maybe_create_user(username=username)25 send_new_user_notification(username=username)26 27 28 if __name__ == "__main__":25- typer.run(main)29+ app()modified:docs_src/terminating/tutorial002.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:docs_src/terminating/tutorial003.py+4 added-1 removed
1 import typer2 3+app = typer.Typer()4 5+6+@app.command()7 def 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}")12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()added:docs_src/typer_app/tutorial001.py+12 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def main(name: str):8+ print(f"Hello {name}")9+10+11+if __name__ == "__main__":12+ app()modified:tests/assets/type_error_no_rich.py+4 added-1 removed
1 unmodified line2 import typer.main3 4 typer.main.HAS_RICH = False5 6+app = typer.Typer()7 8+9+@app.command()10 def main(name: str = "morty"):11 print(name + 3)12 13 14 if __name__ == "__main__":12- typer.run(main)15+ app()modified:tests/test_completion/test_completion_install.py+1 added-1 removed
6 unmodified lines7 import shellingham8 import typer9 from typer.testing import CliRunner10 11-from docs_src.commands.index import tutorial001 as mod11+from docs_src.typer_app import tutorial001 as mod12 13 from ..utils import requires_completion_permission14 15 runner = CliRunner()157 unmodified linesmodified:tests/test_completion/test_completion_show.py+1 added-1 removed
5 unmodified lines6 import shellingham7 import typer8 from typer.testing import CliRunner9 10-from docs_src.commands.index import tutorial001 as mod10+from docs_src.typer_app import tutorial001 as mod11 12 runner = CliRunner()13 app = typer.Typer()14 app.command()(mod.main)135 unmodified linesmodified:tests/test_completion/test_completion.py+1 added-1 removed
1 unmodified line2 import subprocess3 import sys4 from pathlib import Path5 6-from docs_src.commands.index import tutorial001 as mod6+from docs_src.typer_app import tutorial001 as mod7 8 from ..utils import needs_bash, needs_linux, requires_completion_permission9 10 154 unmodified linesdeleted:tests/test_tutorial/test_commands/test_index/test_tutorial001.py-31 removed
1-import subprocess2-import sys3-4-from typer.testing import CliRunner5-6-from docs_src.commands.index import tutorial001 as mod7-8-app = mod.app9-10-runner = CliRunner()11-12-13-def test_no_arg():14- result = runner.invoke(app)15- assert result.exit_code != 016- assert "Missing argument 'NAME'." in result.output17-18-19-def test_arg():20- result = runner.invoke(app, ["Camila"])21- assert result.exit_code == 022- assert "Hello Camila" in result.output23-24-25-def 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.stdoutmodified:tests/test_tutorial/test_exceptions/test_tutorial001.py+2 added-2 removed
18 unmodified lines19 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},20 )21 assert "return get_command(self)(*args, **kwargs)" not in result.stderr22 23- 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 lines35 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": "1"},36 )37 assert "return get_command(self)(*args, **kwargs)" in result.stderr38 39- 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 linesadded:tests/test_tutorial/test_typer_app/__init__.py
added:tests/test_tutorial/test_typer_app/test_tutorial001.py+31 added
1+import subprocess2+import sys3+4+from typer.testing import CliRunner5+6+from docs_src.typer_app import tutorial001 as mod7+8+app = mod.app9+10+runner = CliRunner()11+12+13+def test_no_arg():14+ result = runner.invoke(app)15+ assert result.exit_code != 016+ assert "Missing argument 'NAME'." in result.output17+18+19+def test_arg():20+ result = runner.invoke(app, ["Camila"])21+ assert result.exit_code == 022+ assert "Hello Camila" in result.output23+24+25+def 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.stdoutmodified:tests/test_tracebacks.py+1 added-1 removed
12 unmodified lines13 env={**os.environ, "_TYPER_STANDARD_TRACEBACK": ""},14 )15 assert "return get_command(self)(*args, **kwargs)" not in result.stderr16 17- 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.stderr20 21 31 unmodified linesmodified:mkdocs.yml+1 added
75 unmodified lines76 - 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.md145 unmodified lines