Skip to content
Myr

🔧 Update tabs and admonitions with new syntax and new MkDocs features (#906)

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

* 📝 Update docs tabs to use new pymdownextensions tab blocks * 📝 Update docs with new admonitions * 🔧 Update MkDocs config with new Markdown plugins and configs

authored by Sebastián Ramírez · committed by GitHub · parent a4a3db3 · Browse files · 49 files+2079 added−1174 removed
This commit

State

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

Diff stats

49 files+2079 added−1174 removed

  • other:+2079 added−1174 removed

49 files+2079 added−1174 removed

modified:docs/tutorial/arguments/default.md+45 added-25 removed
modified:docs/tutorial/arguments/envvar.md+57 added-33 removed
1You can also configure a *CLI argument* to read a value from an environment variable if it is not provided in the command line as a *CLI argument*.23To do that, use the `envvar` parameter for `typer.Argument()`:45=== "Python 3.7+"5//// tab | Python 3.7+67 ```Python hl_lines="5"8 {!> ../docs_src/arguments/envvar/tutorial001_an.py!}9 ```7```Python hl_lines="5"8{!> ../docs_src/arguments/envvar/tutorial001_an.py!}9```1011=== "Python 3.7+ non-Annotated"11////1213 !!! tip14 Prefer to use the `Annotated` version if possible.13//// tab | Python 3.7+ non-Annotated1416 ```Python hl_lines="4"17 {!> ../docs_src/arguments/envvar/tutorial001.py!}18 ```15/// tip1617Prefer to use the `Annotated` version if possible.1819///2021```Python hl_lines="4"22{!> ../docs_src/arguments/envvar/tutorial001.py!}23```2425////2627In 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:2829<div class="termy">30
35 unmodified lines
66## Multiple environment variables6768You 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:6963=== "Python 3.7+"70//// tab | Python 3.7+7165 ```Python hl_lines="6"66 {!> ../docs_src/arguments/envvar/tutorial002_an.py!}67 ```72```Python hl_lines="6"73{!> ../docs_src/arguments/envvar/tutorial002_an.py!}74```7569=== "Python 3.7+ non-Annotated"76////7771 !!! tip72 Prefer to use the `Annotated` version if possible.78//// tab | Python 3.7+ non-Annotated7974 ```Python hl_lines="4"75 {!> ../docs_src/arguments/envvar/tutorial002.py!}76 ```80/// tip8182Prefer to use the `Annotated` version if possible.8384///8586```Python hl_lines="4"87{!> ../docs_src/arguments/envvar/tutorial002.py!}88```8990////9192Check it:9394<div class="termy">95
25 unmodified lines
121## Hide an env var from the help text122123By default, environment variables used will be shown in the help text, but you can disable them with `show_envvar=False`:124111=== "Python 3.7+"125//// tab | Python 3.7+126113 ```Python hl_lines="7"114 {!> ../docs_src/arguments/envvar/tutorial003_an.py!}115 ```127```Python hl_lines="7"128{!> ../docs_src/arguments/envvar/tutorial003_an.py!}129```130117=== "Python 3.7+ non-Annotated"131////132119 !!! tip120 Prefer to use the `Annotated` version if possible.133//// tab | Python 3.7+ non-Annotated134122 ```Python hl_lines="4"123 {!> ../docs_src/arguments/envvar/tutorial003.py!}124 ```135/// tip136137Prefer to use the `Annotated` version if possible.138139///140141```Python hl_lines="4"142{!> ../docs_src/arguments/envvar/tutorial003.py!}143```144145////146147Check it:148149<div class="termy">150
17 unmodified lines
168```169170</div>171151!!! note "Technical Details"152 In Click applications the env vars are hidden by default. 🙈172/// note | Technical Details173174In Click applications the env vars are hidden by default. 🙈175154 In **Typer** these env vars are shown by default. 👀176In **Typer** these env vars are shown by default. 👀177178///
modified:docs/tutorial/arguments/help.md+153 added-88 removed
10 unmodified lines
11## Add a `help` text for a *CLI argument*1213You can use the `help` parameter to add a help text for a *CLI argument*:1415=== "Python 3.7+"15//// tab | Python 3.7+1617 ```Python hl_lines="5"18 {!> ../docs_src/arguments/help/tutorial001_an.py!}19 ```17```Python hl_lines="5"18{!> ../docs_src/arguments/help/tutorial001_an.py!}19```2021=== "Python 3.7+ non-Annotated"21////2223 !!! tip24 Prefer to use the `Annotated` version if possible.23//// tab | Python 3.7+ non-Annotated2426 ```Python hl_lines="4"27 {!> ../docs_src/arguments/help/tutorial001.py!}28 ```25/// tip2627Prefer to use the `Annotated` version if possible.2829///3031```Python hl_lines="4"32{!> ../docs_src/arguments/help/tutorial001.py!}33```3435////3637And it will be used in the automatic `--help` option:3839<div class="termy">40
15 unmodified lines
56## Combine help text and docstrings5758And 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>:5953=== "Python 3.7+"60//// tab | Python 3.7+6155 ```Python hl_lines="5-8"56 {!> ../docs_src/arguments/help/tutorial002_an.py!}57 ```62```Python hl_lines="5-8"63{!> ../docs_src/arguments/help/tutorial002_an.py!}64```6559=== "Python 3.7+ non-Annotated"66////6761 !!! tip62 Prefer to use the `Annotated` version if possible.68//// tab | Python 3.7+ non-Annotated6964 ```Python hl_lines="4-7"65 {!> ../docs_src/arguments/help/tutorial002.py!}66 ```70/// tip7172Prefer to use the `Annotated` version if possible.7374///7576```Python hl_lines="4-7"77{!> ../docs_src/arguments/help/tutorial002.py!}78```7980////8182And the `--help` option will combine all the information:8384<div class="termy">85
17 unmodified lines
103## Help with defaults104105If you have a *CLI argument* with a default value, like `"World"`:10693=== "Python 3.7+"107//// tab | Python 3.7+10895 ```Python hl_lines="5"96 {!> ../docs_src/arguments/help/tutorial003_an.py!}97 ```109```Python hl_lines="5"110{!> ../docs_src/arguments/help/tutorial003_an.py!}111```11299=== "Python 3.7+ non-Annotated"113////114101 !!! tip102 Prefer to use the `Annotated` version if possible.115//// tab | Python 3.7+ non-Annotated116104 ```Python hl_lines="4"105 {!> ../docs_src/arguments/help/tutorial003.py!}106 ```117/// tip118119Prefer to use the `Annotated` version if possible.120121///122123```Python hl_lines="4"124{!> ../docs_src/arguments/help/tutorial003.py!}125```126127////128129It will show that default value in the help text:130131<div class="termy">132
15 unmodified lines
148</div>149150But you can disable that if you want to, with `show_default=False`:151131=== "Python 3.7+"152//// tab | Python 3.7+153133 ```Python hl_lines="7"134 {!> ../docs_src/arguments/help/tutorial004_an.py!}135 ```154```Python hl_lines="7"155{!> ../docs_src/arguments/help/tutorial004_an.py!}156```157137=== "Python 3.7+ non-Annotated"158////159139 !!! tip140 Prefer to use the `Annotated` version if possible.160//// tab | Python 3.7+ non-Annotated161142 ```Python hl_lines="4"143 {!> ../docs_src/arguments/help/tutorial004.py!}144 ```162/// tip163164Prefer to use the `Annotated` version if possible.165166///167168```Python hl_lines="4"169{!> ../docs_src/arguments/help/tutorial004.py!}170```171172////173174And then it won't show the default value:175176<div class="termy">177
13 unmodified lines
191```192193</div>194167!!! note "Technical Details"168 In Click applications the default values are hidden by default. 🙈195/// note | Technical Details196170 In **Typer** these default values are shown by default. 👀197In Click applications the default values are hidden by default. 🙈198199In **Typer** these default values are shown by default. 👀200201///202203## Custom default string204205You 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:206176=== "Python 3.7+"207//// tab | Python 3.7+208178 ```Python hl_lines="9"179 {!> ../docs_src/arguments/help/tutorial005_an.py!}180 ```209```Python hl_lines="9"210{!> ../docs_src/arguments/help/tutorial005_an.py!}211```212182=== "Python 3.7+ non-Annotated"213////214184 !!! tip185 Prefer to use the `Annotated` version if possible.215//// tab | Python 3.7+ non-Annotated216187 ```Python hl_lines="6"188 {!> ../docs_src/arguments/help/tutorial005.py!}189 ```217/// tip218219Prefer to use the `Annotated` version if possible.220221///222223```Python hl_lines="6"224{!> ../docs_src/arguments/help/tutorial005.py!}225```226227////228229And it will be used in the help text:230231<div class="termy">232
35 unmodified lines
268But you can customize it with the `metavar` parameter for `typer.Argument()`.269270For 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:271234=== "Python 3.7+"272//// tab | Python 3.7+273236 ```Python hl_lines="5"237 {!> ../docs_src/arguments/help/tutorial006_an.py!}238 ```274```Python hl_lines="5"275{!> ../docs_src/arguments/help/tutorial006_an.py!}276```277240=== "Python 3.7+ non-Annotated"278////279242 !!! tip243 Prefer to use the `Annotated` version if possible.280//// tab | Python 3.7+ non-Annotated281245 ```Python hl_lines="4"246 {!> ../docs_src/arguments/help/tutorial006.py!}247 ```282/// tip283284Prefer to use the `Annotated` version if possible.285286///287288```Python hl_lines="4"289{!> ../docs_src/arguments/help/tutorial006.py!}290```291292////293294Now the generated help text will have `✨username✨` instead of `NAME`:295296<div class="termy">297
16 unmodified lines
314You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.315316If 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:317273=== "Python 3.7+"318//// tab | Python 3.7+319275 ```Python hl_lines="8 12"276 {!> ../docs_src/arguments/help/tutorial007_an.py!}277 ```320```Python hl_lines="8 12"321{!> ../docs_src/arguments/help/tutorial007_an.py!}322```323279=== "Python 3.7+ non-Annotated"324////325281 !!! tip282 Prefer to use the `Annotated` version if possible.326//// tab | Python 3.7+ non-Annotated327284 ```Python hl_lines="7 10"285 {!> ../docs_src/arguments/help/tutorial007.py!}286 ```328/// tip329330Prefer to use the `Annotated` version if possible.331332///333334```Python hl_lines="7 10"335{!> ../docs_src/arguments/help/tutorial007.py!}336```337338////339340Then, 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`.341342And next you will see other panels for the *CLI arguments* that have a custom panel set in the `rich_help_panel` parameter:343
33 unmodified lines
377If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.378379You will probably not want to do this normally, but it's possible:380329=== "Python 3.7+"381//// tab | Python 3.7+382331 ```Python hl_lines="5"332 {!> ../docs_src/arguments/help/tutorial008_an.py!}333 ```383```Python hl_lines="5"384{!> ../docs_src/arguments/help/tutorial008_an.py!}385```386335=== "Python 3.7+ non-Annotated"387////388337 !!! tip338 Prefer to use the `Annotated` version if possible.389//// tab | Python 3.7+ non-Annotated390340 ```Python hl_lines="4"341 {!> ../docs_src/arguments/help/tutorial008.py!}342 ```391/// tip392393Prefer to use the `Annotated` version if possible.394395///396397```Python hl_lines="4"398{!> ../docs_src/arguments/help/tutorial008.py!}399```400401////402403Check it:404405<div class="termy">406
10 unmodified lines
417```418419</div>420362!!! info363 Have in mind that the *CLI argument* will still show up in the first line with `Usage`.421/// info422365 But it won't show up in the main help text under the `Arguments` section.423Have in mind that the *CLI argument* will still show up in the first line with `Usage`.424425But it won't show up in the main help text under the `Arguments` section.426427///428429### Help text for *CLI arguments* in Click430431Click itself doesn't support adding help for *CLI arguments*, and it doesn't generate help for them as in the "`Arguments:`" sections in the examples above.432
12 unmodified lines
445This is also to help you create CLI programs that are ✨ awesome ✨ *by default*. With very little code.446447If you want to keep Click's convention in a **Typer** app, you can do it with the `hidden` parameter as described above.448387!!! note "Technical Details"388 To support `help` in *CLI arguments* **Typer** does a lot of internal work in its own sub-classes of Click's internal classes.449/// note | Technical Details450451To support `help` in *CLI arguments* **Typer** does a lot of internal work in its own sub-classes of Click's internal classes.452453///
modified:docs/tutorial/arguments/optional.md+33 added-15 removed
42 unmodified lines
43```Python hl_lines="5"44{!> ../docs_src/arguments/optional/tutorial001_an.py!}45```4647!!! info48 Typer added support for `Annotated` (and started recommending it) in version 0.9.0.47/// info4850 If you have an older version, you would get errors when trying to use `Annotated`.49Typer added support for `Annotated` (and started recommending it) in version 0.9.0.5052 Make sure you upgrade the Typer version to at least 0.9.0 before using `Annotated`.51If you have an older version, you would get errors when trying to use `Annotated`.5253Make sure you upgrade the Typer version to at least 0.9.0 before using `Annotated`.5455///5657Before, you had this function parameter:5859```Python60name: str
63 unmodified lines
124```125126Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).127125!!! tip126 By using `Optional` your editor will be able to know that the value *could* be `None`, and will be able to warn you if you do something assuming it is a `str` that would break if it was `None`.128/// tip129130By using `Optional` your editor will be able to know that the value *could* be `None`, and will be able to warn you if you do something assuming it is a `str` that would break if it was `None`.131132///133134Check the help:135136<div class="termy">137
11 unmodified lines
149```150151</div>152147!!! tip148 Notice that `NAME` is still a *CLI argument*, it's shown up there in the "`Usage: main.py` ...".153/// tip154150 Also notice that now `[NAME]` has brackets ("`[`" and "`]`") around (before it was just `NAME`) to denote that it's **optional**, not **required**.155Notice that `NAME` is still a *CLI argument*, it's shown up there in the "`Usage: main.py` ...".156157Also notice that now `[NAME]` has brackets ("`[`" and "`]`") around (before it was just `NAME`) to denote that it's **optional**, not **required**.158159///160161Now run it and test it:162163<div class="termy">164
10 unmodified lines
175```176177</div>178170!!! tip171 Notice that "`Camila`" here is an optional *CLI argument*, not a *CLI option*, because we didn't use something like "`--name Camila`", we just passed "`Camila`" directly to the program.179/// tip180181Notice that "`Camila`" here is an optional *CLI argument*, not a *CLI option*, because we didn't use something like "`--name Camila`", we just passed "`Camila`" directly to the program.182183///184185## Alternative (old) `typer.Argument()` as the default value186187**Typer** also supports another older alternative syntax for declaring *CLI arguments* with additional metadata.188
2 unmodified lines
191```Python hl_lines="4"192{!> ../docs_src/arguments/optional/tutorial001.py!}193```194183!!! tip184 Prefer to use the `Annotated` version if possible.195/// tip196197Prefer to use the `Annotated` version if possible.198199///200201Before, because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.202203When using `typer.Argument()` as the default value **Typer** does the same and makes it a **required** *CLI argument*.204
12 unmodified lines
217```Python218name: str = typer.Argument(default=...)219```220206!!! info207 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>.221/// info222223If 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>.224225///226227```Python hl_lines="4"228{!> ../docs_src/arguments/optional/tutorial003.py!}229```230
21 unmodified lines
modified:docs/tutorial/commands/arguments.md+12 added-6 removed
modified:docs/tutorial/commands/callback.md+12 added-6 removed
14 unmodified lines
15```1617Here we create a `callback` with a `--verbose` *CLI option*.1819!!! tip20 After getting the `--verbose` flag, we modify a global `state`, and we use it in the other commands.19/// tip2022 There are other ways to achieve the same, but this will suffice for this example.21After getting the `--verbose` flag, we modify a global `state`, and we use it in the other commands.2223There are other ways to achieve the same, but this will suffice for this example.2425///2627And as we added a docstring to the callback function, by default it will be extracted and used as the help text.2829Check it:30
150 unmodified lines
181```182183The original function `cli` would be the equivalent of a Typer callback.184182!!! note "Technical Details"183 When using Click, it converts that `cli` variable to a Click `Group` object. And then the original function no longer exists in that variable.185/// note | Technical Details186187When using Click, it converts that `cli` variable to a Click `Group` object. And then the original function no longer exists in that variable.188185 **Typer** doesn't do that, the callback function is not modified, only registered in the `typer.Typer` app. This is intentional, it's part of **Typer**'s design, to allow having editor auto completion and type checks.189**Typer** doesn't do that, the callback function is not modified, only registered in the `typer.Typer` app. This is intentional, it's part of **Typer**'s design, to allow having editor auto completion and type checks.190191///
modified:docs/tutorial/commands/context.md+5 added-2 removed
124 unmodified lines
125```126127</div>128129!!! tip130 Notice that it saves all the extra *CLI parameters* as a raw `list` of `str`, including the *CLI option* names and values, everything together.129/// tip130131Notice that it saves all the extra *CLI parameters* as a raw `list` of `str`, including the *CLI option* names and values, everything together.132133///
modified:docs/tutorial/commands/help.md+90 added-51 removed
1The same as before, you can add help for the commands in the docstrings and the *CLI options*.23And the `typer.Typer()` application receives a parameter `help` that you can pass with the main help text for your CLI program:45=== "Python 3.7+"5//// tab | Python 3.7+67 ```Python hl_lines="4 9-11 22 26-30 43 47-51 60-62"8 {!> ../docs_src/commands/help/tutorial001_an.py!}9 ```7```Python hl_lines="4 9-11 22 26-30 43 47-51 60-62"8{!> ../docs_src/commands/help/tutorial001_an.py!}9```1011=== "Python 3.7+ non-Annotated"11////1213 !!! tip14 Prefer to use the `Annotated` version if possible.13//// tab | Python 3.7+ non-Annotated1416 ```Python hl_lines="3 8-10 20 23-27 39 42-46 55-57"17 {!> ../docs_src/commands/help/tutorial001.py!}18 ```15/// tip1617Prefer to use the `Annotated` version if possible.1819///2021```Python hl_lines="3 8-10 20 23-27 39 42-46 55-57"22{!> ../docs_src/commands/help/tutorial001.py!}23```2425////2627Check it:2829<div class="termy">30
66 unmodified lines
97```9899</div>10094!!! tip95 `typer.Typer()` receives several other parameters for other things, we'll see that later.101/// tip10297 You will also see how to use "Callbacks" later, and those include a way to add this same help message in a function docstring.103`typer.Typer()` receives several other parameters for other things, we'll see that later.104105You will also see how to use "Callbacks" later, and those include a way to add this same help message in a function docstring.106107///108109## Overwrite command help110111You will probably be better adding the help text as a docstring to your functions, but if for some reason you wanted to overwrite it, you can use the `help` function argument passed to `@app.command()`:112
90 unmodified lines
203If you have **Rich** installed as described in [Printing and Colors](../printing.md){.internal-link target=_blank}, you can configure your app to enable markup text with the parameter `rich_markup_mode`.204205Then you can use more formatting in the docstrings and the `help` parameter for *CLI arguments* and *CLI options*. You will see more about it below. 👇206197!!! info198 By default, `rich_markup_mode` is `None`, which disables any rich text formatting.207/// info208209By default, `rich_markup_mode` is `None`, which disables any rich text formatting.210211///212213### Rich Markup214215If you set `rich_markup_mode="rich"` when creating the `typer.Typer()` app, you will be able to use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> in the docstring, and even in the help for the *CLI arguments* and options:216204=== "Python 3.7+"217//// tab | Python 3.7+218206 ```Python hl_lines="4 10 14-16 21 24 27"207 {!> ../docs_src/commands/help/tutorial004_an.py!}208 ```219```Python hl_lines="4 10 14-16 21 24 27"220{!> ../docs_src/commands/help/tutorial004_an.py!}221```222210=== "Python 3.7+ non-Annotated"223////224212 !!! tip213 Prefer to use the `Annotated` version if possible.225//// tab | Python 3.7+ non-Annotated226215 ```Python hl_lines="3 9 13-15 20 22 24"216 {!> ../docs_src/commands/help/tutorial004.py!}217 ```227/// tip228229Prefer to use the `Annotated` version if possible.230231///232233```Python hl_lines="3 9 13-15 20 22 24"234{!> ../docs_src/commands/help/tutorial004.py!}235```236237////238239With that, you can use <a href="https://rich.readthedocs.io/en/stable/markup.html" class="external-link" target="_blank">Rich Console Markup</a> to format the text in the docstring for the command `create`, make the word "`create`" bold and green, and even use an <a href="https://rich.readthedocs.io/en/stable/markup.html#emoji" class="external-link" target="_blank">emoji</a>.240241You can also use markup in the help for the `username` CLI Argument.242
53 unmodified lines
296### Rich Markdown297298If you set `rich_markup_mode="markdown"` when creating the `typer.Typer()` app, you will be able to use Markdown in the docstring:299280=== "Python 3.7+"300//// tab | Python 3.7+301282 ```Python hl_lines="4 9 12-20 25 27-28"283 {!> ../docs_src/commands/help/tutorial005_an.py!}284 ```302```Python hl_lines="4 9 12-20 25 27-28"303{!> ../docs_src/commands/help/tutorial005_an.py!}304```305286=== "Python 3.7+ non-Annotated"306////307288 !!! tip289 Prefer to use the `Annotated` version if possible.308//// tab | Python 3.7+ non-Annotated309291 ```Python hl_lines="3 7 9-17 22 24-25"292 {!> ../docs_src/commands/help/tutorial005.py!}293 ```310/// tip311312Prefer to use the `Annotated` version if possible.313314///315316```Python hl_lines="3 7 9-17 22 24-25"317{!> ../docs_src/commands/help/tutorial005.py!}318```319320////321322With that, you can use Markdown to format the text in the docstring for the command `create`, make the word "`create`" bold, show a list of items, and even use an <a href="https://rich.readthedocs.io/en/stable/markup.html#emoji" class="external-link" target="_blank">emoji</a>.323324And the same as before, the help text overwritten for the command `delete` can also use Markdown.325
50 unmodified lines
376```377378</div>379353!!! info354 Notice that in Markdown you cannot define colors. For colors you might prefer to use Rich markup.380/// info381382Notice that in Markdown you cannot define colors. For colors you might prefer to use Rich markup.383384///385386## Help Panels387388If you have many commands or CLI parameters, you might want to show their documentation in different panels when using the `--help` option.389
2 unmodified lines
392### Help Panels for Commands393394To set the panel for a command you can pass the argument `rich_help_panel` with the name of the panel you want to use:395366=== "Python 3.7+"396//// tab | Python 3.7+397368 ```Python hl_lines="22 30 38 46"369 {!> ../docs_src/commands/help/tutorial006.py!}370 ```398```Python hl_lines="22 30 38 46"399{!> ../docs_src/commands/help/tutorial006.py!}400```401402////403404Commands without a panel will be shown in the default panel `Commands`, and the rest will be shown in the next panels:405406<div class="termy">407
31 unmodified lines
439The same way, you can configure the panels for *CLI arguments* and *CLI options* with `rich_help_panel`.440441And of course, in the same application you can also set the `rich_help_panel` for commands.442411=== "Python 3.7+"443//// tab | Python 3.7+444413 ```Python hl_lines="15 21 27 37"414 {!> ../docs_src/commands/help/tutorial007_an.py!}415 ```445```Python hl_lines="15 21 27 37"446{!> ../docs_src/commands/help/tutorial007_an.py!}447```448417=== "Python 3.7+ non-Annotated"449////450419 !!! tip420 Prefer to use the `Annotated` version if possible.451//// tab | Python 3.7+ non-Annotated452422 ```Python hl_lines="12 16 21 30"423 {!> ../docs_src/commands/help/tutorial007.py!}424 ```453/// tip454455Prefer to use the `Annotated` version if possible.456457///458459```Python hl_lines="12 16 21 30"460{!> ../docs_src/commands/help/tutorial007.py!}461```462463////464465Then if you run the application you will see all the *CLI parameters* in their respective panels.466467* First the ***CLI arguments*** that don't have a panel name set in a **default** one named "`Arguments`".468* Next the ***CLI arguments*** with a **custom panel**. In this example named "`Secondary Arguments`".
103 unmodified lines
modified:docs/tutorial/commands/index.md+36 added-18 removed
26 unmodified lines
27Another command of `git` is `git pull`, it also has some *CLI parameters*.2829It's like if the same big program `git` had several small programs inside.3031!!! tip32 A command looks the same as a *CLI argument*, it's just some name without a preceding `--`. But commands have a predefined name, and are used to group different sets of functionalities into the same CLI application.31/// tip3233A command looks the same as a *CLI argument*, it's just some name without a preceding `--`. But commands have a predefined name, and are used to group different sets of functionalities into the same CLI application.3435///3637## Command or subcommand3839It's common to call a CLI program a "command".40
28 unmodified lines
69* Create a new `typer.Typer()` "application".70* Create a new "`command`" with your function.71* Call the same "application" as if it was a function with "`app()`".7270!!! info "`@decorator` Info"71 That `@something` syntax in Python is called a "decorator".73/// info | `@decorator` Info7473 You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).75That `@something` syntax in Python is called a "decorator".7675 A "decorator" takes the function below and does something with it.77You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).7877 In our case, this decorator tells **Typer** that the function below is a "`command`".79A "decorator" takes the function below and does something with it.8081In our case, this decorator tells **Typer** that the function below is a "`command`".8283///8485Both ways, with `typer.run()` and creating the explicit application, achieve almost the same.8681!!! tip82 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.87/// tip8884 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.89If 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.9091You might want to do that later when your app needs the extra features, but if it doesn't need them yet, that's fine.9293///9495If you run the second example, with the explicit `app`, it works exactly the same:9697<div class="termy">98
117 unmodified lines
216</div>217218Notice that the help text now shows the 2 commands: `create` and `delete`.219211!!! tip212 By default, the names of the commands are generated from the function name.220/// tip221222By default, the names of the commands are generated from the function name.223224///225226## Show the help message if no command is given227228By default, we need to specify `--help` to get the command's help page.229
28 unmodified lines
258## Click Group259260If you come from Click, a `typer.Typer` app with subcommands is more or less the equivalent of a <a href="https://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands" class="external-link" target="_blank">Click Group</a>.261250!!! note "Technical Details"251 A `typer.Typer` app is *not* a Click Group, but it provides the equivalent functionality. And it creates a Click Group when calling it.262/// note | Technical Details263253 It is not directly a Group because **Typer** doesn't modify the functions in your code to convert them to another type of object, it only registers them.264A `typer.Typer` app is *not* a Click Group, but it provides the equivalent functionality. And it creates a Click Group when calling it.265266It is not directly a Group because **Typer** doesn't modify the functions in your code to convert them to another type of object, it only registers them.267268///269270## Decorator Technical Details271272When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.273274But Typer doesn't modify that function itself, the function is left as is.275276That means that if your function is simple enough that you could create it without using `typer.Option()` or `typer.Argument()`, you could use the same function for a **Typer** application and a **FastAPI** application putting both decorators on top, or similar tricks.277263!!! note "Click Technical Details"264 This behavior is a design difference with Click.278/// note | Click Technical Details279280This behavior is a design difference with Click.281266 In Click, when you add a `@click.command()` decorator it actually modifies the function underneath and replaces it with an object.282In Click, when you add a `@click.command()` decorator it actually modifies the function underneath and replaces it with an object.283284///
modified:docs/tutorial/commands/one-or-multiple.md+5 added-2 removed
33 unmodified lines
34```3536</div>3738!!! tip39 Notice that it doesn't show a command `main`, even though the function name is `main`.38/// tip3940Notice that it doesn't show a command `main`, even though the function name is `main`.4142///4344But if you add multiple commands, **Typer** will create one *CLI command* for each one of them:4546```Python hl_lines="6 11"47{!../docs_src/commands/index/tutorial002.py!}
107 unmodified lines
modified:docs/tutorial/commands/options.md+22 added-12 removed
1Commands can also have their own *CLI options*.23In fact, each command can have different *CLI arguments* and *CLI options*:45=== "Python 3.7+"5//// tab | Python 3.7+67 ```Python hl_lines="8 14-17 27-29 38"8 {!> ../docs_src/commands/options/tutorial001_an.py!}9 ```7```Python hl_lines="8 14-17 27-29 38"8{!> ../docs_src/commands/options/tutorial001_an.py!}9```1011=== "Python 3.7+ non-Annotated"11////1213 !!! tip14 Prefer to use the `Annotated` version if possible.13//// tab | Python 3.7+ non-Annotated1416 ```Python hl_lines="7 13-14 24 33"17 {!> ../docs_src/commands/options/tutorial001.py!}18 ```15/// tip1617Prefer to use the `Annotated` version if possible.1819///2021```Python hl_lines="7 13-14 24 33"22{!> ../docs_src/commands/options/tutorial001.py!}23```2425////2627Here we have multiple commands, with different *CLI parameters*:2829* `create`:30 * `username`: a *CLI argument*.
26 unmodified lines
57```5859</div>6054!!! tip55 Check the command `delete-all`, by default command names are generated from the function name, replacing `_` with `-`.61/// tip6263Check the command `delete-all`, by default command names are generated from the function name, replacing `_` with `-`.6465///6667Test it:6869<div class="termy">70
47 unmodified lines
modified:docs/tutorial/multiple-values/arguments-with-multiple-values.md+27 added-14 removed
19 unmodified lines
20```2122</div>2324!!! tip25 We also declared a final *CLI argument* `celebration`, and it's correctly used even if we pass an arbitrary number of `files` first.24/// tip2527!!! info28 A `List` can only be used in the last command (if there are subcommands), as this will take anything to the right and assume it's part of the expected *CLI arguments*.26We also declared a final *CLI argument* `celebration`, and it's correctly used even if we pass an arbitrary number of `files` first.2728///2930/// info3132A `List` can only be used in the last command (if there are subcommands), as this will take anything to the right and assume it's part of the expected *CLI arguments*.3334///3536## *CLI arguments* with tuples3738If you want a specific number of values and types, you can use a tuple, and it can even have default values:3934=== "Python 3.7+"40//// tab | Python 3.7+4136 ```Python hl_lines="8-10"37 {!> ../docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py!}38 ```42```Python hl_lines="8-10"43{!> ../docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py!}44```4540=== "Python 3.7+ non-Annotated"46////4742 !!! tip43 Prefer to use the `Annotated` version if possible.48//// tab | Python 3.7+ non-Annotated4945 ```Python hl_lines="7-8"46 {!> ../docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py!}47 ```50/// tip5152Prefer to use the `Annotated` version if possible.5354///5556```Python hl_lines="7-8"57{!> ../docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py!}58```5960////6162Check it:6364<div class="termy">65
33 unmodified lines
modified:docs/tutorial/multiple-values/multiple-options.md+34 added-20 removed
2 unmodified lines
3For example, let's say you want to accept several users in a single execution.45For this, use the standard Python `typing.List` to declare it as a `list` of `str`:67=== "Python 3.7+"7//// tab | Python 3.7+89 ```Python hl_lines="1 7"10 {!> ../docs_src/multiple_values/multiple_options/tutorial001_an.py!}11 ```9```Python hl_lines="1 7"10{!> ../docs_src/multiple_values/multiple_options/tutorial001_an.py!}11```1213=== "Python 3.7+ non-Annotated"13////1415 !!! tip16 Prefer to use the `Annotated` version if possible.15//// tab | Python 3.7+ non-Annotated1618 ```Python hl_lines="1 6"19 {!> ../docs_src/multiple_values/multiple_options/tutorial001.py!}20 ```17/// tip1819Prefer to use the `Annotated` version if possible.2021///2223```Python hl_lines="1 6"24{!> ../docs_src/multiple_values/multiple_options/tutorial001.py!}25```2627////2829You will receive the values as you declared them, as a `list` of `str`.3031Check it:32
24 unmodified lines
57## Multiple `float`5859The same way, you can use other types and they will be converted by **Typer** to their declared type:6054=== "Python 3.7+"61//// tab | Python 3.7+6256 ```Python hl_lines="7"57 {!> ../docs_src/multiple_values/multiple_options/tutorial002_an.py!}58 ```63```Python hl_lines="7"64{!> ../docs_src/multiple_values/multiple_options/tutorial002_an.py!}65```6660=== "Python 3.7+ non-Annotated"67////6862 !!! tip63 Prefer to use the `Annotated` version if possible.69//// tab | Python 3.7+ non-Annotated7065 ```Python hl_lines="6"66 {!> ../docs_src/multiple_values/multiple_options/tutorial002.py!}67 ```71/// tip7273Prefer to use the `Annotated` version if possible.7475///7677```Python hl_lines="6"78{!> ../docs_src/multiple_values/multiple_options/tutorial002.py!}79```8081////8283Check it:8485<div class="termy">86
17 unmodified lines
modified:docs/tutorial/multiple-values/options-with-multiple-values.md+23 added-13 removed
2 unmodified lines
3You can set the number of values and types to anything you want, but it has to be a fixed number of values.45For this, use the standard Python `typing.Tuple`:67=== "Python 3.7+"7//// tab | Python 3.7+89 ```Python hl_lines="1 7"10 {!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py!}11 ```9```Python hl_lines="1 7"10{!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py!}11```1213=== "Python 3.7+ non-Annotated"13////1415 !!! tip16 Prefer to use the `Annotated` version if possible.15//// tab | Python 3.7+ non-Annotated1618 ```Python hl_lines="1 6"19 {!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001.py!}20 ```17/// tip1819Prefer to use the `Annotated` version if possible.2021///2223```Python hl_lines="1 6"24{!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001.py!}25```2627////2829Each of the internal types defines the type of each value in the tuple.3031So:32
32 unmodified lines
65coins = user[1]66is_wizard = user[2]67```6862!!! tip63 Notice that the default is a tuple with `(None, None, None)`.69/// tip7065 You cannot simply use `None` here as the default because <a href="https://github.com/pallets/click/issues/472" class="external-link" target="_blank">Click doesn't support it</a>.71Notice that the default is a tuple with `(None, None, None)`.7273You cannot simply use `None` here as the default because <a href="https://github.com/pallets/click/issues/472" class="external-link" target="_blank">Click doesn't support it</a>.7475///7677## Check it7879Now let's see how this works in the terminal:80
31 unmodified lines
modified:docs/tutorial/options/callback-and-context.md+68 added-40 removed
4 unmodified lines
5## Validate *CLI parameters*67For example, you could do some validation before the rest of the code is executed.89=== "Python 3.7+"9//// tab | Python 3.7+1011 ```Python hl_lines="7-10 13"12 {!> ../docs_src/options/callback/tutorial001_an.py!}13 ```11```Python hl_lines="7-10 13"12{!> ../docs_src/options/callback/tutorial001_an.py!}13```1415=== "Python 3.7+ non-Annotated"15////1617 !!! tip18 Prefer to use the `Annotated` version if possible.17//// tab | Python 3.7+ non-Annotated1820 ```Python hl_lines="6-9 12"21 {!> ../docs_src/options/callback/tutorial001.py!}22 ```19/// tip2021Prefer to use the `Annotated` version if possible.2223///2425```Python hl_lines="6-9 12"26{!> ../docs_src/options/callback/tutorial001.py!}27```2829////3031Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.3233The function receives the value from the command line. It can do anything with it, and then return the value.34
76 unmodified lines
111### Breaking completion in a callback112113Let's say that when the callback is running, we want to show a message saying that it's validating the name:114108=== "Python 3.7+"115//// tab | Python 3.7+116110 ```Python hl_lines="8"111 {!> ../docs_src/options/callback/tutorial002_an.py!}112 ```117```Python hl_lines="8"118{!> ../docs_src/options/callback/tutorial002_an.py!}119```120114=== "Python 3.7+ non-Annotated"121////122116 !!! tip117 Prefer to use the `Annotated` version if possible.123//// tab | Python 3.7+ non-Annotated124119 ```Python hl_lines="7"120 {!> ../docs_src/options/callback/tutorial002.py!}121 ```125/// tip126127Prefer to use the `Annotated` version if possible.128129///130131```Python hl_lines="7"132{!> ../docs_src/options/callback/tutorial002.py!}133```134135////136137And 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.138139It will look something like:140
25 unmodified lines
166But you can access the context by declaring a function parameter of type `typer.Context`.167168The "context" has some additional data about the current execution of your program:169156=== "Python 3.7+"170//// tab | Python 3.7+171158 ```Python hl_lines="7-9"159 {!> ../docs_src/options/callback/tutorial003_an.py!}160 ```172```Python hl_lines="7-9"173{!> ../docs_src/options/callback/tutorial003_an.py!}174```175162=== "Python 3.7+ non-Annotated"176////177164 !!! tip165 Prefer to use the `Annotated` version if possible.178//// tab | Python 3.7+ non-Annotated179167 ```Python hl_lines="6-8"168 {!> ../docs_src/options/callback/tutorial003.py!}169 ```180/// tip181182Prefer to use the `Annotated` version if possible.183184///185186```Python hl_lines="6-8"187{!> ../docs_src/options/callback/tutorial003.py!}188```189190////191192The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.193194But it will be `False` when calling the program normally. So you can continue the execution of your previous code.195
22 unmodified lines
218## Using the `CallbackParam` object219220The 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.221201=== "Python 3.7+"222//// tab | Python 3.7+223203 ```Python hl_lines="7 10"204 {!> ../docs_src/options/callback/tutorial004_an.py!}205 ```224```Python hl_lines="7 10"225{!> ../docs_src/options/callback/tutorial004_an.py!}226```227207=== "Python 3.7+ non-Annotated"228////229209 !!! tip210 Prefer to use the `Annotated` version if possible.230//// tab | Python 3.7+ non-Annotated231212 ```Python hl_lines="6 9"213 {!> ../docs_src/options/callback/tutorial004.py!}214 ```232/// tip233234Prefer to use the `Annotated` version if possible.235236///237238```Python hl_lines="6 9"239{!> ../docs_src/options/callback/tutorial004.py!}240```241242////243244It's probably not very common, but you could do it if you need it.245246For 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.247
42 unmodified lines
modified:docs/tutorial/options/help.md+74 added-43 removed
1You already saw how to add a help text for *CLI arguments* with the `help` parameter.23Let's now do the same for *CLI options*:45=== "Python 3.7+"5//// tab | Python 3.7+67 ```Python hl_lines="7-8"8 {!> ../docs_src/options/help/tutorial001_an.py!}9 ```7```Python hl_lines="7-8"8{!> ../docs_src/options/help/tutorial001_an.py!}9```1011=== "Python 3.7+ non-Annotated"11////1213 !!! tip14 Prefer to use the `Annotated` version if possible.13//// tab | Python 3.7+ non-Annotated1416 ```Python hl_lines="6-7"17 {!> ../docs_src/options/help/tutorial001.py!}18 ```15/// tip1617Prefer to use the `Annotated` version if possible.1819///2021```Python hl_lines="6-7"22{!> ../docs_src/options/help/tutorial001.py!}23```2425////2627The same way as with `typer.Argument()`, we can put `typer.Option()` inside of `Annotated`.2829We can then pass the `help` keyword parameter:30
42 unmodified lines
73The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.7475If 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*:7670=== "Python 3.7+"77//// tab | Python 3.7+7872 ```Python hl_lines="11 17"73 {!> ../docs_src/options/help/tutorial002_an.py!}74 ```79```Python hl_lines="11 17"80{!> ../docs_src/options/help/tutorial002_an.py!}81```8276=== "Python 3.7+ non-Annotated"83////8478 !!! tip79 Prefer to use the `Annotated` version if possible.85//// tab | Python 3.7+ non-Annotated8681 ```Python hl_lines="8 11"82 {!> ../docs_src/options/help/tutorial002.py!}83 ```87/// tip8889Prefer to use the `Annotated` version if possible.9091///9293```Python hl_lines="8 11"94{!> ../docs_src/options/help/tutorial002.py!}95```9697////9899Now, 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`.100101And below you will see other panels for the *CLI options* that have a custom panel set in the `rich_help_panel` parameter:102
36 unmodified lines
139## Hide default from help140141You can tell Typer to not show the default value in the help text with `show_default=False`:142129=== "Python 3.7+"143//// tab | Python 3.7+144131 ```Python hl_lines="5"132 {!> ../docs_src/options/help/tutorial003_an.py!}133 ```145```Python hl_lines="5"146{!> ../docs_src/options/help/tutorial003_an.py!}147```148135=== "Python 3.7+ non-Annotated"149////150137 !!! tip138 Prefer to use the `Annotated` version if possible.151//// tab | Python 3.7+ non-Annotated152140 ```Python hl_lines="4"141 {!> ../docs_src/options/help/tutorial003.py!}142 ```153/// tip154155Prefer to use the `Annotated` version if possible.156157///158159```Python hl_lines="4"160{!> ../docs_src/options/help/tutorial003.py!}161```162163////164165And it will no longer show the default value in the help text:166167<div class="termy">168
15 unmodified lines
184```185186</div>187167!!! note "Technical Details"168 In Click applications the default values are hidden by default. 🙈188/// note | Technical Details189170 In **Typer** these default values are shown by default. 👀190In Click applications the default values are hidden by default. 🙈191192In **Typer** these default values are shown by default. 👀193194///195196## Custom default string197198You 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:199176=== "Python 3.7+"200//// tab | Python 3.7+201178 ```Python hl_lines="7"179 {!> ../docs_src/options/help/tutorial004_an.py!}180 ```202```Python hl_lines="7"203{!> ../docs_src/options/help/tutorial004_an.py!}204```205182=== "Python 3.7+ non-Annotated"206////207184 !!! tip185 Prefer to use the `Annotated` version if possible.208//// tab | Python 3.7+ non-Annotated209187 ```Python hl_lines="6"188 {!> ../docs_src/options/help/tutorial004.py!}189 ```210/// tip211212Prefer to use the `Annotated` version if possible.213214///215216```Python hl_lines="6"217{!> ../docs_src/options/help/tutorial004.py!}218```219220////221222And it will be used in the help text:223224<div class="termy">225
18 unmodified lines
modified:docs/tutorial/options/name.md+106 added-62 removed
24 unmodified lines
25Let's say the function parameter name is `user_name` as above, but you want the *CLI option* to be just `--name`.2627You can pass the *CLI option* name that you want to have in the following positional argument passed to `typer.Option()`:2829=== "Python 3.7+"29//// tab | Python 3.7+3031 ```Python hl_lines="5"32 {!> ../docs_src/options/name/tutorial001_an.py!}33 ```31```Python hl_lines="5"32{!> ../docs_src/options/name/tutorial001_an.py!}33```3435 Here you are passing the string `"--name"` as the first positional argument to `typer.Option()`.35Here you are passing the string `"--name"` as the first positional argument to `typer.Option()`.3637=== "Python 3.7+ non-Annotated"37////3839 !!! tip40 Prefer to use the `Annotated` version if possible.39//// tab | Python 3.7+ non-Annotated4042 ```Python hl_lines="4"43 {!> ../docs_src/options/name/tutorial001.py!}44 ```41/// tip4246 Here you are passing the string `"--name"` as the second positional argument to `typer.Option()`, as the first argument is `...` to mark it as required.43Prefer to use the `Annotated` version if possible.4448!!! info49 "<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.45///4651 For example `show_default=True` is a keyword argument. "`show_default`" is the keyword.47```Python hl_lines="4"48{!> ../docs_src/options/name/tutorial001.py!}49```5053 But in `"--name"` there's no `option_name="--name"` or something similar, it's just the string value `"--name"` that goes in `typer.Option()`.51Here you are passing the string `"--name"` as the second positional argument to `typer.Option()`, as the first argument is `...` to mark it as required.5255 That's a "positional argument" in a function.53////5455/// info5657"<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.5859For example `show_default=True` is a keyword argument. "`show_default`" is the keyword.6061But in `"--name"` there's no `option_name="--name"` or something similar, it's just the string value `"--name"` that goes in `typer.Option()`.6263That's a "positional argument" in a function.6465///6667Check it:6869<div class="termy">70
123 unmodified lines
194In **Typer** you can also define *CLI option* short names the same way you can customize the long names.195196You can pass *positional* arguments to `typer.Option()` to define the *CLI option* name(s).197188!!! tip189 Remember the *positional* function arguments are those that don't have a keyword.198/// tip199191 All the other function arguments/parameters you pass to `typer.Option()` like `prompt=True` and `help="This option blah, blah"` require the keyword.200Remember the *positional* function arguments are those that don't have a keyword.201202All the other function arguments/parameters you pass to `typer.Option()` like `prompt=True` and `help="This option blah, blah"` require the keyword.203204///205206You can overwrite the *CLI option* name to use as in the previous example, but you can also declare extra alternatives, including short names.207208For example, extending the previous example, let's add a *CLI option* short name `-n`:209197=== "Python 3.7+"210//// tab | Python 3.7+211199 ```Python hl_lines="5"200 {!> ../docs_src/options/name/tutorial002_an.py!}201 ```212```Python hl_lines="5"213{!> ../docs_src/options/name/tutorial002_an.py!}214```215203=== "Python 3.7+ non-Annotated"216////217205 !!! tip206 Prefer to use the `Annotated` version if possible.218//// tab | Python 3.7+ non-Annotated219208 ```Python hl_lines="4"209 {!> ../docs_src/options/name/tutorial002.py!}210 ```220/// tip221222Prefer to use the `Annotated` version if possible.223224///225226```Python hl_lines="4"227{!> ../docs_src/options/name/tutorial002.py!}228```229230////231232Here 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`.233234Check it:235
21 unmodified lines
257### *CLI option* only short name258259If 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.260241=== "Python 3.7+"261//// tab | Python 3.7+262243 ```Python hl_lines="5"244 {!> ../docs_src/options/name/tutorial003_an.py!}245 ```263```Python hl_lines="5"264{!> ../docs_src/options/name/tutorial003_an.py!}265```266247=== "Python 3.7+ non-Annotated"267////268249 !!! tip250 Prefer to use the `Annotated` version if possible.269//// tab | Python 3.7+ non-Annotated270252 ```Python hl_lines="4"253 {!> ../docs_src/options/name/tutorial003.py!}254 ```271/// tip272273Prefer to use the `Annotated` version if possible.274275///276277```Python hl_lines="4"278{!> ../docs_src/options/name/tutorial003.py!}279```280281////282283Check it:284285<div class="termy">286
18 unmodified lines
305### *CLI option* short name and default306307Continuing 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:308282=== "Python 3.7+"309//// tab | Python 3.7+310284 ```Python hl_lines="5"285 {!> ../docs_src/options/name/tutorial004_an.py!}286 ```311```Python hl_lines="5"312{!> ../docs_src/options/name/tutorial004_an.py!}313```314288=== "Python 3.7+ non-Annotated"315////316290 !!! tip291 Prefer to use the `Annotated` version if possible.317//// tab | Python 3.7+ non-Annotated318293 ```Python hl_lines="4"294 {!> ../docs_src/options/name/tutorial004.py!}295 ```319/// tip320321Prefer to use the `Annotated` version if possible.322323///324325```Python hl_lines="4"326{!> ../docs_src/options/name/tutorial004.py!}327```328329////330331Check it:332333<div class="termy">334
24 unmodified lines
359You can create multiple short names and use them together.360361You don't have to do anything special for it to work (apart from declaring those short versions):362329=== "Python 3.7+"363//// tab | Python 3.7+364331 ```Python hl_lines="6-7"332 {!> ../docs_src/options/name/tutorial005_an.py!}333 ```365```Python hl_lines="6-7"366{!> ../docs_src/options/name/tutorial005_an.py!}367```368335=== "Python 3.7+ non-Annotated"369////370337 !!! tip338 Prefer to use the `Annotated` version if possible.371//// tab | Python 3.7+ non-Annotated372340 ```Python hl_lines="5-6"341 {!> ../docs_src/options/name/tutorial005.py!}342 ```373/// tip374344!!! tip345 Notice that, again, we are declaring the long and short version of the *CLI option* names.375Prefer to use the `Annotated` version if possible.376377///378379```Python hl_lines="5-6"380{!> ../docs_src/options/name/tutorial005.py!}381```382383////384385/// tip386387Notice that, again, we are declaring the long and short version of the *CLI option* names.388389///390391Check it:392393<div class="termy">394
25 unmodified lines
modified:docs/tutorial/options/password.md+34 added-20 removed
1Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:23=== "Python 3.7+"3//// tab | Python 3.7+45 ```Python hl_lines="7"6 {!> ../docs_src/options/password/tutorial001_an.py!}7 ```5```Python hl_lines="7"6{!> ../docs_src/options/password/tutorial001_an.py!}7```89=== "Python 3.7+ non-Annotated"9////1011 !!! tip12 Prefer to use the `Annotated` version if possible.11//// tab | Python 3.7+ non-Annotated1214 ```Python hl_lines="5"15 {!> ../docs_src/options/password/tutorial001.py!}16 ```13/// tip1415Prefer to use the `Annotated` version if possible.1617///1819```Python hl_lines="5"20{!> ../docs_src/options/password/tutorial001.py!}21```2223////2425And the CLI program will ask for confirmation:2627<div class="termy">28
18 unmodified lines
47You can achieve the same using `hide_input=True`.4849And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:5044=== "Python 3.7+"51//// tab | Python 3.7+5246 ```Python hl_lines="8"47 {!> ../docs_src/options/password/tutorial002_an.py!}48 ```53```Python hl_lines="8"54{!> ../docs_src/options/password/tutorial002_an.py!}55```5650=== "Python 3.7+ non-Annotated"57////5852 !!! tip53 Prefer to use the `Annotated` version if possible.59//// tab | Python 3.7+ non-Annotated6055 ```Python hl_lines="6-8"56 {!> ../docs_src/options/password/tutorial002.py!}57 ```61/// tip6263Prefer to use the `Annotated` version if possible.6465///6667```Python hl_lines="6-8"68{!> ../docs_src/options/password/tutorial002.py!}69```7071////7273Check it:7475<div class="termy">76
13 unmodified lines
modified:docs/tutorial/options/prompt.md+51 added-30 removed
1It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:23=== "Python 3.7+"3//// tab | Python 3.7+45 ```Python hl_lines="5"6 {!> ../docs_src/options/prompt/tutorial001_an.py!}7 ```5```Python hl_lines="5"6{!> ../docs_src/options/prompt/tutorial001_an.py!}7```89=== "Python 3.7+ non-Annotated"9////1011 !!! tip12 Prefer to use the `Annotated` version if possible.11//// tab | Python 3.7+ non-Annotated1214 ```Python hl_lines="4"15 {!> ../docs_src/options/prompt/tutorial001.py!}16 ```13/// tip1415Prefer to use the `Annotated` version if possible.1617///1819```Python hl_lines="4"20{!> ../docs_src/options/prompt/tutorial001.py!}21```2223////2425And then your program will ask the user for it in the terminal:2627<div class="termy">28
12 unmodified lines
41## Customize the prompt4243You can also set a custom prompt, passing the string that you want to use instead of just `True`:4438=== "Python 3.7+"45//// tab | Python 3.7+4640 ```Python hl_lines="7"41 {!> ../docs_src/options/prompt/tutorial002_an.py!}42 ```47```Python hl_lines="7"48{!> ../docs_src/options/prompt/tutorial002_an.py!}49```5044=== "Python 3.7+ non-Annotated"51////5246 !!! tip47 Prefer to use the `Annotated` version if possible.53//// tab | Python 3.7+ non-Annotated5449 ```Python hl_lines="5"50 {!> ../docs_src/options/prompt/tutorial002.py!}51 ```55/// tip5657Prefer to use the `Annotated` version if possible.5859///6061```Python hl_lines="5"62{!> ../docs_src/options/prompt/tutorial002.py!}63```6465////6667And then your program will ask for it using with your custom prompt:6869<div class="termy">70
16 unmodified lines
87You can do it passing the parameter `confirmation_prompt=True`.8889Let's say it's a CLI app to delete a project:9077=== "Python 3.7+"91//// tab | Python 3.7+9279 ```Python hl_lines="6"80 {!> ../docs_src/options/prompt/tutorial003_an.py!}81 ```93```Python hl_lines="6"94{!> ../docs_src/options/prompt/tutorial003_an.py!}95```9683=== "Python 3.7+ non-Annotated"97////9885 !!! tip86 Prefer to use the `Annotated` version if possible.99//// tab | Python 3.7+ non-Annotated10088 ```Python hl_lines="4"89 {!> ../docs_src/options/prompt/tutorial003.py!}90 ```101/// tip102103Prefer to use the `Annotated` version if possible.104105///106107```Python hl_lines="4"108{!> ../docs_src/options/prompt/tutorial003.py!}109```110111////112113And it will prompt the user for a value and then for the confirmation:114115<div class="termy">116
26 unmodified lines
modified:docs/tutorial/options/required.md+28 added-16 removed
9 unmodified lines
10To make a *CLI option* required, you can put `typer.Option()` inside of `Annotated` and leave the parameter without a default value.1112Let's make `--lastname` a required *CLI option*:1314=== "Python 3.7+"14//// tab | Python 3.7+1516 ```Python hl_lines="5"17 {!> ../docs_src/options/required/tutorial001_an.py!}18 ```16```Python hl_lines="5"17{!> ../docs_src/options/required/tutorial001_an.py!}18```1920////2122The 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.2322=== "Python 3.7+ non-Annotated"24//// tab | Python 3.7+ non-Annotated2524 ```Python hl_lines="4"25 {!> ../docs_src/options/required/tutorial001.py!}26 ```26```Python hl_lines="4"27{!> ../docs_src/options/required/tutorial001.py!}28```2930////3132Or you can explictily pass `...` to `typer.Option(default=...)`:3330=== "Python 3.7+ non-Annotated"34//// tab | Python 3.7+ non-Annotated3532 ```Python hl_lines="4"33 {!> ../docs_src/options/required/tutorial002.py!}34 ```36```Python hl_lines="4"37{!> ../docs_src/options/required/tutorial002.py!}38```3936!!! info37 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>.40////4142/// info4344If 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>.4546///4748That will tell **Typer** that it's still a *CLI option*, but it doesn't have a default value, and it's required.4941!!! tip42 Again, prefer to use the `Annotated` version if possible. That way your code will mean the same in standard Python and in **Typer**.50/// tip5152Again, prefer to use the `Annotated` version if possible. That way your code will mean the same in standard Python and in **Typer**.5354///5556And test it:5758<div class="termy">59
28 unmodified lines
modified:docs/tutorial/options/version.md+71 added-38 removed
4 unmodified lines
5## First version of `--version`67Let's see a first version of how it could look like:89=== "Python 3.7+"9//// tab | Python 3.7+1011 ```Python hl_lines="9-12 17-19"12 {!> ../docs_src/options/version/tutorial001_an.py!}13 ```11```Python hl_lines="9-12 17-19"12{!> ../docs_src/options/version/tutorial001_an.py!}13```1415=== "Python 3.7+ non-Annotated"15////1617 !!! tip18 Prefer to use the `Annotated` version if possible.17//// tab | Python 3.7+ non-Annotated1820 ```Python hl_lines="8-11 16-18"21 {!> ../docs_src/options/version/tutorial001.py!}22 ```19/// tip2024!!! tip25 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.21Prefer to use the `Annotated` version if possible.2223///2425```Python hl_lines="8-11 16-18"26{!> ../docs_src/options/version/tutorial001.py!}27```2829////3031/// tip3233Notice 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.3435///3637If the `--version` *CLI option* is passed, we get a value `True` in the callback.3839Then we can print the version and raise `typer.Exit()` to make sure the program is terminated before anything else is executed.40
33 unmodified lines
74## Previous parameters and `is_eager`7576But 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:7768=== "Python 3.7+"78//// tab | Python 3.7+7970 ```Python hl_lines="15-17 22-24"71 {!> ../docs_src/options/version/tutorial002_an.py!}72 ```80```Python hl_lines="15-17 22-24"81{!> ../docs_src/options/version/tutorial002_an.py!}82```8374=== "Python 3.7+ non-Annotated"84////8576 !!! tip77 Prefer to use the `Annotated` version if possible.86//// tab | Python 3.7+ non-Annotated8779 ```Python hl_lines="14-16 21-23"80 {!> ../docs_src/options/version/tutorial002.py!}81 ```88/// tip8990Prefer to use the `Annotated` version if possible.9192///9394```Python hl_lines="14-16 21-23"95{!> ../docs_src/options/version/tutorial002.py!}96```9798////99100Then 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:101102<div class="termy">103
5 unmodified lines
109```110111</div>11296!!! tip97 We don't have to check for `ctx.resilient_parsing` in the `name_callback()` for completion to work, because we are not using `typer.echo()`, instead we are raising a `typer.BadParameter`.113/// tip11499!!! note "Technical Details"100 `typer.BadParameter` prints the error to "standard error", not to "standard output", and because the completion system only reads from "standard output", it won't break completion.115We don't have to check for `ctx.resilient_parsing` in the `name_callback()` for completion to work, because we are not using `typer.echo()`, instead we are raising a `typer.BadParameter`.116102!!! info103 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](../printing.md#standard-output-and-standard-error){.internal-link target=_blank}.117///118119/// note | Technical Details120121`typer.BadParameter` prints the error to "standard error", not to "standard output", and because the completion system only reads from "standard output", it won't break completion.122123///124125/// info126127If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](../printing.md#standard-output-and-standard-error){.internal-link target=_blank}.128129///130131### Fix with `is_eager`132133For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.134135That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:136111=== "Python 3.7+"137//// tab | Python 3.7+138113 ```Python hl_lines="23-26"114 {!> ../docs_src/options/version/tutorial003_an.py!}115 ```139```Python hl_lines="23-26"140{!> ../docs_src/options/version/tutorial003_an.py!}141```142117=== "Python 3.7+ non-Annotated"143////144119 !!! tip120 Prefer to use the `Annotated` version if possible.145//// tab | Python 3.7+ non-Annotated146122 ```Python hl_lines="22-24"123 {!> ../docs_src/options/version/tutorial003.py!}124 ```147/// tip148149Prefer to use the `Annotated` version if possible.150151///152153```Python hl_lines="22-24"154{!> ../docs_src/options/version/tutorial003.py!}155```156157////158159Check it:160161<div class="termy">162
8 unmodified lines
modified:docs/tutorial/parameter-types/bool.md+74 added-43 removed
6 unmodified lines
7Let's say that we want a `--force` *CLI option* only, we want to discard `--no-force`.89We can do that by specifying the exact name we want:1011=== "Python 3.7+"11//// tab | Python 3.7+1213 ```Python hl_lines="5"14 {!> ../docs_src/parameter_types/bool/tutorial001_an.py!}15 ```13```Python hl_lines="5"14{!> ../docs_src/parameter_types/bool/tutorial001_an.py!}15```1617=== "Python 3.7+ non-Annotated"17////1819 !!! tip20 Prefer to use the `Annotated` version if possible.19//// tab | Python 3.7+ non-Annotated2022 ```Python hl_lines="4"23 {!> ../docs_src/parameter_types/bool/tutorial001.py!}24 ```21/// tip2223Prefer to use the `Annotated` version if possible.2425///2627```Python hl_lines="4"28{!> ../docs_src/parameter_types/bool/tutorial001.py!}29```3031////3233Now there's only a `--force` *CLI option*:3435<div class="termy">36
38 unmodified lines
75We might want to instead have `--accept` and `--reject`.7677We can do that by passing a single `str` with the 2 names for the `bool` *CLI option* separated by `/`:7872=== "Python 3.7+"79//// tab | Python 3.7+8074 ```Python hl_lines="7"75 {!> ../docs_src/parameter_types/bool/tutorial002_an.py!}76 ```81```Python hl_lines="7"82{!> ../docs_src/parameter_types/bool/tutorial002_an.py!}83```8478=== "Python 3.7+ non-Annotated"85////8680 !!! tip81 Prefer to use the `Annotated` version if possible.87//// tab | Python 3.7+ non-Annotated8883 ```Python hl_lines="6"84 {!> ../docs_src/parameter_types/bool/tutorial002.py!}85 ```89/// tip9091Prefer to use the `Annotated` version if possible.9293///9495```Python hl_lines="6"96{!> ../docs_src/parameter_types/bool/tutorial002.py!}97```9899////100101Check it:102103<div class="termy">104
31 unmodified lines
136The same way, you can declare short versions of the names for these *CLI options*.137138For example, let's say we want `-f` for `--force` and `-F` for `--no-force`:139126=== "Python 3.7+"140//// tab | Python 3.7+141128 ```Python hl_lines="5"129 {!> ../docs_src/parameter_types/bool/tutorial003_an.py!}130 ```142```Python hl_lines="5"143{!> ../docs_src/parameter_types/bool/tutorial003_an.py!}144```145132=== "Python 3.7+ non-Annotated"146////147134 !!! tip135 Prefer to use the `Annotated` version if possible.148//// tab | Python 3.7+ non-Annotated149137 ```Python hl_lines="4"138 {!> ../docs_src/parameter_types/bool/tutorial003.py!}139 ```150/// tip151152Prefer to use the `Annotated` version if possible.153154///155156```Python hl_lines="4"157{!> ../docs_src/parameter_types/bool/tutorial003.py!}158```159160////161162Check it:163164<div class="termy">165
26 unmodified lines
192If you want to (although it might not be a good idea), you can declare only *CLI option* names to set the `False` value.193194To do that, use a space and a single `/` and pass the negative name after:195175=== "Python 3.7+"196//// tab | Python 3.7+197177 ```Python hl_lines="5"178 {!> ../docs_src/parameter_types/bool/tutorial004_an.py!}179 ```198```Python hl_lines="5"199{!> ../docs_src/parameter_types/bool/tutorial004_an.py!}200```201181=== "Python 3.7+ non-Annotated"202////203183 !!! tip184 Prefer to use the `Annotated` version if possible.204//// tab | Python 3.7+ non-Annotated205186 ```Python hl_lines="4"187 {!> ../docs_src/parameter_types/bool/tutorial004.py!}188 ```206/// tip207190!!! tip191 Have in mind that it's a string with a preceding space and then a `/`.208Prefer to use the `Annotated` version if possible.209193 So, it's `" /-S"` not `"/-S"`.210///211212```Python hl_lines="4"213{!> ../docs_src/parameter_types/bool/tutorial004.py!}214```215216////217218/// tip219220Have in mind that it's a string with a preceding space and then a `/`.221222So, it's `" /-S"` not `"/-S"`.223224///225226Check it:227228<div class="termy">229
28 unmodified lines
modified:docs/tutorial/parameter-types/custom-types.md+22 added-22 removed
9 unmodified lines
10## Type Parser1112`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>.1314=== "Python 3.7+"14//// tab | Python 3.7+1516 ```Python hl_lines="13-14 18-19"17 {!> ../docs_src/parameter_types/custom_types/tutorial001_an.py!}18 ```16```Python hl_lines="13-14 18-19"17{!> ../docs_src/parameter_types/custom_types/tutorial001_an.py!}18```1920=== "Python 3.7+ non-Annotated"20////2122 !!! tip23 Prefer to use the `Annotated` version if possible.22//// tab | Python 3.7+ non-Annotated2325 ```Python hl_lines="12-13 17-18"26 {!> ../docs_src/parameter_types/custom_types/tutorial001.py!}27 ```24/// tip2526Prefer to use the `Annotated` version if possible.2728///2930```Python hl_lines="12-13 17-18"31{!> ../docs_src/parameter_types/custom_types/tutorial001.py!}32```3334////3536The 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.3738## Click Custom Type3940If 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.4135=== "Python 3.7+"42//// tab | Python 3.7+4337 ```Python hl_lines="14-18 22-25"38 {!> ../docs_src/parameter_types/custom_types/tutorial002_an.py!}39 ```44```Python hl_lines="14-18 22-25"45{!> ../docs_src/parameter_types/custom_types/tutorial002_an.py!}46```4741=== "Python 3.7+ non-Annotated"4243 !!! tip44 Prefer to use the `Annotated` version if possible.4546 ```Python hl_lines="13-17 21-22"47 {!> ../docs_src/parameter_types/custom_types/tutorial002.py!}48 ```48////
modified:docs/tutorial/parameter-types/datetime.md+22 added-12 removed
56 unmodified lines
57* separated with "`/`"5859...It's a crazy example, but let's say you also needed that strange format:6061=== "Python 3.7+"61//// tab | Python 3.7+6263 ```Python hl_lines="11"64 {!> ../docs_src/parameter_types/datetime/tutorial002_an.py!}65 ```63```Python hl_lines="11"64{!> ../docs_src/parameter_types/datetime/tutorial002_an.py!}65```6667=== "Python 3.7+ non-Annotated"67////6869 !!! tip70 Prefer to use the `Annotated` version if possible.69//// tab | Python 3.7+ non-Annotated7072 ```Python hl_lines="8"73 {!> ../docs_src/parameter_types/datetime/tutorial002.py!}74 ```71/// tip7276!!! tip77 Notice the last string in `formats`: `"%m/%d/%Y"`.73Prefer to use the `Annotated` version if possible.7475///7677```Python hl_lines="8"78{!> ../docs_src/parameter_types/datetime/tutorial002.py!}79```8081////8283/// tip8485Notice the last string in `formats`: `"%m/%d/%Y"`.8687///8889Check it:9091<div class="termy">92
13 unmodified lines
modified:docs/tutorial/parameter-types/enum.md+40 added-23 removed
2 unmodified lines
3```Python hl_lines="1 6 7 8 9 12 13"4{!../docs_src/parameter_types/enum/tutorial001.py!}5```67!!! tip8 Notice that the function parameter `network` will be an `Enum`, not a `str`.7/// tip810 To get the `str` value in your function's code use `network.value`.9Notice that the function parameter `network` will be an `Enum`, not a `str`.1011To get the `str` value in your function's code use `network.value`.1213///1415Check it:1617<div class="termy">18
34 unmodified lines
53### Case insensitive Enum choices5455You can make an `Enum` (choice) *CLI parameter* be case-insensitive with the `case_sensitive` parameter:5654=== "Python 3.7+"57//// tab | Python 3.7+5856 ```Python hl_lines="15"57 {!> ../docs_src/parameter_types/enum/tutorial002_an.py!}58 ```59```Python hl_lines="15"60{!> ../docs_src/parameter_types/enum/tutorial002_an.py!}61```6260=== "Python 3.7+ non-Annotated"63////6462 !!! tip63 Prefer to use the `Annotated` version if possible.65//// tab | Python 3.7+ non-Annotated6665 ```Python hl_lines="13"66 {!> ../docs_src/parameter_types/enum/tutorial002.py!}67 ```67/// tip6869Prefer to use the `Annotated` version if possible.7071///7273```Python hl_lines="13"74{!> ../docs_src/parameter_types/enum/tutorial002.py!}75```7677////7879And then the values of the `Enum` will be checked no matter if lower case, upper case, or a mix:8081<div class="termy">82
14 unmodified lines
97### List of Enum values9899A *CLI parameter* can also take a list of `Enum` values:10091=== "Python 3.7+"101//// tab | Python 3.7+10293 ```Python hl_lines="14"94 {!> ../docs_src/parameter_types/enum/tutorial003_an.py!}95 ```103```Python hl_lines="14"104{!> ../docs_src/parameter_types/enum/tutorial003_an.py!}105```10697=== "Python 3.7+ non-Annotated"107////10899 !!! tip100 Prefer to use the `Annotated` version if possible.109//// tab | Python 3.7+ non-Annotated110102 ```Python hl_lines="13"103 {!> ../docs_src/parameter_types/enum/tutorial003.py!}104 ```111/// tip112113Prefer to use the `Annotated` version if possible.114115///116117```Python hl_lines="13"118{!> ../docs_src/parameter_types/enum/tutorial003.py!}119```120121////122123This works just like any other parameter value taking a list of things:124125<div class="termy">126
27 unmodified lines
modified:docs/tutorial/parameter-types/file.md+108 added-61 removed
1Apart from `Path` *CLI parameters* you can also declare some types of "files".23!!! tip4 In most of the cases you are probably fine just using `Path`.3/// tip46 You can read and write data with `Path` the same way.5In most of the cases you are probably fine just using `Path`.67You can read and write data with `Path` the same way.89///1011The difference is that these types will give you a Python <a href="https://docs.python.org/3/glossary.html#term-file-object" class="external-link" target="_blank">file-like object</a> instead of a Python <a href="https://docs.python.org/3/library/pathlib.html#basic-use" class="external-link" target="_blank">Path</a>.1213A "file-like object" is the same type of object returned by `open()` as in:14
29 unmodified lines
44```4546You will get all the correct editor support, attributes, methods, etc for the file-like object:`4745=== "Python 3.7+"48//// tab | Python 3.7+4947 ```Python hl_lines="5"48 {!> ../docs_src/parameter_types/file/tutorial001_an.py!}49 ```50```Python hl_lines="5"51{!> ../docs_src/parameter_types/file/tutorial001_an.py!}52```5351=== "Python 3.7+ non-Annotated"54////5553 !!! tip54 Prefer to use the `Annotated` version if possible.56//// tab | Python 3.7+ non-Annotated5756 ```Python hl_lines="4"57 {!> ../docs_src/parameter_types/file/tutorial001.py!}58 ```58/// tip5960Prefer to use the `Annotated` version if possible.6162///6364```Python hl_lines="4"65{!> ../docs_src/parameter_types/file/tutorial001.py!}66```6768////6970Check it:7172<div class="termy">73
17 unmodified lines
91## `FileTextWrite`9293For writing text, you can use `typer.FileTextWrite`:9485=== "Python 3.7+"95//// tab | Python 3.7+9687 ```Python hl_lines="5-6"88 {!> ../docs_src/parameter_types/file/tutorial002_an.py!}89 ```97```Python hl_lines="5-6"98{!> ../docs_src/parameter_types/file/tutorial002_an.py!}99```10091=== "Python 3.7+ non-Annotated"101////10293 !!! tip94 Prefer to use the `Annotated` version if possible.103//// tab | Python 3.7+ non-Annotated10496 ```Python hl_lines="4-5"97 {!> ../docs_src/parameter_types/file/tutorial002.py!}98 ```105/// tip106107Prefer to use the `Annotated` version if possible.108109///110111```Python hl_lines="4-5"112{!> ../docs_src/parameter_types/file/tutorial002.py!}113```114115////116117This would be for writing human text, like:118119```120some settings
18 unmodified lines
139```140141</div>142126!!! info "Technical Details"127 `typer.FileTextWrite` is a just a convenience class.143/// info | Technical Details144129 It's the same as using `typer.FileText` and setting `mode="w"`. You will learn about `mode` later below.145`typer.FileTextWrite` is a just a convenience class.146147It's the same as using `typer.FileText` and setting `mode="w"`. You will learn about `mode` later below.148149///150151## `FileBinaryRead`152153To read binary data you can use `typer.FileBinaryRead`.154155You will receive `bytes` from it.156157It's useful for reading binary files like images:158139=== "Python 3.7+"159//// tab | Python 3.7+160141 ```Python hl_lines="5"142 {!> ../docs_src/parameter_types/file/tutorial003_an.py!}143 ```161```Python hl_lines="5"162{!> ../docs_src/parameter_types/file/tutorial003_an.py!}163```164145=== "Python 3.7+ non-Annotated"165////166147 !!! tip148 Prefer to use the `Annotated` version if possible.167//// tab | Python 3.7+ non-Annotated168150 ```Python hl_lines="4"151 {!> ../docs_src/parameter_types/file/tutorial003.py!}152 ```169/// tip170171Prefer to use the `Annotated` version if possible.172173///174175```Python hl_lines="4"176{!> ../docs_src/parameter_types/file/tutorial003.py!}177```178179////180181Check it:182183<div class="termy">184
19 unmodified lines
204Have in mind that you have to pass `bytes` to its `.write()` method, not `str`.205206If you have a `str`, you have to encode it first to get `bytes`.207181=== "Python 3.7+"208//// tab | Python 3.7+209183 ```Python hl_lines="5"184 {!> ../docs_src/parameter_types/file/tutorial004_an.py!}185 ```210```Python hl_lines="5"211{!> ../docs_src/parameter_types/file/tutorial004_an.py!}212```213187=== "Python 3.7+ non-Annotated"214////215189 !!! tip190 Prefer to use the `Annotated` version if possible.216//// tab | Python 3.7+ non-Annotated217192 ```Python hl_lines="4"193 {!> ../docs_src/parameter_types/file/tutorial004.py!}194 ```218/// tip219220Prefer to use the `Annotated` version if possible.221222///223224```Python hl_lines="4"225{!> ../docs_src/parameter_types/file/tutorial004.py!}226```227228////229230<div class="termy">231232```console233$ python main.py --file binary.dat
40 unmodified lines
274You can override the `mode` from the defaults above.275276For example, you could use `mode="a"` to write "appending" to the same file:277244=== "Python 3.7+"278//// tab | Python 3.7+279246 ```Python hl_lines="5"247 {!> ../docs_src/parameter_types/file/tutorial005_an.py!}248 ```280```Python hl_lines="5"281{!> ../docs_src/parameter_types/file/tutorial005_an.py!}282```283250=== "Python 3.7+ non-Annotated"284////285252 !!! tip253 Prefer to use the `Annotated` version if possible.286//// tab | Python 3.7+ non-Annotated287255 ```Python hl_lines="4"256 {!> ../docs_src/parameter_types/file/tutorial005.py!}257 ```288/// tip289259!!! tip260 As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.290Prefer to use the `Annotated` version if possible.291292///293294```Python hl_lines="4"295{!> ../docs_src/parameter_types/file/tutorial005.py!}296```297298////299300/// tip301302As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.303304///305306Check it:307308<div class="termy">309
22 unmodified lines
332</div>333334## About the different types335292!!! info293 These are technical details about why the different types/classes provided by **Typer**.336/// info337295 But you don't need this information to be able to use them. You can skip it.338These are technical details about why the different types/classes provided by **Typer**.339340But you don't need this information to be able to use them. You can skip it.341342///343344**Typer** provides you these different types (classes) because they inherit directly from the actual Python implementation that will be provided underneath for each case.345346This way your editor will give you the right type checks and completion for each type.347
3 unmodified lines
modified:docs/tutorial/parameter-types/index.md+5 added-2 removed
60 unmodified lines
6162See more about specific types and validations in the next sections...636465!!! info "Technical Details"66 All the types you will see in the next sections are handled underneath by <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click's Parameter Types</a>.65/// info | Technical Details6667All the types you will see in the next sections are handled underneath by <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click's Parameter Types</a>.6869///
modified:docs/tutorial/parameter-types/number.md+51 added-30 removed
1You can define numeric validations with `max` and `min` values for `int` and `float` *CLI parameters*:23=== "Python 3.7+"3//// tab | Python 3.7+45 ```Python hl_lines="6-8"6 {!> ../docs_src/parameter_types/number/tutorial001_an.py!}7 ```5```Python hl_lines="6-8"6{!> ../docs_src/parameter_types/number/tutorial001_an.py!}7```89=== "Python 3.7+ non-Annotated"9////1011 !!! tip12 Prefer to use the `Annotated` version if possible.11//// tab | Python 3.7+ non-Annotated1214 ```Python hl_lines="5-7"15 {!> ../docs_src/parameter_types/number/tutorial001.py!}16 ```13/// tip1415Prefer to use the `Annotated` version if possible.1617///1819```Python hl_lines="5-7"20{!> ../docs_src/parameter_types/number/tutorial001.py!}21```2223////2425*CLI arguments* and *CLI options* can both use these validations.2627You can specify `min`, `max` or both.28
61 unmodified lines
90You might want to, instead of showing an error, use the closest minimum or maximum valid values.9192You can do it with the `clamp` parameter:9387=== "Python 3.7+"94//// tab | Python 3.7+9589 ```Python hl_lines="6-8"90 {!> ../docs_src/parameter_types/number/tutorial002_an.py!}91 ```96```Python hl_lines="6-8"97{!> ../docs_src/parameter_types/number/tutorial002_an.py!}98```9993=== "Python 3.7+ non-Annotated"100////10195 !!! tip96 Prefer to use the `Annotated` version if possible.102//// tab | Python 3.7+ non-Annotated10398 ```Python hl_lines="5-7"99 {!> ../docs_src/parameter_types/number/tutorial002.py!}100 ```104/// tip105106Prefer to use the `Annotated` version if possible.107108///109110```Python hl_lines="5-7"111{!> ../docs_src/parameter_types/number/tutorial002.py!}112```113114////115116And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:117118<div class="termy">119
19 unmodified lines
139## Counter *CLI options*140141You can make a *CLI option* work as a counter with the `counter` parameter:142129=== "Python 3.7+"143//// tab | Python 3.7+144131 ```Python hl_lines="5"132 {!> ../docs_src/parameter_types/number/tutorial003_an.py!}133 ```145```Python hl_lines="5"146{!> ../docs_src/parameter_types/number/tutorial003_an.py!}147```148135=== "Python 3.7+ non-Annotated"149////150137 !!! tip138 Prefer to use the `Annotated` version if possible.151//// tab | Python 3.7+ non-Annotated152140 ```Python hl_lines="4"141 {!> ../docs_src/parameter_types/number/tutorial003.py!}142 ```153/// tip154155Prefer to use the `Annotated` version if possible.156157///158159```Python hl_lines="4"160{!> ../docs_src/parameter_types/number/tutorial003.py!}161```162163////164165It means that the *CLI option* will be like a boolean flag, e.g. `--verbose`.166167And the value you receive in the function will be the amount of times that `--verbose` was added:168
35 unmodified lines
modified:docs/tutorial/parameter-types/path.md+50 added-27 removed
1You 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>.23This is what you would do for directory paths, file paths, etc:45=== "Python 3.7+"5//// tab | Python 3.7+67 ```Python hl_lines="1 8"8 {!> ../docs_src/parameter_types/path/tutorial001_an.py!}9 ```7```Python hl_lines="1 8"8{!> ../docs_src/parameter_types/path/tutorial001_an.py!}9```1011=== "Python 3.7+ non-Annotated"11////1213 !!! tip14 Prefer to use the `Annotated` version if possible.13//// tab | Python 3.7+ non-Annotated1416 ```Python hl_lines="1 7"17 {!> ../docs_src/parameter_types/path/tutorial001.py!}18 ```15/// tip1617Prefer to use the `Annotated` version if possible.1819///2021```Python hl_lines="1 7"22{!> ../docs_src/parameter_types/path/tutorial001.py!}23```2425////2627And 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.2829Check it:30
37 unmodified lines
68* `writable`: if true, a writable check is performed.69* `readable`: if true, a readable check is performed.70* `resolve_path`: if this is true, then the path is fully resolved before the value is passed onwards. This means that it’s absolute and <abbr title="symbolic links, also known as shortcuts. Links in a file system that point to other location. For example, some applications when installed create symlinks in the desktop to launch them.">symlinks</abbr> are resolved.7165!!! note "Technical Details"66 It will not expand a tilde-prefix (something with `~`, like `~/Documents/`), as this is supposed to be done by the shell only.72/// note | Technical Details7368!!! tip69 All these parameters come directly from <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click</a>.74It will not expand a tilde-prefix (something with `~`, like `~/Documents/`), as this is supposed to be done by the shell only.7576///7778/// tip7980All these parameters come directly from <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click</a>.8182///8384For example:8573=== "Python 3.7+"86//// tab | Python 3.7+8775 ```Python hl_lines="11-16"76 {!> ../docs_src/parameter_types/path/tutorial002_an.py!}77 ```88```Python hl_lines="11-16"89{!> ../docs_src/parameter_types/path/tutorial002_an.py!}90```9179=== "Python 3.7+ non-Annotated"92////9381 !!! tip82 Prefer to use the `Annotated` version if possible.94//// tab | Python 3.7+ non-Annotated9584 ```Python hl_lines="9-14"85 {!> ../docs_src/parameter_types/path/tutorial002.py!}86 ```96/// tip9798Prefer to use the `Annotated` version if possible.99100///101102```Python hl_lines="9-14"103{!> ../docs_src/parameter_types/path/tutorial002.py!}104```105106////107108Check it:109110<div class="termy">111
25 unmodified lines
137</div>138139### Advanced `Path` configurations140121!!! warning "Advanced Details"122 You probably won't need these configurations at first, you may want to skip it.141/// warning | Advanced Details142124 They are used for more advanced use cases.143You probably won't need these configurations at first, you may want to skip it.144145They are used for more advanced use cases.146147///148149* `allow_dash`: If this is set to True, a single dash to indicate standard streams is permitted.150* `path_type`: optionally a string type that should be used to represent the path. The default is None which means the return value will be either bytes or unicode depending on what makes most sense given the input data Click deals with.
modified:docs/tutorial/parameter-types/uuid.md+11 added-10 removed
1!!! info2 A UUID is a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" class="external-link" target="_blank">"Universally Unique Identifier"</a>.1/// info24 It's a standard format for identifiers, like passport numbers, but for anything, not just people in countries.3A UUID is a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" class="external-link" target="_blank">"Universally Unique Identifier"</a>.46 They look like this:5It's a standard format for identifiers, like passport numbers, but for anything, not just people in countries.68 ```9 d48edaa6-871a-4082-a196-4daab372d4a110 ```7They look like this:812 The way they are generated makes them sufficiently long and random that you could assume that every UUID generated is unique. Even if it was generated by a different application, database, or system.9```10d48edaa6-871a-4082-a196-4daab372d4a111```1214 So, if your system uses UUIDs to identify your data, you could mix it with the data from some other system that also uses UUIDs with some confidence that their IDs (UUIDs) won't clash with yours.13The way they are generated makes them sufficiently long and random that you could assume that every UUID generated is unique. Even if it was generated by a different application, database, or system.1416 This wouldn't be true if you just used `int`s as identifiers, as most databases do.15So, if your system uses UUIDs to identify your data, you could mix it with the data from some other system that also uses UUIDs with some confidence that their IDs (UUIDs) won't clash with yours.1617This wouldn't be true if you just used `int`s as identifiers, as most databases do.1819///2021You can declare a *CLI parameter* as a UUID:2223```Python hl_lines="1 6 7 8"
26 unmodified lines
modified:docs/tutorial/subcommands/add-typer.md+5 added-2 removed
125 unmodified lines
126```127128</div>129130!!! tip131 Notice that we are still calling `$ python main.py` but now we are using the command `items`.130/// tip131132Notice that we are still calling `$ python main.py` but now we are using the command `items`.133134///135136And now check the command `users`, with all its subcommands:137138<div class="termy">139
33 unmodified lines
modified:docs/tutorial/subcommands/name-and-help.md+16 added-7 removed
50 unmodified lines
51We can set the `name` and `help` in several places, each one taking precedence over the other, overriding the previous value.5253Let's see those locations.5455!!! tip56 There are other attributes that can be set in that same way in the same places we'll see next.55/// tip5658 But those are documented later in another section.57There are other attributes that can be set in that same way in the same places we'll see next.5859But those are documented later in another section.6061///6263## Inferring name and help from callback6465### Inferring a command's name and help66
231 unmodified lines
298## Set the name and help299300Let's now see the places where you can set the command name and help text, from lowest priority to highest.301299!!! tip300 Setting the name and help text explicitly always has a higher precedence than inferring from a callback function.302/// tip303304Setting the name and help text explicitly always has a higher precedence than inferring from a callback function.305306///307308### Name and help in `typer.Typer()`309310You could have all the callbacks and overrides we defined before, but the name and help text was inferred from the function name and docstring.311
4 unmodified lines
316```Python hl_lines="12"317{!../docs_src/subcommands/name_help/tutorial006.py!}318```319314!!! info315 The rest of the callbacks and overrides are there only to show you that they don't affect the name and help text when you set it explicitly.320/// info321322The rest of the callbacks and overrides are there only to show you that they don't affect the name and help text when you set it explicitly.323324///325326We set an explicit name `exp-users`, and an explicit help `Explicit help.`.327328So that will take precedence now.329
142 unmodified lines
modified:docs/tutorial/subcommands/nested-subcommands.md+12 added-6 removed
276 unmodified lines
277```Python278{!../docs_src/subcommands/tutorial003/main.py!}279```280281!!! tip282 All these files have an `if __name__ == "__main__"` block just to demonstrate how each of them can also be an independent *CLI app*.281/// tip282284 But for your final application, only `main.py` would need it.283All these files have an `if __name__ == "__main__"` block just to demonstrate how each of them can also be an independent *CLI app*.284285But for your final application, only `main.py` would need it.286287///288289## Recap290291That's it, you can just add **Typer** applications one inside another as much as you want and create complex *CLI programs* while writing simple code.292293You can probably achieve a simpler *CLI program* design that's easier to use than the example here. But if your requirements are complex, **Typer** helps you build your *CLI app* easily.294292!!! tip293 Auto completion helps a lot, specially with complex programs.295/// tip296297Auto completion helps a lot, specially with complex programs.298295 Check the docs about adding auto completion to your *CLI apps*.299Check the docs about adding auto completion to your *CLI apps*.300301///
modified:docs/tutorial/first-steps.md+64 added-37 removed
91 unmodified lines
92```9394</div>9596!!! tip97 If you need to pass a single value that contains spaces to a *CLI argument*, use quotes (`"`) around it.96/// tip9798If you need to pass a single value that contains spaces to a *CLI argument*, use quotes (`"`) around it.99100///101102## Two CLI arguments103104Now let's say we want to have the name and last name separated.105
41 unmodified lines
147```148149</div>150148!!! tip149 Notice that the order is important. The last name has to go after the first name.151/// tip152151 If you called it with:153Notice that the order is important. The last name has to go after the first name.154153 ```154 $ python main.py Gutiérrez Camila155 ```155If you called it with:156157 your app wouldn't have a way to know which is the `name` and which the `lastname`. It expects the first *CLI argument* to be the `name` and the second *CLI argument* to be the `lastname`.157```158$ python main.py Gutiérrez Camila159```160161your app wouldn't have a way to know which is the `name` and which the `lastname`. It expects the first *CLI argument* to be the `name` and the second *CLI argument* to be the `lastname`.162163///164165## What is a **CLI option**166167Here we will use the word **CLI option** to refer to *CLI parameters* passed to the CLI application with a specific name. For example, if you go to your terminal and type:168
50 unmodified lines
219220* *CLI options* **start with `--`** and don't depend on the order221* *CLI arguments* depend on the **sequence order**222217!!! tip218 In this example above the *CLI option* `--size` is just a "flag" or "switch" that will contain a boolean value, `True` or `False`, depending on if it was added to the command or not.223/// tip224220 This one doesn't receive any values. But *CLI options* can also receive values like *CLI arguments*. You'll see how later.225In this example above the *CLI option* `--size` is just a "flag" or "switch" that will contain a boolean value, `True` or `False`, depending on if it was added to the command or not.226227This one doesn't receive any values. But *CLI options* can also receive values like *CLI arguments*. You'll see how later.228229///230231## Add one *CLI option*232233Now add a `--formal` *CLI option*:234
23 unmodified lines
258```259260</div>261253!!! tip254 Notice that it automatically creates a `--formal` and a `--no-formal` because it detected that `formal` is a `bool`.262/// tip263264Notice that it automatically creates a `--formal` and a `--no-formal` because it detected that `formal` is a `bool`.265266///267268Now call it normally:269270<div class="termy">271
48 unmodified lines
320```321322</div>323312!!! tip313 Notice the `--lastname`, and notice that it takes a textual value.324/// tip325315 A *CLI option* with a value like `--lastname` (contrary to a *CLI option* without a value, a `bool` flag, like `--formal` or `--size`) takes as its value whatever is at the *right side* of the *CLI option*.326Notice the `--lastname`, and notice that it takes a textual value.327328A *CLI option* with a value like `--lastname` (contrary to a *CLI option* without a value, a `bool` flag, like `--formal` or `--size`) takes as its value whatever is at the *right side* of the *CLI option*.329330///331332<div class="termy">333334```console335// Call it without a --lastname
8 unmodified lines
344```345346</div>347333!!! tip334 Notice that "`Gutiérrez`" is at the right side of `--lastname`. A *CLI option* with a value takes as its value whatever is at the *right side*.348/// tip349350Notice that "`Gutiérrez`" is at the right side of `--lastname`. A *CLI option* with a value takes as its value whatever is at the *right side*.351352///353354And as `--lastname` is now a *CLI option* that doesn't depend on the order, you can pass it before the name:355356<div class="termy">357
38 unmodified lines
396```397398</div>399382!!! tip383 There is another place to document the specific *CLI options* and *CLI arguments* that will show up next to them in the help text as with `--install-completion` or `--help`, you will learn that later in the tutorial.400/// tip401402There is another place to document the specific *CLI options* and *CLI arguments* that will show up next to them in the help text as with `--install-completion` or `--help`, you will learn that later in the tutorial.403404///405406## Arguments, options, parameters, optional, required407408Be aware that these terms refer to multiple things depending on the context, and sadly, those "contexts" mix frequently, so it's easy to get confused.409
7 unmodified lines
417```418419are called "Python function parameters" or "Python function arguments".420400!!! note "Technical Details"401 There's actually a very small distinction in Python between "parameter" and "argument".421/// note | Technical Details422403 It's quite technical... and somewhat pedantic.423There's actually a very small distinction in Python between "parameter" and "argument".424405 *Parameter* refers to the variable name in a function *declaration*. Like:425It's quite technical... and somewhat pedantic.426407 ```408 def bring_person(name: str, lastname: str = ""):409 pass410 ```427*Parameter* refers to the variable name in a function *declaration*. Like:428412 *Argument* refers to the value passed when *calling* a function. Like:429```430def bring_person(name: str, lastname: str = ""):431 pass432```433414 ```415 person = bring_person("Camila", lastname="Gutiérrez")416 ```434*Argument* refers to the value passed when *calling* a function. Like:435418 ...but you will probably see them used interchangeably in most of the places (including here).436```437person = bring_person("Camila", lastname="Gutiérrez")438```439440...but you will probably see them used interchangeably in most of the places (including here).441442///443444#### Python default values445446In Python, in a function, a parameter with a *default value* like `lastname` in:447
61 unmodified lines
509...and it will give you auto completion in your terminal when you hit <kbd>TAB</kbd> for all your code.510511So you can use it to have auto completion for your own scripts as you continue with the tutorial.512489!!! tip490 Your CLI application built with **Typer** won't need the `typer` command to have auto completion once you create a Python package.513/// tip514515Your CLI application built with **Typer** won't need the `typer` command to have auto completion once you create a Python package.516492 But for short scripts and for learning, before creating a Python package, it might be useful.517But for short scripts and for learning, before creating a Python package, it might be useful.518519///
modified:docs/tutorial/index.md+12 added-9 removed
73 unmodified lines
74</div>7576By default, `typer` comes with `rich` and `shellingham`.7778!!! note79 If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.78/// note7981 ```bash82 pip install typer83 ```80If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.8185 ...includes the same optional dependencies as:82```bash83pip install typer84```8586...includes the same optional dependencies as:8787 ```bash88 pip install "typer-slim[standard]"89 ```88```bash89pip install "typer-slim[standard]"90```9192///
modified:docs/tutorial/launch.md+6 added-3 removed
26 unmodified lines
27```Python hl_lines="17"28{!../docs_src/launch/tutorial002.py!}29```3031!!! tip32 The rest of the code in this example is just making sure the app directory exists and creating the config file.31/// tip3234 But the most important part is the `typer.launch(config_file_str, locate=True)` with the argument `locate=True`.33The rest of the code in this example is just making sure the app directory exists and creating the config file.3435But the most important part is the `typer.launch(config_file_str, locate=True)` with the argument `locate=True`.3637///3839Check it:4041<div class="termy">42
9 unmodified lines
modified:docs/tutorial/options-autocompletion.md+224 added-125 removed
12 unmodified lines
13To check it quickly without creating a new Python package, use the `typer` command.1415Then let's create small example program:1617=== "Python 3.7+"17//// tab | Python 3.7+1819 ```Python20 {!> ../docs_src/options_autocompletion/tutorial001_an.py!}21 ```19```Python20{!> ../docs_src/options_autocompletion/tutorial001_an.py!}21```2223=== "Python 3.7+ non-Annotated"23////2425 !!! tip26 Prefer to use the `Annotated` version if possible.25//// tab | Python 3.7+ non-Annotated2628 ```Python29 {!> ../docs_src/options_autocompletion/tutorial001.py!}30 ```27/// tip2829Prefer to use the `Annotated` version if possible.3031///3233```Python34{!> ../docs_src/options_autocompletion/tutorial001.py!}35```3637////3839And let's try it with the `typer` command to get completion:4041<div class="termy">42
24 unmodified lines
67Right now we get completion for the *CLI option* names, but not for the values.6869We can provide completion for the values creating an `autocompletion` function, similar to the `callback` functions from [CLI Option Callback and Context](./options/callback-and-context.md){.internal-link target=_blank}:7064=== "Python 3.7+"71//// tab | Python 3.7+7266 ```Python hl_lines="5-6 15"67 {!> ../docs_src/options_autocompletion/tutorial002_an.py!}68 ```73```Python hl_lines="5-6 15"74{!> ../docs_src/options_autocompletion/tutorial002_an.py!}75```7670=== "Python 3.7+ non-Annotated"77////7872 !!! tip73 Prefer to use the `Annotated` version if possible.79//// tab | Python 3.7+ non-Annotated8075 ```Python hl_lines="4-5 14"76 {!> ../docs_src/options_autocompletion/tutorial002.py!}77 ```81/// tip8283Prefer to use the `Annotated` version if possible.8485///8687```Python hl_lines="4-5 14"88{!> ../docs_src/options_autocompletion/tutorial002.py!}89```9091////9293We return a `list` of strings from the `complete_name()` function.9495And then we get those values when using completion:96
19 unmodified lines
116Modify the `complete_name()` function to receive a parameter of type `str`, it will contain the incomplete value.117118Then we can check and return only the values that start with the incomplete value from the command line:119106=== "Python 3.7+"120//// tab | Python 3.7+121108 ```Python hl_lines="7-12"109 {!> ../docs_src/options_autocompletion/tutorial003_an.py!}110 ```122```Python hl_lines="7-12"123{!> ../docs_src/options_autocompletion/tutorial003_an.py!}124```125112=== "Python 3.7+ non-Annotated"126////127114 !!! tip115 Prefer to use the `Annotated` version if possible.128//// tab | Python 3.7+ non-Annotated129117 ```Python hl_lines="6-11"118 {!> ../docs_src/options_autocompletion/tutorial003.py!}119 ```130/// tip131132Prefer to use the `Annotated` version if possible.133134///135136```Python hl_lines="6-11"137{!> ../docs_src/options_autocompletion/tutorial003.py!}138```139140////141142Now let's try it:143144<div class="termy">145
7 unmodified lines
153</div>154155Now we are only returning the valid values, that start with `Ca`, we are no longer returning `Sebastian` as a completion option.156136!!! tip137 You have to declare the incomplete value of type `str` and that's what you will receive in the function.157/// tip158139 No matter if the actual value will be an `int`, or something else, when doing completion, you will only get a `str` as the incomplete value.159You have to declare the incomplete value of type `str` and that's what you will receive in the function.160141 And the same way, you can only return `str`, not `int`, etc.161No matter if the actual value will be an `int`, or something else, when doing completion, you will only get a `str` as the incomplete value.162163And the same way, you can only return `str`, not `int`, etc.164165///166167## Add help to completions168169Right now we are returning a `list` of `str`.170
4 unmodified lines
175In the `complete_name()` function, instead of providing one `str` per completion element, we provide a `tuple` with 2 items. The first item is the actual completion string, and the second item is the help text.176177So, in the end, we return a `list` of `tuples` of `str`:178155=== "Python 3.7+"179//// tab | Python 3.7+180157 ```Python hl_lines="4-8 11-17"158 {!> ../docs_src/options_autocompletion/tutorial004_an.py!}159 ```181```Python hl_lines="4-8 11-17"182{!> ../docs_src/options_autocompletion/tutorial004_an.py!}183```184161=== "Python 3.7+ non-Annotated"185////186163 !!! tip164 Prefer to use the `Annotated` version if possible.187//// tab | Python 3.7+ non-Annotated188166 ```Python hl_lines="3-7 10-16"167 {!> ../docs_src/options_autocompletion/tutorial004.py!}168 ```189/// tip190170!!! tip171 If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.191Prefer to use the `Annotated` version if possible.192173 Click checks specifically for a `tuple` when extracting the help text.193///194175 So in the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.195```Python hl_lines="3-7 10-16"196{!> ../docs_src/options_autocompletion/tutorial004.py!}197```198177!!! info178 The help text will be visible in Zsh, Fish, and PowerShell.199////200180 Bash doesn't support showing the help text, but completion will still work the same.201/// tip202203If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.204205Click checks specifically for a `tuple` when extracting the help text.206207So in the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.208209///210211/// info212213The help text will be visible in Zsh, Fish, and PowerShell.214215Bash doesn't support showing the help text, but completion will still work the same.216217///218219If you have a shell like Zsh, it would look like:220221<div class="termy">222
13 unmodified lines
236Instead of creating and returning a list with values (`str` or `tuple`), we can use `yield` with each value that we want in the completion.237238That way our function will be a <a href="https://docs.python.org/3.8/glossary.html#index-19" class="external-link" target="_blank">generator</a> that **Typer** (actually Click) can iterate:239203=== "Python 3.7+"240//// tab | Python 3.7+241205 ```Python hl_lines="11-14"206 {!> ../docs_src/options_autocompletion/tutorial005_an.py!}207 ```242```Python hl_lines="11-14"243{!> ../docs_src/options_autocompletion/tutorial005_an.py!}244```245209=== "Python 3.7+ non-Annotated"246////247211 !!! tip212 Prefer to use the `Annotated` version if possible.248//// tab | Python 3.7+ non-Annotated249214 ```Python hl_lines="10-13"215 {!> ../docs_src/options_autocompletion/tutorial005.py!}216 ```250/// tip251252Prefer to use the `Annotated` version if possible.253254///255256```Python hl_lines="10-13"257{!> ../docs_src/options_autocompletion/tutorial005.py!}258```259260////261262That simplifies our code a bit and works the same.263220!!! tip221 If all the `yield` part seems complex for you, don't worry, you can just use the version with the `list` above.264/// tip265223 In the end, that's just to save us a couple of lines of code.266If all the `yield` part seems complex for you, don't worry, you can just use the version with the `list` above.267225!!! info226 The function can use `yield`, so it doesn't have to return strictly a `list`, it just has to be <a href="https://docs.python.org/3.8/glossary.html#term-iterable" class="external-link" target="_blank">iterable</a>.268In the end, that's just to save us a couple of lines of code.269228 But each of the elements for completion has to be a `str` or a `tuple` (when containing a help text).270///271272/// info273274The function can use `yield`, so it doesn't have to return strictly a `list`, it just has to be <a href="https://docs.python.org/3.8/glossary.html#term-iterable" class="external-link" target="_blank">iterable</a>.275276But each of the elements for completion has to be a `str` or a `tuple` (when containing a help text).277278///279280## Access other *CLI parameters* with the Context281282Let's say that now we want to modify the program to be able to "say hi" to multiple people at the same time.283284So, we will allow multiple `--name` *CLI options*.285236!!! tip237 You will learn more about *CLI parameters* with multiple values later in the tutorial.286/// tip287239 So, for now, take this as a sneak peek 😉.288You will learn more about *CLI parameters* with multiple values later in the tutorial.289290So, for now, take this as a sneak peek 😉.291292///293294For this we use a `List` of `str`:295243=== "Python 3.7+"296//// tab | Python 3.7+297245 ```Python hl_lines="9-14"246 {!> ../docs_src/options_autocompletion/tutorial006_an.py!}247 ```298```Python hl_lines="9-14"299{!> ../docs_src/options_autocompletion/tutorial006_an.py!}300```301249=== "Python 3.7+ non-Annotated"302////303251 !!! tip252 Prefer to use the `Annotated` version if possible.304//// tab | Python 3.7+ non-Annotated305254 ```Python hl_lines="8-11"255 {!> ../docs_src/options_autocompletion/tutorial006.py!}256 ```306/// tip307308Prefer to use the `Annotated` version if possible.309310///311312```Python hl_lines="8-11"313{!> ../docs_src/options_autocompletion/tutorial006.py!}314```315316////317318And then we can use it like:319320<div class="termy">321
15 unmodified lines
337But you can access the context by declaring a function parameter of type `typer.Context`.338339And from that context you can get the current values for each parameter.340281=== "Python 3.7+"341//// tab | Python 3.7+342283 ```Python hl_lines="13-14 16"284 {!> ../docs_src/options_autocompletion/tutorial007_an.py!}285 ```343```Python hl_lines="13-14 16"344{!> ../docs_src/options_autocompletion/tutorial007_an.py!}345```346287=== "Python 3.7+ non-Annotated"347////348289 !!! tip290 Prefer to use the `Annotated` version if possible.349//// tab | Python 3.7+ non-Annotated350292 ```Python hl_lines="12-13 15"293 {!> ../docs_src/options_autocompletion/tutorial007.py!}294 ```351/// tip352353Prefer to use the `Annotated` version if possible.354355///356357```Python hl_lines="12-13 15"358{!> ../docs_src/options_autocompletion/tutorial007.py!}359```360361////362363We are getting the `names` already provided with `--name` in the command line before this completion was triggered.364365If there's no `--name` in the command line, it will be `None`, so we use `or []` to make sure we have a `list` (even if empty) to check its contents later.366
28 unmodified lines
395```396397</div>398332!!! tip333 It's quite possible that if there's only one option left, your shell will complete it right away instead of showing the option with the help text, to save you more typing.399/// tip400401It's quite possible that if there's only one option left, your shell will complete it right away instead of showing the option with the help text, to save you more typing.402403///404405## Getting the raw *CLI parameters*406407You can also get the raw *CLI parameters*, just a `list` of `str` with everything passed in the command line before the incomplete value.408409For example, something like `["typer", "main.py", "run", "--name"]`.410341!!! tip342 This would be for advanced scenarios, in most use cases you would be better off using the context.411/// tip412344 But it's still possible if you need it.413This would be for advanced scenarios, in most use cases you would be better off using the context.414415But it's still possible if you need it.416417///418419As a simple example, let's show it on the screen before completion.420421Because completion is based on the output printed by your program (handled internally by **Typer**), during completion we can't just print something else as we normally do.422423### Printing to "standard error"424352!!! tip353 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](./printing.md#standard-output-and-standard-error){.internal-link target=_blank}.425/// tip426427If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](./printing.md#standard-output-and-standard-error){.internal-link target=_blank}.428429///430431The completion system only reads from "standard output", so, printing to "standard error" won't break completion. 🚀432433You can print to "standard error" with a **Rich** `Console(stderr=True)`.434435Using `stderr=True` tells **Rich** that the output should be shown in "standard error".436361=== "Python 3.7+"437//// tab | Python 3.7+438363 ```Python hl_lines="13 16-17"364 {!> ../docs_src/options_autocompletion/tutorial008_an.py!}365 ```439```Python hl_lines="13 16-17"440{!> ../docs_src/options_autocompletion/tutorial008_an.py!}441```442367=== "Python 3.7+ non-Annotated"443////444369 !!! tip370 Prefer to use the `Annotated` version if possible.445//// tab | Python 3.7+ non-Annotated446372 ```Python hl_lines="12 15-16"373 {!> ../docs_src/options_autocompletion/tutorial008.py!}374 ```447/// tip448376!!! info377 If you can't install and use Rich, you can also use `print(lastname, file=sys.stderr)` or `typer.echo("some text", err=True)` instead.449Prefer to use the `Annotated` version if possible.450451///452453```Python hl_lines="12 15-16"454{!> ../docs_src/options_autocompletion/tutorial008.py!}455```456457////458459/// info460461If you can't install and use Rich, you can also use `print(lastname, file=sys.stderr)` or `typer.echo("some text", err=True)` instead.462463///464465We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `List[str]`, here it's named `args`.466381!!! tip382 Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.467/// tip468384 But it doesn't contain only *CLI arguments*, it has everything, including *CLI options* and values, as a raw `list` of `str`.469Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.470471But it doesn't contain only *CLI arguments*, it has everything, including *CLI options* and values, as a raw `list` of `str`.472473///474475And then we just print it to "standard error".476477<div class="termy">478
10 unmodified lines
489```490491</div>492404!!! tip405 This is a very simple (and quite useless) example, just so you know how it works and that you can use it.493/// tip494407 But it's probably useful only in very advanced use cases.495This is a very simple (and quite useless) example, just so you know how it works and that you can use it.496497But it's probably useful only in very advanced use cases.498499///500501## Getting the Context and the raw *CLI parameters*502503Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:504413=== "Python 3.7+"505//// tab | Python 3.7+506415 ```Python hl_lines="16"416 {!> ../docs_src/options_autocompletion/tutorial009_an.py!}417 ```507```Python hl_lines="16"508{!> ../docs_src/options_autocompletion/tutorial009_an.py!}509```510419=== "Python 3.7+ non-Annotated"511////512421 !!! tip422 Prefer to use the `Annotated` version if possible.513//// tab | Python 3.7+ non-Annotated514424 ```Python hl_lines="15"425 {!> ../docs_src/options_autocompletion/tutorial009.py!}426 ```515/// tip516517Prefer to use the `Annotated` version if possible.518519///520521```Python hl_lines="15"522{!> ../docs_src/options_autocompletion/tutorial009.py!}523```524525////526527Check it:528529<div class="termy">530
34 unmodified lines
modified:docs/tutorial/package.md+46 added-19 removed
8 unmodified lines
9You might even have your favorite already.1011Here's a very opinionated, short guide, showing one of the alternative ways of creating a Python package with a **Typer** app, from scratch.1213!!! tip14 If you already have a favorite way of creating Python packages, feel free to skip this.13/// tip1415If you already have a favorite way of creating Python packages, feel free to skip this.1617///1819## Prerequisites2021For this guide we'll use <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a>.22
120 unmodified lines
143 """144 typer.echo("Loading portal gun")145```146144!!! tip145 As we are creating an installable Python package, there's no need to add a section with `if __name__ == "__main__":`.147/// tip148149As we are creating an installable Python package, there's no need to add a section with `if __name__ == "__main__":`.150151///152153## Modify the README154155Let's change the README to have something like:156
167 unmodified lines
324```325326</div>327322!!! warning323 The `--user` is important, that ensures you install it in your user's directory and not in the global system.328/// warning329325 If you installed it in the global system (e.g. with `sudo`) you could install a version of a library (e.g. a sub-dependency) that is incompatible with your system.330The `--user` is important, that ensures you install it in your user's directory and not in the global system.331327!!! tip328 Bonus points if you use <a href="https://github.com/pipxproject/pipx" class="external-link" target="_blank">`pipx`</a> to install it while keeping an isolated environment for your Python CLI programs 🚀332If you installed it in the global system (e.g. with `sudo`) you could install a version of a library (e.g. a sub-dependency) that is incompatible with your system.333334///335336/// tip337338Bonus points if you use <a href="https://github.com/pipxproject/pipx" class="external-link" target="_blank">`pipx`</a> to install it while keeping an isolated environment for your Python CLI programs 🚀339340///341342Now you have your CLI program installed. And you can use it freely:343344<div class="termy">345
18 unmodified lines
364```365366</div>367356!!! tip357 If you want to remove completion you can just delete the added line in that file.368/// tip369370If you want to remove completion you can just delete the added line in that file.371372///373374And after you restart the terminal you will get completion for your new CLI program:375376<div class="termy">377
34 unmodified lines
412Here we pass `pip` as the value for `-m`, so, Python will execute the module `pip` as if it was a script. And then it will pass the rest of the *CLI Parameters* (`install fastapi`) to it.413414These two are more or less equivalent, the `install fastapi` will be passed to `pip`.415401!!! tip402 In the case of `pip`, in many occasions it's actually recommended that you run it with `python -m`, because if you create a virtual environment with its own `python`, that will ensure that you use the `pip` from *that* environment.416/// tip417418In the case of `pip`, in many occasions it's actually recommended that you run it with `python -m`, because if you create a virtual environment with its own `python`, that will ensure that you use the `pip` from *that* environment.419420///421422### Add a `__main__.py`423424You can support that same style of calling the package/module for your own package, simply by adding a file `__main__.py`.425
47 unmodified lines
473```474475</div>476459!!! tip460 Notice that you have to pass the importable version of the package name, so `rick_portal_gun` instead of `rick-portal-gun`.477/// tip478479Notice that you have to pass the importable version of the package name, so `rick_portal_gun` instead of `rick-portal-gun`.480481///482483That works! 🚀 Sort of... 🤔484485See the `__main__.py` in the help instead of `rick-portal-gun`? We'll fix that next.486
14 unmodified lines
501from .main import app502app(prog_name="rick-portal-gun")503```504484!!! tip485 You can pass all the arguments and keyword arguments you could pass to a Click application, including `prog_name`.505/// tip506507You can pass all the arguments and keyword arguments you could pass to a Click application, including `prog_name`.508509///510511<div class="termy">512513```console514$ python -m rick_portal_gun
172 unmodified lines
687You just have to pass it the module to import (`rick_portal_gun.main`) and it will detect the `typer.Typer` app automatically.688689By specifying the `--name` of the program it will be able to use it while generating the docs.690667!!! tip668 If you installed `typer-slim` and don't have the `typer` command, you can use `python -m typer` instead.691/// tip692693If you installed `typer-slim` and don't have the `typer` command, you can use `python -m typer` instead.694695///696697### Publish a new version with the docs698699Now you can publish a new version with the updated docs.700
73 unmodified lines
modified:docs/tutorial/printing.md+50 added-23 removed
134 unmodified lines
135And there's another "**virtual file**" called "**standard error**" that is normally only used for errors.136137But we can also "print" to "standard error". And both are shown on the terminal to the users.138139!!! info140 If you use PowerShell it's quite possible that what you print to "standard error" won't be shown in the terminal.139/// info140142 In PowerShell, to see "standard error" you would have to check the variable `$Error`.141If you use PowerShell it's quite possible that what you print to "standard error" won't be shown in the terminal.142144 But it will work normally in Bash, Zsh, and Fish.143In PowerShell, to see "standard error" you would have to check the variable `$Error`.144145But it will work normally in Bash, Zsh, and Fish.146147///148149### Printing to "standard error"150151You can print to "standard error" creating a Rich `Console` with `stderr=True`.152150!!! tip151 `stderr` is short for "standard error".153/// tip154155`stderr` is short for "standard error".156157///158159Using `stderr=True` tells **Rich** that the output should be shown in "standard error".160161```Python hl_lines="4 8"162{!../docs_src/printing/tutorial004.py!}
24 unmodified lines
187But understanding that will come handy in the future, for example for autocompletion and testing.188189## Typer Echo190185!!! warning186 In most of the cases, for displaying advanced information, it is recommended to use <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>.191/// warning192188 You can probably skip the rest of this section. 🎉😎193In most of the cases, for displaying advanced information, it is recommended to use <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>.194195You can probably skip the rest of this section. 🎉😎196197///198199**Typer** also has a small utility `typer.echo()` to print information on the screen, it comes directly from Click. But normally you shouldn't need it.200201For the simplest cases, you can use the standard Python `print()`.202
8 unmodified lines
211If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.212213And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.214206!!! info207 `typer.echo()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/7.x/quickstart/#echoing" class="external-link" target="_blank">Click's docs</a>.215/// info216217`typer.echo()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/7.x/quickstart/#echoing" class="external-link" target="_blank">Click's docs</a>.218219///220221### Color222211!!! note "Technical Details"212 The way color works in terminals is by using some codes (ANSI escape sequences) as part of the text.223/// note | Technical Details224214 So, a colored text is still just a `str`.225The way color works in terminals is by using some codes (ANSI escape sequences) as part of the text.226216!!! tip217 Again, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎227So, a colored text is still just a `str`.228229///230231/// tip232233Again, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎234235///236237You 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()`:238239```Python hl_lines="7 9"240{!../docs_src/printing/tutorial005.py!}241```242225!!! tip226 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"`.243/// tip244228 But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.245The 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"`.246247But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.248249///250251Check it:252253<div class="use-termynal" data-termynal>254<span data-ty="input">python main.py</span>
12 unmodified lines
267* `blink`: enable or disable blinking.268* `reverse`: enable or disable inverse rendering (foreground becomes background and the other way round).269* `reset`: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.270250!!! info251 You can read more about it in <a href="https://click.palletsprojects.com/en/7.x/api/#click.style" class="external-link" target="_blank">Click's docs about `style()`</a>271/// info272273You can read more about it in <a href="https://click.palletsprojects.com/en/7.x/api/#click.style" class="external-link" target="_blank">Click's docs about `style()`</a>274275///276277### `typer.secho()` - style and print278255!!! tip256 In case you didn't see above, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎279/// tip280281In case you didn't see above, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎282283///284285There'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()`:286287```Python hl_lines="5"288{!../docs_src/printing/tutorial006.py!}
8 unmodified lines
modified:docs/tutorial/progressbar.md+35 added-15 removed
69 unmodified lines
70## Typer `progressbar`7172If you can, you should use **Rich** as explained above, it has more features, it's more advanced, and can display information more beautifully. ✨7374!!! tip75 If you can use Rich, use the information above, the Rich docs, and skip the rest of this page. 😎74/// tip7576If you can use Rich, use the information above, the Rich docs, and skip the rest of this page. 😎7778///7980But if you can't use Rich, Typer (actually Click) comes with a simple utility to show progress bars.8179!!! info80 `typer.progressbar()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/8.1.x/utils/#showing-progress-bars" class="external-link" target="_blank">Click's docs</a>.82/// info8384`typer.progressbar()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/8.1.x/utils/#showing-progress-bars" class="external-link" target="_blank">Click's docs</a>.8586///8788### Use `typer.progressbar`8985!!! tip86 Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎90/// tip9192Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎9394///9596You can use `typer.progressbar()` with a `with` statement, as in:9798```Python99with typer.progressbar(something) as progress:
26 unmodified lines
126 for user in progress:127 typer.echo(user)128```129122!!! tip123 Notice that there are 2 levels of code blocks. One for the `with` statement and one for the `for` statement.130/// tip131125!!! info126 This is mostly useful for operations that take some time.132Notice that there are 2 levels of code blocks. One for the `with` statement and one for the `for` statement.133128 In the example above we are faking it with `time.sleep()`.134///135136/// info137138This is mostly useful for operations that take some time.139140In the example above we are faking it with `time.sleep()`.141142///143144Check it:145146<div class="termy">147
8 unmodified lines
156</div>157158### Setting a Progress Bar `length`159146!!! tip147 Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎160/// tip161162Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎163164///165166The progress bar is generated from the length of the iterable (e.g. the list of users).167168But 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()`.169
38 unmodified lines
208would print each of the "user IDs" (here it's just the numbers from `0` to `99`).209210### Add a `label`211195!!! tip196 Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎212/// tip213214Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎215216///217218You can also set a `label`:219220```Python hl_lines="8"221{!../docs_src/progressbar/tutorial005.py!}
27 unmodified lines
modified:docs/tutorial/terminating.md+12 added-6 removed
38 unmodified lines
39```4041</div>4243!!! tip44 Even though you are raising an exception, it doesn't necessarily mean there's an error.43/// tip4446 This is done with an exception because it works as an "error" and stops all execution.45Even though you are raising an exception, it doesn't necessarily mean there's an error.4648 But then **Typer** (actually Click) catches it and just terminates the program normally.47This is done with an exception because it works as an "error" and stops all execution.4849But then **Typer** (actually Click) catches it and just terminates the program normally.5051///5253## Exit with an error5455`typer.Exit()` takes an optional `code` parameter. By default, `code` is `0`, meaning there was no error.56
31 unmodified lines
88```8990</div>9189!!! tip90 The error code might be used by other programs (for example a Bash script) that execute your CLI program.92/// tip9394The error code might be used by other programs (for example a Bash script) that execute your CLI program.9596///9798## Abort99100There's a special exception that you can use to "abort" a program.101
23 unmodified lines
modified:docs/tutorial/testing.md+42 added-20 removed
35 unmodified lines
36```Python hl_lines="1 5"37{!../docs_src/testing/app01/test_main.py!}38```3940!!! tip41 It's important that the name of the file starts with `test_`, that way pytest will be able to detect it and use it automatically.40/// tip4142It's important that the name of the file starts with `test_`, that way pytest will be able to detect it and use it automatically.4344///4546### Call the app4748Then create a function `test_app()`.49
6 unmodified lines
56```Python hl_lines="8 9"57{!../docs_src/testing/app01/test_main.py!}58```5957!!! tip58 The name of the function has to start with `test_`, that way pytest can detect it and use it automatically.60/// tip6162The name of the function has to start with `test_`, that way pytest can detect it and use it automatically.6364///6566### Check the result6768Then, inside of the test function, add `assert` statements to ensure that everything in the result of the call is as it should be.69
4 unmodified lines
74Here we are checking that the exit code is 0, as it is for programs that exit without errors.7576Then we check that the text printed to "standard output" contains the text that our CLI program prints.7772!!! tip73 You could also check `result.stderr` for "standard error" independently from "standard output" if your `CliRunner` instance is created with the `mix_stderr=False` argument.78/// tip7975!!! info76 If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](printing.md#standard-output-and-standard-error){.internal-link target=_blank}.80You could also check `result.stderr` for "standard error" independently from "standard output" if your `CliRunner` instance is created with the `mix_stderr=False` argument.8182///8384/// info8586If you need a refresher about what is "standard output" and "standard error" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](printing.md#standard-output-and-standard-error){.internal-link target=_blank}.8788///8990### Call `pytest`9192Then you can call `pytest` in your directory and it will run your tests:93
20 unmodified lines
114## Testing input115116If you have a CLI with prompts, like:117106=== "Python 3.7+"118//// tab | Python 3.7+119108 ```Python hl_lines="8"109 {!> ../docs_src/testing/app02_an/main.py!}110 ```120```Python hl_lines="8"121{!> ../docs_src/testing/app02_an/main.py!}122```123112=== "Python 3.7+ non-Annotated"124////125114 !!! tip115 Prefer to use the `Annotated` version if possible.126//// tab | Python 3.7+ non-Annotated127117 ```Python hl_lines="7"118 {!> ../docs_src/testing/app02/main.py!}119 ```128/// tip129130Prefer to use the `Annotated` version if possible.131132///133134```Python hl_lines="7"135{!> ../docs_src/testing/app02/main.py!}136```137138////139140That you would use like:141142<div class="termy">143
10 unmodified lines
154You can test the input typed in the terminal using `input="camila@example.com\n"`.155156This is because what you type in the terminal goes to "**standard input**" and is handled by the operating system as if it was a "virtual file".157139!!! info140 If you need a refresher about what is "standard output", "standard error", and "standard input" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](printing.md#standard-output-and-standard-error){.internal-link target=_blank}.158/// info159160If you need a refresher about what is "standard output", "standard error", and "standard input" check the section in [Printing and Colors: "Standard Output" and "Standard Error"](printing.md#standard-output-and-standard-error){.internal-link target=_blank}.161162///163164When you hit the <kbd>ENTER</kbd> key after typing the email, that is just a "new line character". And in Python that is represented with `"\n"`.165166So, if you use `input="camila@example.com\n"` it means: "type `camila@example.com` in the terminal, then hit the <kbd>ENTER</kbd> key":167
79 unmodified lines
modified:docs/tutorial/typer-command.md+8 added-5 removed
259 unmodified lines
260```261262</div>263264!!! tip265 If you installed only `typer-slim` and you don't have the `typer` command, you can still generate docs with:264/// tip265267 ```console268 $ python -m typer some_script.py utils docs269 ```266If you installed only `typer-slim` and you don't have the `typer` command, you can still generate docs with:267268```console269$ python -m typer some_script.py utils docs270```271272///273274**Options**:275276* `--name TEXT`: The name of the CLI program to use in docs.277* `--output FILE`: An output file to write docs to, like README.md.
104 unmodified lines
modified:docs/tutorial/using-click.md+21 added-9 removed
1!!! warning2 This is a more advanced topic, if you are starting with **Typer**, feel free to skip it.1/// warning24 It will be mostly useful for people that already work with Click and have questions around it.3This is a more advanced topic, if you are starting with **Typer**, feel free to skip it.45It will be mostly useful for people that already work with Click and have questions around it.67///89**Typer** is powered by <a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a>. It does all the work underneath.1011Here is some more information related to using both together.12
36 unmodified lines
49```5051The `cli` variable is converted by Click from a function to a `Group` object. And the original `cli` function is used by that `Group` internally.5250!!! tip51 The original `cli` function would be the equivalent of a [Typer Callback](./commands/callback.md){.internal-link target=_blank}.53/// tip5455The original `cli` function would be the equivalent of a [Typer Callback](./commands/callback.md){.internal-link target=_blank}.5657///5859Then the `cli` variable, that now is a `Group` object, is used to add sub-commands.6061### How **Typer** works62
8 unmodified lines
71* More than one command.72* A callback.73* Sub-Typer apps (sub commands).7469!!! tip70 If you want to learn more about this check the section [One or Multiple Commands](./commands/one-or-multiple.md){.internal-link target=_blank}.75/// tip7677If you want to learn more about this check the section [One or Multiple Commands](./commands/one-or-multiple.md){.internal-link target=_blank}.7879///8081### Combine Click and **Typer**8283**Typer** uses an internal function `typer.main.get_command()` to generate a Click `Command` (or `Group`) from a `typer.Typer` object.84
104 unmodified lines
189Most of the functionality provided by decorators in Click has an alternative way of doing it in **Typer**.190191For example, to access the context, you can just declare a function parameter of type `typer.Context`.192184!!! tip185 You can read more about using the context in the docs: [Commands: Using the Context](commands/context.md){.internal-link target=_blank}193/// tip194195You can read more about using the context in the docs: [Commands: Using the Context](commands/context.md){.internal-link target=_blank}196197///198199But if you need to use something based on Click decorators, you can always generate a Click object using the methods described above, and use it as you would normally use Click.
modified:docs/alternatives.md+32 added-14 removed
12 unmodified lines
13`argparse` is the Python standard library's module to write CLIs.1415It provides a better alternative than reading the *CLI Parameters* as a `list` of `str` and parsing everything by hand.1617!!! check "Inspired **Typer** to"18 Provide a better development experience than just reading *CLI Parameters* by hand.17/// check | Inspired **Typer** to1819Provide a better development experience than just reading *CLI Parameters* by hand.2021///2223### <a href="https://www.hug.rest/" class="external-link" target="_blank">Hug</a>2425Hug is a library to create APIs and CLIs, it uses parameters in functions to declare the required data.2627It inspired a lot of the ideas in **FastAPI** and **Typer**.2826!!! check "Inspired **Typer** to"27 Use function parameters to declare *CLI arguments* and *CLI options* as it simplifies a lot the development experience.29/// check | Inspired **Typer** to3031Use function parameters to declare *CLI arguments* and *CLI options* as it simplifies a lot the development experience.3233///3435### <a href="https://plac.readthedocs.io/en/latest/" class="external-link" target="_blank">Plac</a>3637Plac is another library to create CLIs using parameters in functions, similar to Hug.3833!!! check "Inspired **Typer** to"34 Provide a simple way to use a function as a command line app, without having to create a complete app, with `typer.run(some_function)`.39/// check | Inspired **Typer** to4041Provide a simple way to use a function as a command line app, without having to create a complete app, with `typer.run(some_function)`.4243///4445### <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a>4647Pydantic is a library to handle data validation using standard modern Python type annotations.4849It powers **FastAPI** underneath.5051It is not used by **Typer**, but it inspired a lot of the design (through **FastAPI**).5244!!! check "Inspired **Typer** to"45 Use standard Python type annotations to declare types instead of library-specific types or classes and use them for data validation and documentation.53/// check | Inspired **Typer** to5455Use standard Python type annotations to declare types instead of library-specific types or classes and use them for data validation and documentation.5657///5859### <a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a>6061Click is one of the most widely used libraries to create CLIs in Python.62
4 unmodified lines
67It uses decorators on top of functions to modify the actual value of those functions, converting them to instances of a specific class. This is a clever trick, but code editors can't provide great support for autocompletion that way.6869It was built with some great ideas and design using the features available in the language at the time (Python 2.x).7059!!! check "**Typer** uses it for"60 Everything. 🚀71/// check | **Typer** uses it for7262 **Typer** mainly adds a layer on top of Click, making the code simpler and easier to use, with autocompletion everywhere, etc, but providing all the powerful features of Click underneath.73Everything. 🚀7464 As someone pointed out: <em><a href="https://twitter.com/fishnets88/status/1210126833745838080" class="external-link" target="_blank">"Nice to see it is built on Click but adds the type stuff. Me gusta!"</a></em>75**Typer** mainly adds a layer on top of Click, making the code simpler and easier to use, with autocompletion everywhere, etc, but providing all the powerful features of Click underneath.7677As someone pointed out: <em><a href="https://twitter.com/fishnets88/status/1210126833745838080" class="external-link" target="_blank">"Nice to see it is built on Click but adds the type stuff. Me gusta!"</a></em>7879///8081### <a href="https://github.com/click-contrib/click-completion" class="external-link" target="_blank">`click-completion`</a>8283`click-completion` is a plug-in for Click. It was created to extend completion support for shells when Click only had support for Bash completion.8485Previous versions of **Typer** had deep integrations with `click-completion` and used it as an optional dependency. But now all the completion logic is implemented internally in **Typer** itself, the internal logic was heavily inspired and using some parts of `click-completion`.8687And now **Typer** improved it to have new features, tests, some bug fixes (for issues in plain `click-completion` and Click), and better support for shells, including modern versions of PowerShell (e.g. the default versions that come with Windows 10).8874!!! check "Inspired **Typer** to"75 Provide auto completion for all the shells.89/// check | Inspired **Typer** to9091Provide auto completion for all the shells.9293///9495### <a href="https://fastapi.tiangolo.com/" class="external-link" target="_blank">FastAPI</a>9697I created **FastAPI** to provide an easy way to build APIs with autocompletion for everything in the code (and some other <a href="https://fastapi.tiangolo.com/features/" class="external-link" target="_blank">features</a>).98
3 unmodified lines
modified:docs/contributing.md+68 added-51 removed
20 unmodified lines
21### Activate the environment2223Activate the new environment with:2425=== "Linux, macOS"25//// tab | Linux, macOS2627 <div class="termy">27<div class="termy">2829 ```console30 $ source ./env/bin/activate31 ```29```console30$ source ./env/bin/activate31```3233 </div>33</div>3435=== "Windows PowerShell"35////3637 <div class="termy">37//// tab | Windows PowerShell3839 ```console40 $ .\env\Scripts\Activate.ps141 ```39<div class="termy">4043 </div>41```console42$ .\env\Scripts\Activate.ps143```4445=== "Windows Bash"45</div>4647 Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):47////4849 <div class="termy">49//// tab | Windows Bash5051 ```console52 $ source ./env/Scripts/activate53 ```51Or if you use Bash for Windows (e.g. <a href="https://gitforwindows.org/" class="external-link" target="_blank">Git Bash</a>):5255 </div>53<div class="termy">5455```console56$ source ./env/Scripts/activate57```5859</div>6061////6263To check it worked, use:6459=== "Linux, macOS, Windows Bash"65//// tab | Linux, macOS, Windows Bash6661 <div class="termy">67<div class="termy">6863 ```console64 $ which pip69```console70$ which pip7166 some/directory/typer/env/bin/pip67 ```72some/directory/typer/env/bin/pip73```7469 </div>75</div>7671=== "Windows PowerShell"77////7873 <div class="termy">79//// tab | Windows PowerShell8075 ```console76 $ Get-Command pip81<div class="termy">8278 some/directory/typer/env/bin/pip79 ```83```console84$ Get-Command pip8581 </div>86some/directory/typer/env/bin/pip87```8889</div>9091////9293If it shows the `pip` binary at `env/bin/pip` then it worked. 🎉9485!!! tip86 Every time you install a new package with `pip` under that environment, activate the environment again.95/// tip9688 This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally.97Every time you install a new package with `pip` under that environment, activate the environment again.9899This makes sure that if you use a terminal program installed by that package (like `flit`), you use the one from your local environment and not any other that could be installed globally.100101///102103### Flit104105**Typer** uses <a href="https://flit.readthedocs.io/en/latest/index.html" class="external-link" target="_blank">Flit</a> to build, package and publish the project.106
12 unmodified lines
119Now re-activate the environment to make sure you are using the `flit` you just installed (and not a global one).120121And now use `flit` to install the development dependencies:122110=== "Linux, macOS"123//// tab | Linux, macOS124112 <div class="termy">125<div class="termy">126114 ```console115 $ flit install --deps develop --symlink127```console128$ flit install --deps develop --symlink129117 ---> 100%118 ```130---> 100%131```132120 </div>133</div>134122=== "Windows"135////136124 If you are on Windows, use `--pth-file` instead of `--symlink`:137//// tab | Windows138126 <div class="termy">139If you are on Windows, use `--pth-file` instead of `--symlink`:140128 ```console129 $ flit install --deps develop --pth-file141<div class="termy">142131 ---> 100%132 ```143```console144$ flit install --deps develop --pth-file145134 </div>146---> 100%147```148149</div>150151////152153It will install all the dependencies and your local Typer in your local environment.154155#### Using your local Typer156
92 unmodified lines
modified:docs/features.md+19 added-13 removed
46 unmodified lines
47* Automatic help options for the main CLI program and all its subcommands.48* Automatic command and subcommand structure handling (you will see more about subcommands in the Tutorial - User Guide).49* Automatic completion for the CLI app in all operating systems, in all the shells (Bash, Zsh, Fish, PowerShell), so that the final user of your app can just hit <kbd>TAB</kbd> and get the available options or subcommands. *5051!!! note "* Auto completion"52 Auto completion works when you create a package (installable with `pip`). Or when using the `typer` command.51/// note | * Auto completion5254 **Typer** uses `shellingham` to auto-detect the current shell when installing completion. If you don't want to include `shellingham`, install `typer-slim`.53Auto completion works when you create a package (installable with `pip`). Or when using the `typer` command.5456 **Typer** will automatically create 2 *CLI options*:55**Typer** uses `shellingham` to auto-detect the current shell when installing completion. If you don't want to include `shellingham`, install `typer-slim`.5658 * `--install-completion`: Install completion for the current shell.59 * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.57**Typer** will automatically create 2 *CLI options*:5861 If you didn't add `shellingham` (if you installed `pip install typer-slim`) those *CLI options* take a value with the name of the shell to install completion for, e.g.:59* `--install-completion`: Install completion for the current shell.60* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.6163 * `--install-completion bash`.64 * `--show-completion powershell`.62If you didn't add `shellingham` (if you installed `pip install typer-slim`) those *CLI options* take a value with the name of the shell to install completion for, e.g.:6366 Then you can tell the user to install completion after installing your CLI program and the rest will just work.64* `--install-completion bash`.65* `--show-completion powershell`.6668!!! tip69 **Typer**'s completion is implemented internally, it uses ideas and components from Click and ideas from `click-completion`, but it doesn't use `click-completion` and re-implements some of the relevant parts of Click.67Then you can tell the user to install completion after installing your CLI program and the rest will just work.6871 Then it extends those ideas with features and bug fixes. For example, **Typer** programs also support modern versions of PowerShell (e.g. in Windows 10) among all the other shells.69///7071/// tip7273**Typer**'s completion is implemented internally, it uses ideas and components from Click and ideas from `click-completion`, but it doesn't use `click-completion` and re-implements some of the relevant parts of Click.7475Then it extends those ideas with features and bug fixes. For example, **Typer** programs also support modern versions of PowerShell (e.g. in Windows 10) among all the other shells.7677///7879## The power of Click8081<a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a> is one of the most popular tools for building CLIs in Python.82
9 unmodified lines
modified:docs/help-typer.md+13 added-7 removed
153 unmodified lines
154* Check and read the code, see if it makes sense, **run it locally** and see if it actually solves the problem.155156* Then **comment** saying that you did that, that's how I will know you really checked it.157158!!! info159 Unfortunately, I can't simply trust PRs that just have several approvals.158/// info159161 Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅160Unfortunately, I can't simply trust PRs that just have several approvals.161163 So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓162Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅163164So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓165166///167168* If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things.169170### Tests171
37 unmodified lines
209## Join the chat210211Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">FastAPI and Friends Discord chat server</a> 👥 and hang out with others in the community. There's a `#typer` channel.212210!!! tip211 For questions, ask them in <a href="https://github.com/tiangolo/typer/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help there.213/// tip214213 Use the chat only for other general conversations.215For questions, ask them in <a href="https://github.com/tiangolo/typer/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help there.216217Use the chat only for other general conversations.218219///220221### Don't use the chat for questions222223Have in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.224
23 unmodified lines
modified:mkdocs.yml+25 added-19 removed
113 unmodified lines
114 - Development - Contributing: contributing.md115 - Release Notes: release-notes.md116117markdown_extensions:118 - toc:119 permalink: true120 - markdown.extensions.codehilite:121 guess_lang: false122 - admonition123 - codehilite124 - extra125 - pymdownx.superfences:126 custom_fences:127 - name: mermaid128 class: mermaid129 format: !!python/name:pymdownx.superfences.fence_code_format ''130 - pymdownx.tabbed:131 alternate_style: true132 - mdx_include:133 base_path: docs134 # Enable while writing docs to simplify highlighting135 # - pymdownx.highlight:136 # linenums: true118 toc:119 permalink: true120 markdown.extensions.attr_list:121 markdown.extensions.tables:122 markdown.extensions.md_in_html:123124 pymdownx.superfences:125 custom_fences:126 - name: mermaid127 class: mermaid128 format: !!python/name:pymdownx.superfences.fence_code_format ''129 pymdownx.betterem:130 pymdownx.blocks.details:131 pymdownx.blocks.admonition:132 types:133 - note134 - info135 - tip136 - warning137 - danger138 - check139 pymdownx.blocks.tab:140 alternate_style: True141 mdx_include:142 base_path: docs143144extra:145 analytics:146 provider: google147 property: G-T78C5GNRXK
21 unmodified lines