Skip to content
Myr

✨ Add support for PEP-593 `Annotated` for specifying options and arguments (#584)

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

* ✨ Add support for PEP-593 `Annotated` for specifying options and arguments Implements #184 * Revert things I did to get a 3.6 virtualenv 😅 A lot of the dev dependency packages weren't installable on 3.6, so I had to remove them from the pyproject.toml. This commit adds them back * Fix mypy/lint errors * Skip coverage on test lines that shouldn't execute * Missed a spot * ♻️ Tweak examples and tests with Annotated, add extra examples and tests * 🔥 Remove Pydantic-specific logic from _typing.py * 📝 Update docs to use new Annotated examples * 📝 Add docs introducing Annotated and previous versions * 🔧 Add commented out MkDocs config for highlighting docs examples * ✅ Fix tests for Click 7 ---------

authored by Ryan Miller Galamb · committed by GitHub · parent 1260b8d · Browse files · 179 files+6782 added−322 removed
This commit

State

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

Trailers

  • Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>

Diff stats

179 files+6782 added−322 removed

  • tests:+3455 added−54 removed
  • other:+3327 added−268 removed

179 files+6782 added−322 removed

modified:docs/tutorial/arguments/default.md+32 added-7 removed
modified:docs/tutorial/arguments/envvar.md+42 added-9 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 hl_lines="4"6{!../docs_src/arguments/envvar/tutorial001.py!}7```5=== "Python 3.6+"67 ```Python hl_lines="5"8 {!> ../docs_src/arguments/envvar/tutorial001_an.py!}9 ```1011=== "Python 3.6+ non-Annotated"1213 !!! tip14 Prefer to use the `Annotated` version if possible.1516 ```Python hl_lines="4"17 {!> ../docs_src/arguments/envvar/tutorial001.py!}18 ```1920In 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:2122<div class="termy">23
37 unmodified lines
61## Multiple environment variables6263You 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:6454```Python hl_lines="4"55{!../docs_src/arguments/envvar/tutorial002.py!}56```65=== "Python 3.6+"6667 ```Python hl_lines="6"68 {!> ../docs_src/arguments/envvar/tutorial002_an.py!}69 ```7071=== "Python 3.6+ non-Annotated"7273 !!! tip74 Prefer to use the `Annotated` version if possible.7576 ```Python hl_lines="4"77 {!> ../docs_src/arguments/envvar/tutorial002.py!}78 ```7980Check it:8182<div class="termy">83
27 unmodified lines
111## Hide an env var from the help text112113By default, environment variables used will be shown in the help text, but you can disable them with `show_envvar=False`:11493```Python hl_lines="4"94{!../docs_src/arguments/envvar/tutorial003.py!}95```115=== "Python 3.6+"116117 ```Python hl_lines="7"118 {!> ../docs_src/arguments/envvar/tutorial003_an.py!}119 ```120121=== "Python 3.6+ non-Annotated"122123 !!! tip124 Prefer to use the `Annotated` version if possible.125126 ```Python hl_lines="4"127 {!> ../docs_src/arguments/envvar/tutorial003.py!}128 ```129130Check it:131132<div class="termy">133
27 unmodified lines
modified:docs/tutorial/arguments/help.md+112 added-24 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 hl_lines="4"16{!../docs_src/arguments/help/tutorial001.py!}17```15=== "Python 3.6+"1617 ```Python hl_lines="5"18 {!> ../docs_src/arguments/help/tutorial001_an.py!}19 ```2021=== "Python 3.6+ non-Annotated"2223 !!! tip24 Prefer to use the `Annotated` version if possible.2526 ```Python hl_lines="4"27 {!> ../docs_src/arguments/help/tutorial001.py!}28 ```2930And it will be used in the automatic `--help` option:3132<div class="termy">33
17 unmodified lines
51## Combine help text and docstrings5253And 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>:5444```Python hl_lines="4 5 6 7"45{!../docs_src/arguments/help/tutorial002.py!}46```55=== "Python 3.6+"5657 ```Python hl_lines="5-8"58 {!> ../docs_src/arguments/help/tutorial002_an.py!}59 ```6061=== "Python 3.6+ non-Annotated"6263 !!! tip64 Prefer to use the `Annotated` version if possible.6566 ```Python hl_lines="4-7"67 {!> ../docs_src/arguments/help/tutorial002.py!}68 ```6970And the `--help` option will combine all the information:7172<div class="termy">73
19 unmodified lines
93## Help with defaults9495If you have a *CLI argument* with a default value, like `"World"`:9675```Python hl_lines="4"76{!../docs_src/arguments/help/tutorial003.py!}77```97=== "Python 3.6+"9899 ```Python hl_lines="5"100 {!> ../docs_src/arguments/help/tutorial003_an.py!}101 ```102103=== "Python 3.6+ non-Annotated"104105 !!! tip106 Prefer to use the `Annotated` version if possible.107108 ```Python hl_lines="4"109 {!> ../docs_src/arguments/help/tutorial003.py!}110 ```111112It will show that default value in the help text:113114<div class="termy">115
17 unmodified lines
133</div>134135But you can disable that if you want to, with `show_default=False`:136104```Python hl_lines="4"105{!../docs_src/arguments/help/tutorial004.py!}106```137=== "Python 3.6+"138139 ```Python hl_lines="7"140 {!> ../docs_src/arguments/help/tutorial004_an.py!}141 ```142143=== "Python 3.6+ non-Annotated"144145 !!! tip146 Prefer to use the `Annotated` version if possible.147148 ```Python hl_lines="4"149 {!> ../docs_src/arguments/help/tutorial004.py!}150 ```151152And then it won't show the default value:153154<div class="termy">155
25 unmodified lines
181## Custom default string182183You 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:184141```Python hl_lines="6"142{!../docs_src/arguments/help/tutorial005.py!}143```185=== "Python 3.6+"186187 ```Python hl_lines="9"188 {!> ../docs_src/arguments/help/tutorial005_an.py!}189 ```190191=== "Python 3.6+ non-Annotated"192193 !!! tip194 Prefer to use the `Annotated` version if possible.195196 ```Python hl_lines="6"197 {!> ../docs_src/arguments/help/tutorial005.py!}198 ```199200And it will be used in the help text:201202<div class="termy">203
37 unmodified lines
241But you can customize it with the `metavar` parameter for `typer.Argument()`.242243For 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:244190```Python hl_lines="4"191{!../docs_src/arguments/help/tutorial006.py!}192```245=== "Python 3.6+"246247 ```Python hl_lines="5"248 {!> ../docs_src/arguments/help/tutorial006_an.py!}249 ```250251=== "Python 3.6+ non-Annotated"252253 !!! tip254 Prefer to use the `Annotated` version if possible.255256 ```Python hl_lines="4"257 {!> ../docs_src/arguments/help/tutorial006.py!}258 ```259260Now the generated help text will have `✨username✨` instead of `NAME`:261262<div class="termy">263
18 unmodified lines
282You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.283284If 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:285220```Python hl_lines="7 10"221{!../docs_src/arguments/help/tutorial007.py!}222```286=== "Python 3.6+"287288 ```Python hl_lines="8 12"289 {!> ../docs_src/arguments/help/tutorial007_an.py!}290 ```291292=== "Python 3.6+ non-Annotated"293294 !!! tip295 Prefer to use the `Annotated` version if possible.296297 ```Python hl_lines="7 10"298 {!> ../docs_src/arguments/help/tutorial007.py!}299 ```300301Then, 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`.302303And next you will see other panels for the *CLI arguments* that have a custom panel set in the `rich_help_panel` parameter:304
38 unmodified lines
343If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.344345You will probably not want to do this normally, but it's possible:346270```Python hl_lines="4"271{!../docs_src/arguments/help/tutorial008.py!}272```347=== "Python 3.6+"348349 ```Python hl_lines="5"350 {!> ../docs_src/arguments/help/tutorial008_an.py!}351 ```352353=== "Python 3.6+ non-Annotated"354355 !!! tip356 Prefer to use the `Annotated` version if possible.357358 ```Python hl_lines="4"359 {!> ../docs_src/arguments/help/tutorial008.py!}360 ```361362Check it:363364<div class="termy">365
43 unmodified lines
modified:docs/tutorial/arguments/optional.md+98 added-21 removed
27 unmodified lines
28```2930</div>3132### An alternative *CLI argument* declaration32## An alternative *CLI argument* declaration3334In the [First Steps](../first-steps.md#add-a-cli-argument){.internal-link target=_blank} you saw how to add a *CLI argument*:3536```Python hl_lines="4"
1 unmodified line
38```3940Now let's see an alternative way to create the same *CLI argument*:414242```Python hl_lines="4"43{!../docs_src/arguments/optional/tutorial001.py!}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.4950 If you have an older version, you would get errors when trying to use `Annotated`.5152 Make sure you Upgrade the Typer version to at least 0.9.0 before using `Annotated`.5354Before, you had this function parameter:5556```Python57name: str58```5952And because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.60And now we wrap it with `Annotated`:6154**Typer** does the same and makes it a **required** *CLI argument*.5556And then we changed it to:5762```Python59name: str = typer.Argument(...)63name: Annotated[str]64```6562But now as `typer.Argument()` is the "default value" of the function's parameter, it would mean that "it is no longer required" (in Python terms).66Both of these versions mean the same thing, `Annotated` is part of standard Python and is there for this.6764As we no longer have the Python function default value (or its absence) to tell if something is required or not and what is the default value, the first parameter to `typer.Argument()` serves the same purpose of defining that default value, or making it required.68But the second version using `Annotated` allows us to pass additional metadata that can be used by **Typer**:6966To make it *required*, we pass `...` as the first function argument passed to `typer.Argument(...)`.70```Python71name: Annotated[str, typer.Argument()]72```7368!!! info69 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>.74Now we are being explicit that `name` is a *CLI argument*. It's still a `str` and it's still required (it doesn't have a default value).7576All we did there achieves the same thing as before, a **required** *CLI argument*:7778<div class="termy">
10 unmodified lines
89</div>9091It's still not very useful, but it works correctly.9288And being able to declare a **required** *CLI argument* using `name: str = typer.Argument(...)` that works exactly the same as `name: str` will come handy later.93And being able to declare a **required** *CLI argument* using9490### Make an optional *CLI argument*95```Python96name: Annoated[str, typer.Argument()]97```9899...that works exactly the same as100101```Python102name: str103```104105...will come handy later.106107## Make an optional *CLI argument*108109Now, finally what we came for, an optional *CLI argument*.110111To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:11296```Python hl_lines="6"97{!../docs_src/arguments/optional/tutorial002.py!}113```Python hl_lines="7"114{!../docs_src/arguments/optional/tutorial002_an.py!}115```116117Now we have:118119```Python103name: Optional[str] = typer.Argument(None)120name: Annotated[Optional[str], typer.Argument()] = None121```122123Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).124108And because the first parameter passed to `typer.Argument(None)` (the new "default" value) is `None`, **Typer** knows that this is an **optional** *CLI argument*, if no value is provided when calling it in the command line, it will have that default value of `None`.109125!!! 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`.127128Check the help:
41 unmodified lines
170</div>171172!!! tip173 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.174175## Alternative (old) `typer.Argument()` as the default value176177**Typer** also supports another older alternative syntax for declaring *CLI arguments* with additional metadata.178179Instead of using `Annotated`, you can use `typer.Argument()` as the default value:180181```Python hl_lines="4"182{!> ../docs_src/arguments/optional/tutorial001.py!}183```184185!!! tip186 Prefer to use the `Annotated` version if possible.187188Before, because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.189190When using `typer.Argument()` as the default value **Typer** does the same and makes it a **required** *CLI argument*.191192We changed it to:193194```Python195name: str = typer.Argument()196```197198But now as `typer.Argument()` is the "default value" of the function's parameter, it would mean that "it is no longer required" (in Python terms).199200As we no longer have the Python function default value (or its absence) to tell if something is required or not and what is the default value, `typer.Argument()` receives a first parameter `default` that serves the same purpose of defining that default value, or making it required.201202Not passing any value to the `default` argument is the same as marking it as required. But you can also explicitly mark it as *required* by passing `...` as the `default` argument, passed to `typer.Argument(default=...)`.203204```Python205name: str = typer.Argument(default=...)206```207208!!! info209 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>.210211```Python hl_lines="4"212{!> ../docs_src/arguments/optional/tutorial003.py!}213```214215And the same way, you can make it optional by passing a different `default` value, for example `None`:216217```Python hl_lines="6"218{!> ../docs_src/arguments/optional/tutorial002.py!}219```220221Because the first parameter passed to `typer.Argument(default=None)` (the new "default" value) is `None`, **Typer** knows that this is an **optional** *CLI argument*, if no value is provided when calling it in the command line, it will have that default value of `None`.222223The `default` argument is the first one, so it's possible that you see code that passes the value without explicitly using `default=`, like:224225```Python226name: str = typer.Argument(...)227```228229...or like:230231```Python232name: str = typer.Argument(None)233```234235...but again, try to use `Annotated` if possible, that way your code in terms of Python will mean the same thing as with **Typer** and you won't have to remember any of these details.
modified:docs/tutorial/commands/help.md+61 added-15 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 hl_lines="3 8 9 10 20 23 24 25 26 27 39 42 43 44 45 46 55 56 57"6{!../docs_src/commands/help/tutorial001.py!}7```5=== "Python 3.6+"67 ```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.6+ non-Annotated"1213 !!! tip14 Prefer to use the `Annotated` version if possible.1516 ```Python hl_lines="3 8-10 20 23-27 39 42-46 55-57"17 {!> ../docs_src/commands/help/tutorial001.py!}18 ```1920Check it:2122<div class="termy">23
176 unmodified lines
200### Rich Markup201202If 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:203193```Python hl_lines="3 9 13-15 20 22 24"194{!../docs_src/commands/help/tutorial004.py!}195```204=== "Python 3.6+"205206 ```Python hl_lines="4 10 14-16 21 24 27"207 {!> ../docs_src/commands/help/tutorial004_an.py!}208 ```209210=== "Python 3.6+ non-Annotated"211212 !!! tip213 Prefer to use the `Annotated` version if possible.214215 ```Python hl_lines="3 9 13-15 20 22 24"216 {!> ../docs_src/commands/help/tutorial004.py!}217 ```218219With 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>.220221You can also use markup in the help for the `username` CLI Argument.222
53 unmodified lines
276### Rich Markdown277278If you set `rich_markup_mode="markdown"` when creating the `typer.Typer()` app, you will be able to use Markdown in the docstring:279258```Python hl_lines="3 7 9-17 22 24-25"259{!../docs_src/commands/help/tutorial005.py!}260```280=== "Python 3.6+"281282 ```Python hl_lines="4 9 12-20 25 27-28"283 {!> ../docs_src/commands/help/tutorial005_an.py!}284 ```285286=== "Python 3.6+ non-Annotated"287288 !!! tip289 Prefer to use the `Annotated` version if possible.290291 ```Python hl_lines="3 7 9-17 22 24-25"292 {!> ../docs_src/commands/help/tutorial005.py!}293 ```294295With 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>.296297And the same as before, the help text overwritten for the command `delete` can also use Markdown.298
63 unmodified lines
362### Help Panels for Commands363364To set the panel for a command you can pass the argument `rich_help_panel` with the name of the panel you want to use:365333```Python hl_lines="22 30 38 46"334{!../docs_src/commands/help/tutorial006.py!}335```366=== "Python 3.6+"367368 ```Python hl_lines="22 30 38 46"369 {!> ../docs_src/commands/help/tutorial006.py!}370 ```371372Commands without a panel will be shown in the default panel `Commands`, and the rest will be shown in the next panels:373374<div class="termy">375
31 unmodified lines
407The same way, you can configure the panels for *CLI arguments* and *CLI options* with `rich_help_panel`.408409And of course, in the same application you can also set the `rich_help_panel` for commands.410376```Python hl_lines="12 16 21 30"377{!../docs_src/commands/help/tutorial007.py!}378```411=== "Python 3.6+"412413 ```Python hl_lines="15 21 27 37"414 {!> ../docs_src/commands/help/tutorial007_an.py!}415 ```416417=== "Python 3.6+ non-Annotated"418419 !!! tip420 Prefer to use the `Annotated` version if possible.421422 ```Python hl_lines="12 16 21 30"423 {!> ../docs_src/commands/help/tutorial007.py!}424 ```425426Then if you run the application you will see all the *CLI parameters* in their respective panels.427428* First the ***CLI arguments*** that don't have a panel name set in a **default** one named "`Arguments`".429* Next the ***CLI arguments*** with a **custom panel**. In this example named "`Secondary Arguments`".
103 unmodified lines
modified:docs/tutorial/commands/options.md+14 added-3 removed
1Commands can also have their own *CLI options*.23In fact, each command can have different *CLI arguments* and *CLI options*:45```Python hl_lines="7 13 14 24 33"6{!../docs_src/commands/options/tutorial001.py!}7```5=== "Python 3.6+"67 ```Python hl_lines="8 14-17 27-29 38"8 {!> ../docs_src/commands/options/tutorial001_an.py!}9 ```1011=== "Python 3.6+ non-Annotated"1213 !!! tip14 Prefer to use the `Annotated` version if possible.1516 ```Python hl_lines="7 13-14 24 33"17 {!> ../docs_src/commands/options/tutorial001.py!}18 ```1920Here we have multiple commands, with different *CLI parameters*:2122* `create`:23 * `username`: a *CLI argument*.
84 unmodified lines
modified:docs/tutorial/multiple-values/arguments-with-multiple-values.md+14 added-3 removed
modified:docs/tutorial/multiple-values/multiple-options.md+28 added-6 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 hl_lines="1 6"8{!../docs_src/multiple_values/multiple_options/tutorial001.py!}9```7=== "Python 3.6+"89 ```Python hl_lines="1 7"10 {!> ../docs_src/multiple_values/multiple_options/tutorial001_an.py!}11 ```1213=== "Python 3.6+ non-Annotated"1415 !!! tip16 Prefer to use the `Annotated` version if possible.1718 ```Python hl_lines="1 6"19 {!> ../docs_src/multiple_values/multiple_options/tutorial001.py!}20 ```2122You will receive the values as you declared them, as a `list` of `str`.2324Check it:25
23 unmodified lines
49## Multiple `float`5051The same way, you can use other types and they will be converted by **Typer** to their declared type:5242```Python hl_lines="6"43{!../docs_src/multiple_values/multiple_options/tutorial002.py!}44```53=== "Python 3.6+"5455 ```Python hl_lines="7"56 {!> ../docs_src/multiple_values/multiple_options/tutorial002_an.py!}57 ```5859=== "Python 3.6+ non-Annotated"6061 !!! tip62 Prefer to use the `Annotated` version if possible.6364 ```Python hl_lines="6"65 {!> ../docs_src/multiple_values/multiple_options/tutorial002.py!}66 ```6768Check it:6970<div class="termy">71
17 unmodified lines
modified:docs/tutorial/multiple-values/options-with-multiple-values.md+14 added-3 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 hl_lines="1 6"8{!../docs_src/multiple_values/options_with_multiple_values/tutorial001.py!}9```7=== "Python 3.6+"89 ```Python hl_lines="1 7"10 {!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py!}11 ```1213=== "Python 3.6+ non-Annotated"1415 !!! tip16 Prefer to use the `Annotated` version if possible.1718 ```Python hl_lines="1 6"19 {!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001.py!}20 ```2122Each of the internal types defines the type of each value in the tuple.2324So:25
78 unmodified lines
modified:docs/tutorial/options/callback-and-context.md+56 added-12 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 hl_lines="4 5 6 7 10"10{!../docs_src/options/callback/tutorial001.py!}11```9=== "Python 3.6+"1011 ```Python hl_lines="5-8 11"12 {!> ../docs_src/options/callback/tutorial001_an.py!}13 ```1415=== "Python 3.6+ non-Annotated"1617 !!! tip18 Prefer to use the `Annotated` version if possible.1920 ```Python hl_lines="4-7 10"21 {!> ../docs_src/options/callback/tutorial001.py!}22 ```2324Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.2526The function receives the value from the command line. It can do anything with it, and then return the value.27
76 unmodified lines
104### Breaking completion in a callback105106Let's say that when the callback is running, we want to show a message saying that it's validating the name:10797```Python hl_lines="5"98{!../docs_src/options/callback/tutorial002.py!}99```108=== "Python 3.6+"109110 ```Python hl_lines="6"111 {!> ../docs_src/options/callback/tutorial002_an.py!}112 ```113114=== "Python 3.6+ non-Annotated"115116 !!! tip117 Prefer to use the `Annotated` version if possible.118119 ```Python hl_lines="5"120 {!> ../docs_src/options/callback/tutorial002.py!}121 ```122123And 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.124125It will look something like:126
25 unmodified lines
152But you can access the context by declaring a function parameter of type `typer.Context`.153154The "context" has some additional data about the current execution of your program:155134```Python hl_lines="4 5 6"135{!../docs_src/options/callback/tutorial003.py!}136```156=== "Python 3.6+"157158 ```Python hl_lines="5-7"159 {!> ../docs_src/options/callback/tutorial003_an.py!}160 ```161162=== "Python 3.6+ non-Annotated"163164 !!! tip165 Prefer to use the `Annotated` version if possible.166167 ```Python hl_lines="4-6"168 {!> ../docs_src/options/callback/tutorial003.py!}169 ```170171The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.172173But it will be `False` when calling the program normally. So you can continue the execution of your previous code.174
22 unmodified lines
197## Using the `CallbackParam` object198199The 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.200168```Python hl_lines="4 7"169{!../docs_src/options/callback/tutorial004.py!}170```201=== "Python 3.6+"202203 ```Python hl_lines="5 8"204 {!> ../docs_src/options/callback/tutorial004_an.py!}205 ```206207=== "Python 3.6+ non-Annotated"208209 !!! tip210 Prefer to use the `Annotated` version if possible.211212 ```Python hl_lines="4 7"213 {!> ../docs_src/options/callback/tutorial004.py!}214 ```215216It's probably not very common, but you could do it if you need it.217218For 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.219
42 unmodified lines
modified:docs/tutorial/options/help.md+45 added-22 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 hl_lines="6 7"6{!../docs_src/options/help/tutorial001.py!}7```5=== "Python 3.6+"69We are replacing the default values we had before with `typer.Option()`.7 ```Python hl_lines="7-8"8 {!> ../docs_src/options/help/tutorial001_an.py!}9 ```1011As we no longer have a default value there, the first parameter to `typer.Option()` serves the same purpose of defining that default value.11=== "Python 3.6+ non-Annotated"1213So, if we had:13 !!! tip14 Prefer to use the `Annotated` version if possible.1515```Python16lastname: str = ""17```16 ```Python hl_lines="6-7"17 {!> ../docs_src/options/help/tutorial001.py!}18 ```1919now we write:20The same way as with `typer.Argument()`, we can put `typer.Option()` inside of `Annotated`.2122We can then pass the `help` keyword parameter:2324```Python22lastname: str = typer.Option("")25lastname: Annotated[str, typer.Option(help="this option does this and that")] = ""26```2725And both forms achieve the same: a *CLI option* with a default value of an empty string (`""`).28...to create the help for that *CLI option*.2927And then we can pass the `help` keyword parameter:30The same way as with `typer.Argument()`, **Typer** also supports the old style using the function parameter default value:3132```Python30lastname: str = typer.Option("", help="this option does this and that")33lastname: str = typer.Option(default="", help="this option does this and that")34```3533to create the help for that *CLI option*.3436Copy that example from above to a file `main.py`.3738Test it:39
28 unmodified lines
68The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.6970If 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*:7171```Python hl_lines="8 11"72{!../docs_src/options/help/tutorial002.py!}73```72=== "Python 3.6+"7374 ```Python hl_lines="11 17"75 {!> ../docs_src/options/help/tutorial002_an.py!}76 ```7778=== "Python 3.6+ non-Annotated"7980 !!! tip81 Prefer to use the `Annotated` version if possible.8283 ```Python hl_lines="8 11"84 {!> ../docs_src/options/help/tutorial002.py!}85 ```8687Now, 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`.8889And below you will see other panels for the *CLI options* that have a custom panel set in the `rich_help_panel` parameter:90
41 unmodified lines
132## Hide default from help133134You can tell Typer to not show the default value in the help text with `show_default=False`:135124```Python hl_lines="4"125{!../docs_src/options/help/tutorial003.py!}126```136=== "Python 3.6+"137138 ```Python hl_lines="5"139 {!> ../docs_src/options/help/tutorial003_an.py!}140 ```141142=== "Python 3.6+ non-Annotated"143144 !!! tip145 Prefer to use the `Annotated` version if possible.146147 ```Python hl_lines="4"148 {!> ../docs_src/options/help/tutorial003.py!}149 ```150151And it will no longer show the default value in the help text:152153<div class="termy">154
25 unmodified lines
modified:docs/tutorial/options/name.md+77 added-20 removed
8 unmodified lines
910or1112```Python13def main(user_name: Optional[str] = typer.Option(None)):13def main(user_name: Annotated[Optional[str], typer.Option()] = None):14 pass15```1617**Typer** will create a *CLI option*:
5 unmodified lines
23But you can customize it if you want to.2425Let'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 next positional argument passed to `typer.Option()`:27You can pass the *CLI option* name that you want to have in the following positional argument passed to `typer.Option()`:2829```Python hl_lines="4"30{!../docs_src/options/name/tutorial001.py!}31```29=== "Python 3.6+"3033Here you are passing the string `"--name"` as the second positional argument to `typer.Option()`.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()`.3637=== "Python 3.6+ non-Annotated"3839 !!! tip40 Prefer to use the `Annotated` version if possible.4142 ```Python hl_lines="4"43 {!> ../docs_src/options/name/tutorial001.py!}44 ```4546 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.4748!!! 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.5051 For example `show_default=True` is a keyword argument. "`show_default`" is the keyword.5240 But in `"--name"` there's no `option_name="--name"` or something similar, it's just the string value `"--name"` that goes in `typer.Option()` after the `...` value passed in the first position.53 But in `"--name"` there's no `option_name="--name"` or something similar, it's just the string value `"--name"` that goes in `typer.Option()`.5455 That's a "positional argument" in a function.5657Check it:
126 unmodified lines
184### Defining *CLI option* short names185186In **Typer** you can also define *CLI option* short names the same way you can customize the long names.187175`typer.Option()` receives as a first function argument the default value, e.g. `None`, and all the next *positional* values are to define the *CLI option* name(s).188YOu can pass *positional* arguments to `typer.Option()` to define the *CLI option* name(s).189190!!! tip191 Remember the *positional* function arguments are those that don't have a keyword.192
2 unmodified lines
195You can overwrite the *CLI option* name to use as in the previous example, but you can also declare extra alternatives, including short names.196197For example, extending the previous example, let's add a *CLI option* short name `-n`:198186```Python hl_lines="4"187{!../docs_src/options/name/tutorial002.py!}188```199=== "Python 3.6+"200201 ```Python hl_lines="5"202 {!> ../docs_src/options/name/tutorial002_an.py!}203 ```204205=== "Python 3.6+ non-Annotated"206207 !!! tip208 Prefer to use the `Annotated` version if possible.209210 ```Python hl_lines="4"211 {!> ../docs_src/options/name/tutorial002.py!}212 ```213214Here 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`.215216Check it:217
23 unmodified lines
241### *CLI option* only short name242243If 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.244221```Python hl_lines="4"222{!../docs_src/options/name/tutorial003.py!}223```245=== "Python 3.6+"246247 ```Python hl_lines="5"248 {!> ../docs_src/options/name/tutorial003_an.py!}249 ```250251=== "Python 3.6+ non-Annotated"252253 !!! tip254 Prefer to use the `Annotated` version if possible.255256 ```Python hl_lines="4"257 {!> ../docs_src/options/name/tutorial003.py!}258 ```259260Check it:261262<div class="termy">263
20 unmodified lines
284### *CLI option* short name and default285286Continuing 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:287253```Python hl_lines="4"254{!../docs_src/options/name/tutorial004.py!}255```288=== "Python 3.6+"289290 ```Python hl_lines="5"291 {!> ../docs_src/options/name/tutorial004_an.py!}292 ```293294=== "Python 3.6+ non-Annotated"295296 !!! tip297 Prefer to use the `Annotated` version if possible.298299 ```Python hl_lines="4"300 {!> ../docs_src/options/name/tutorial004.py!}301 ```302303Check it:304305<div class="termy">306
26 unmodified lines
333You can create multiple short names and use them together.334335You don't have to do anything special for it to work (apart from declaring those short versions):336291```Python hl_lines="5 6"292{!../docs_src/options/name/tutorial005.py!}293```337=== "Python 3.6+"338339 ```Python hl_lines="6-7"340 {!> ../docs_src/options/name/tutorial005_an.py!}341 ```342343=== "Python 3.6+ non-Annotated"344345 !!! tip346 Prefer to use the `Annotated` version if possible.347348 ```Python hl_lines="5-6"349 {!> ../docs_src/options/name/tutorial005.py!}350 ```351352!!! tip353 Notice that, again, we are declaring the long and short version of the *CLI option* names.354355Check it:
30 unmodified lines
modified:docs/tutorial/options/password.md+28 added-6 removed
1Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:23```Python hl_lines="5"4{!../docs_src/options/password/tutorial001.py!}5```3=== "Python 3.6+"45 ```Python hl_lines="7"6 {!> ../docs_src/options/password/tutorial001_an.py!}7 ```89=== "Python 3.6+ non-Annotated"1011 !!! tip12 Prefer to use the `Annotated` version if possible.1314 ```Python hl_lines="5"15 {!> ../docs_src/options/password/tutorial001.py!}16 ```1718And the CLI program will ask for confirmation:1920<div class="termy">21
18 unmodified lines
40You can achieve the same using `hide_input=True`.4142And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:4333```Python hl_lines="6 7 8"34{!../docs_src/options/password/tutorial002.py!}35```44=== "Python 3.6+"4546 ```Python hl_lines="8"47 {!> ../docs_src/options/password/tutorial002_an.py!}48 ```4950=== "Python 3.6+ non-Annotated"5152 !!! tip53 Prefer to use the `Annotated` version if possible.5455 ```Python hl_lines="6-8"56 {!> ../docs_src/options/password/tutorial002.py!}57 ```5859Check it:6061<div class="termy">62
13 unmodified lines
modified:docs/tutorial/options/prompt.md+42 added-9 removed
1It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:23```Python hl_lines="4"4{!../docs_src/options/prompt/tutorial001.py!}5```3=== "Python 3.6+"45 ```Python hl_lines="5"6 {!> ../docs_src/options/prompt/tutorial001_an.py!}7 ```89=== "Python 3.6+ non-Annotated"1011 !!! tip12 Prefer to use the `Annotated` version if possible.1314 ```Python hl_lines="4"15 {!> ../docs_src/options/prompt/tutorial001.py!}16 ```1718And then your program will ask the user for it in the terminal:1920<div class="termy">21
12 unmodified lines
34## Customize the prompt3536You can also set a custom prompt, passing the string that you want to use instead of just `True`:3727```Python hl_lines="5"28{!../docs_src/options/prompt/tutorial002.py!}29```38=== "Python 3.6+"3940 ```Python hl_lines="7"41 {!> ../docs_src/options/prompt/tutorial002_an.py!}42 ```4344=== "Python 3.6+ non-Annotated"4546 !!! tip47 Prefer to use the `Annotated` version if possible.4849 ```Python hl_lines="5"50 {!> ../docs_src/options/prompt/tutorial002.py!}51 ```5253And then your program will ask for it using with your custom prompt:5455<div class="termy">56
16 unmodified lines
73You can do it passing the parameter `confirmation_prompt=True`.7475Let's say it's a CLI app to delete a project:7655```Python hl_lines="4"56{!../docs_src/options/prompt/tutorial003.py!}57```77=== "Python 3.6+"7879 ```Python hl_lines="6"80 {!> ../docs_src/options/prompt/tutorial003_an.py!}81 ```8283=== "Python 3.6+ non-Annotated"8485 !!! tip86 Prefer to use the `Annotated` version if possible.8788 ```Python hl_lines="4"89 {!> ../docs_src/options/prompt/tutorial003.py!}90 ```9192And it will prompt the user for a value and then for the confirmation:9394<div class="termy">95
26 unmodified lines
modified:docs/tutorial/options/required.md+27 added-6 removed
5 unmodified lines
6Well, that's how they work *by default*, and that's the convention in many CLI programs and systems.78But if you really want, you can change that.910To make a *CLI option* required, pass `...` to `typer.Option()`.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.6+"1516 ```Python hl_lines="5"17 {!> ../docs_src/options/required/tutorial001_an.py!}18 ```1920The 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.2122=== "Python 3.6+ non-Annotated"2324 ```Python hl_lines="4"25 {!> ../docs_src/options/required/tutorial001.py!}26 ```2728Or you can explictily pass `...` to `typer.Option(default=...)`:2930=== "Python 3.6+ non-Annotated"3132 ```Python hl_lines="4"33 {!> ../docs_src/options/required/tutorial002.py!}34 ```3536!!! 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>.3839That will tell **Typer** that it's still a *CLI option*, but it doesn't have a default value, and it's required.4017Let's make `--lastname` a required *CLI option*:41!!! tip42 Again, prefer to use the `Annotated` version if possible. That way your code will mean the same in standard Python and in **Typer**.4319```Python hl_lines="4"20{!../docs_src/options/required/tutorial001.py!}21```2244And test it:4546<div class="termy">47
30 unmodified lines
modified:docs/tutorial/options/version.md+42 added-9 removed
4 unmodified lines
5## First version of `--version`67Let's see a first version of how it could look like:89```Python hl_lines="8-11 16-18"10{!../docs_src/options/version/tutorial001.py!}11```9=== "Python 3.6+"1011 ```Python hl_lines="9-12 17-19"12 {!> ../docs_src/options/version/tutorial001_an.py!}13 ```1415=== "Python 3.6+ non-Annotated"1617 !!! tip18 Prefer to use the `Annotated` version if possible.1920 ```Python hl_lines="8-11 16-18"21 {!> ../docs_src/options/version/tutorial001.py!}22 ```2324!!! 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.2627If the `--version` *CLI option* is passed, we get a value `True` in the callback.
39 unmodified lines
67## Previous parameters and `is_eager`6869But 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:7060```Python hl_lines="14-16 21-23"61{!../docs_src/options/version/tutorial002.py!}62```71=== "Python 3.6+"7273 ```Python hl_lines="15-17 22-24"74 {!> ../docs_src/options/version/tutorial002_an.py!}75 ```7677=== "Python 3.6+ non-Annotated"7879 !!! tip80 Prefer to use the `Annotated` version if possible.8182 ```Python hl_lines="14-16 21-23"83 {!> ../docs_src/options/version/tutorial002.py!}84 ```8586Then 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:8788<div class="termy">89
20 unmodified lines
110For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.111112That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:11392```Python hl_lines="22-24"93{!../docs_src/options/version/tutorial003.py!}94```114=== "Python 3.6+"115116 ```Python hl_lines="23-26"117 {!> ../docs_src/options/version/tutorial003_an.py!}118 ```119120=== "Python 3.6+ non-Annotated"121122 !!! tip123 Prefer to use the `Annotated` version if possible.124125 ```Python hl_lines="22-24"126 {!> ../docs_src/options/version/tutorial003.py!}127 ```128129Check it:130131<div class="termy">132
8 unmodified lines
modified:docs/tutorial/parameter-types/bool.md+56 added-12 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 hl_lines="4"12{!../docs_src/parameter_types/bool/tutorial001.py!}13```11=== "Python 3.6+"1213 ```Python hl_lines="5"14 {!> ../docs_src/parameter_types/bool/tutorial001_an.py!}15 ```1617=== "Python 3.6+ non-Annotated"1819 !!! tip20 Prefer to use the `Annotated` version if possible.2122 ```Python hl_lines="4"23 {!> ../docs_src/parameter_types/bool/tutorial001.py!}24 ```2526Now there's only a `--force` *CLI option*:2728<div class="termy">29
40 unmodified lines
70We might want to instead have `--accept` and `--reject`.7172We can do that by passing a single `str` with the 2 names for the `bool` *CLI option* separated by `/`:7363```Python hl_lines="6"64{!../docs_src/parameter_types/bool/tutorial002.py!}65```74=== "Python 3.6+"7576 ```Python hl_lines="7"77 {!> ../docs_src/parameter_types/bool/tutorial002_an.py!}78 ```7980=== "Python 3.6+ non-Annotated"8182 !!! tip83 Prefer to use the `Annotated` version if possible.8485 ```Python hl_lines="6"86 {!> ../docs_src/parameter_types/bool/tutorial002.py!}87 ```8889Check it:9091<div class="termy">92
33 unmodified lines
126The same way, you can declare short versions of the names for these *CLI options*.127128For example, let's say we want `-f` for `--force` and `-F` for `--no-force`:129108```Python hl_lines="4"109{!../docs_src/parameter_types/bool/tutorial003.py!}110```130=== "Python 3.6+"131132 ```Python hl_lines="5"133 {!> ../docs_src/parameter_types/bool/tutorial003_an.py!}134 ```135136=== "Python 3.6+ non-Annotated"137138 !!! tip139 Prefer to use the `Annotated` version if possible.140141 ```Python hl_lines="4"142 {!> ../docs_src/parameter_types/bool/tutorial003.py!}143 ```144145Check it:146147<div class="termy">148
28 unmodified lines
177If you want to (although it might not be a good idea), you can declare only *CLI option* names to set the `False` value.178179To do that, use a space and a single `/` and pass the negative name after:180148```Python hl_lines="4"149{!../docs_src/parameter_types/bool/tutorial004.py!}150```181=== "Python 3.6+"182183 ```Python hl_lines="5"184 {!> ../docs_src/parameter_types/bool/tutorial004_an.py!}185 ```186187=== "Python 3.6+ non-Annotated"188189 !!! tip190 Prefer to use the `Annotated` version if possible.191192 ```Python hl_lines="4"193 {!> ../docs_src/parameter_types/bool/tutorial004.py!}194 ```195196!!! tip197 Have in mind that it's a string with a preceding space and then a `/`.198199 So, it's `" /-S"` not `"/-S"`.
35 unmodified lines
modified:docs/tutorial/parameter-types/datetime.md+14 added-3 removed
58 unmodified lines
59* separated with "`/`"6061...It's a crazy example, but let's say you also needed that strange format:6263```Python hl_lines="8"64{!../docs_src/parameter_types/datetime/tutorial002.py!}65```63=== "Python 3.6+"6465 ```Python hl_lines="11"66 {!> ../docs_src/parameter_types/datetime/tutorial002_an.py!}67 ```6869=== "Python 3.6+ non-Annotated"7071 !!! tip72 Prefer to use the `Annotated` version if possible.7374 ```Python hl_lines="8"75 {!> ../docs_src/parameter_types/datetime/tutorial002.py!}76 ```7778!!! tip79 Notice the last string in `formats`: `"%m/%d/%Y"`.8081Check it:
16 unmodified lines
modified:docs/tutorial/parameter-types/enum.md+14 added-3 removed
43 unmodified lines
44### Case insensitive Enum choices4546You can make an `Enum` (choice) *CLI parameter* be case-insensitive with the `case_sensitive` parameter:4748```Python hl_lines="13"49{!../docs_src/parameter_types/enum/tutorial002.py!}50```48=== "Python 3.6+"4950 ```Python hl_lines="15"51 {!> ../docs_src/parameter_types/enum/tutorial002_an.py!}52 ```5354=== "Python 3.6+ non-Annotated"5556 !!! tip57 Prefer to use the `Annotated` version if possible.5859 ```Python hl_lines="13"60 {!> ../docs_src/parameter_types/enum/tutorial002.py!}61 ```6263And then the values of the `Enum` will be checked no matter if lower case, upper case, or a mix:6465<div class="termy">66
13 unmodified lines
modified:docs/tutorial/parameter-types/file.md+71 added-16 removed
38 unmodified lines
39```Python40content = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"41```4243You will get all the correct editor support, attributes, methods, etc for the file-like object:43You will get all the correct editor support, attributes, methods, etc for the file-like object:`4445```Python hl_lines="4"46{!../docs_src/parameter_types/file/tutorial001.py!}47```45=== "Python 3.6+"4647 ```Python hl_lines="5"48 {!> ../docs_src/parameter_types/file/tutorial001_an.py!}49 ```5051=== "Python 3.6+ non-Annotated"5253 !!! tip54 Prefer to use the `Annotated` version if possible.5556 ```Python hl_lines="4"57 {!> ../docs_src/parameter_types/file/tutorial001.py!}58 ```5960Check it:6162<div class="termy">63
17 unmodified lines
81## `FileTextWrite`8283For writing text, you can use `typer.FileTextWrite`:8474```Python hl_lines="4 5"75{!../docs_src/parameter_types/file/tutorial002.py!}76```85=== "Python 3.6+"8687 ```Python hl_lines="5-6"88 {!> ../docs_src/parameter_types/file/tutorial002_an.py!}89 ```9091=== "Python 3.6+ non-Annotated"9293 !!! tip94 Prefer to use the `Annotated` version if possible.9596 ```Python hl_lines="4-5"97 {!> ../docs_src/parameter_types/file/tutorial002.py!}98 ```99100This would be for writing human text, like:101102```103some settings
31 unmodified lines
135You will receive `bytes` from it.136137It's useful for reading binary files like images:138117```Python hl_lines="4"118{!../docs_src/parameter_types/file/tutorial003.py!}119```139=== "Python 3.6+"140141 ```Python hl_lines="5"142 {!> ../docs_src/parameter_types/file/tutorial003_an.py!}143 ```144145=== "Python 3.6+ non-Annotated"146147 !!! tip148 Prefer to use the `Annotated` version if possible.149150 ```Python hl_lines="4"151 {!> ../docs_src/parameter_types/file/tutorial003.py!}152 ```153154Check it:155156<div class="termy">157
19 unmodified lines
177Have in mind that you have to pass `bytes` to its `.write()` method, not `str`.178179If you have a `str`, you have to encode it first to get `bytes`.180148```Python hl_lines="4"149{!../docs_src/parameter_types/file/tutorial004.py!}150```181=== "Python 3.6+"182183 ```Python hl_lines="5"184 {!> ../docs_src/parameter_types/file/tutorial004_an.py!}185 ```186187=== "Python 3.6+ non-Annotated"188189 !!! tip190 Prefer to use the `Annotated` version if possible.191192 ```Python hl_lines="4"193 {!> ../docs_src/parameter_types/file/tutorial004.py!}194 ```195196<div class="termy">197198```console199$ python main.py --file binary.dat
40 unmodified lines
240You can override the `mode` from the defaults above.241242For example, you could use `mode="a"` to write "appending" to the same file:243200```Python hl_lines="4"201{!../docs_src/parameter_types/file/tutorial005.py!}202```244=== "Python 3.6+"245246 ```Python hl_lines="5"247 {!> ../docs_src/parameter_types/file/tutorial005_an.py!}248 ```249250=== "Python 3.6+ non-Annotated"251252 !!! tip253 Prefer to use the `Annotated` version if possible.254255 ```Python hl_lines="4"256 {!> ../docs_src/parameter_types/file/tutorial005.py!}257 ```258259!!! tip260 As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.261262Check it:
41 unmodified lines
modified:docs/tutorial/parameter-types/number.md+42 added-9 removed
1You can define numeric validations with `max` and `min` values for `int` and `float` *CLI parameters*:23```Python hl_lines="5 6 7"4{!../docs_src/parameter_types/number/tutorial001.py!}5```3=== "Python 3.6+"45 ```Python hl_lines="6-8"6 {!> ../docs_src/parameter_types/number/tutorial001_an.py!}7 ```89=== "Python 3.6+ non-Annotated"1011 !!! tip12 Prefer to use the `Annotated` version if possible.1314 ```Python hl_lines="5-7"15 {!> ../docs_src/parameter_types/number/tutorial001.py!}16 ```1718*CLI arguments* and *CLI options* can both use these validations.1920You can specify `min`, `max` or both.21
63 unmodified lines
85You might want to, instead of showing an error, use the closest minimum or maximum valid values.8687You can do it with the `clamp` parameter:8878```Python hl_lines="5 6 7"79{!../docs_src/parameter_types/number/tutorial002.py!}80```89=== "Python 3.6+"9091 ```Python hl_lines="6-8"92 {!> ../docs_src/parameter_types/number/tutorial002_an.py!}93 ```9495=== "Python 3.6+ non-Annotated"9697 !!! tip98 Prefer to use the `Annotated` version if possible.99100 ```Python hl_lines="5-7"101 {!> ../docs_src/parameter_types/number/tutorial002.py!}102 ```103104And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:105106<div class="termy">107
19 unmodified lines
127## Counter *CLI options*128129You can make a *CLI option* work as a counter with the `counter` parameter:130109```Python hl_lines="4"110{!../docs_src/parameter_types/number/tutorial003.py!}111```131=== "Python 3.6+"132133 ```Python hl_lines="5"134 {!> ../docs_src/parameter_types/number/tutorial003_an.py!}135 ```136137=== "Python 3.6+ non-Annotated"138139 !!! tip140 Prefer to use the `Annotated` version if possible.141142 ```Python hl_lines="4"143 {!> ../docs_src/parameter_types/number/tutorial003.py!}144 ```145146It means that the *CLI option* will be like a boolean flag, e.g. `--verbose`.147148And the value you receive in the function will be the amount of times that `--verbose` was added:149
35 unmodified lines
modified:docs/tutorial/parameter-types/path.md+28 added-6 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 hl_lines="1 7"6{!../docs_src/parameter_types/path/tutorial001.py!}7```5=== "Python 3.6+"67 ```Python hl_lines="1 8"8 {!> ../docs_src/parameter_types/path/tutorial001_an.py!}9 ```1011=== "Python 3.6+ non-Annotated"1213 !!! tip14 Prefer to use the `Annotated` version if possible.1516 ```Python hl_lines="1 7"17 {!> ../docs_src/parameter_types/path/tutorial001.py!}18 ```1920And 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.2122Check it:23
45 unmodified lines
69 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>.7071For example:7262```Python hl_lines="9 10 11 12 13 14"63{!../docs_src/parameter_types/path/tutorial002.py!}64```73=== "Python 3.6+"7475 ```Python hl_lines="11-16"76 {!> ../docs_src/parameter_types/path/tutorial002_an.py!}77 ```7879=== "Python 3.6+ non-Annotated"8081 !!! tip82 Prefer to use the `Annotated` version if possible.8384 ```Python hl_lines="9-14"85 {!> ../docs_src/parameter_types/path/tutorial002.py!}86 ```8788Check it:8990<div class="termy">91
36 unmodified lines
modified:docs/tutorial/options-autocompletion.md+126 added-27 removed
12 unmodified lines
13To check it quickly without creating a new Python package, install [Typer CLI](../typer-cli.md){.internal-link target=_blank}.1415Then let's create small example program:1617```Python18{!../docs_src/options_autocompletion/tutorial001.py!}19```17=== "Python 3.6+"1819 ```Python20 {!> ../docs_src/options_autocompletion/tutorial001_an.py!}21 ```2223=== "Python 3.6+ non-Annotated"2425 !!! tip26 Prefer to use the `Annotated` version if possible.2728 ```Python29 {!> ../docs_src/options_autocompletion/tutorial001.py!}30 ```3132And let's try it with **Typer CLI** to get completion:3334<div class="termy">35
24 unmodified lines
60Right now we get completion for the *CLI option* names, but not for the values.6162We 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}:6353```Python hl_lines="4-5 14"54{!../docs_src/options_autocompletion/tutorial002.py!}55```64=== "Python 3.6+"6566 ```Python hl_lines="5-6 15"67 {!> ../docs_src/options_autocompletion/tutorial002_an.py!}68 ```6970=== "Python 3.6+ non-Annotated"7172 !!! tip73 Prefer to use the `Annotated` version if possible.7475 ```Python hl_lines="4-5 14"76 {!> ../docs_src/options_autocompletion/tutorial002.py!}77 ```7879We return a `list` of strings from the `complete_name()` function.8081And then we get those values when using completion:82
19 unmodified lines
102Modify the `complete_name()` function to receive a parameter of type `str`, it will contain the incomplete value.103104Then we can check and return only the values that start with the incomplete value from the command line:10584```Python hl_lines="6-11"85{!../docs_src/options_autocompletion/tutorial003.py!}86```106=== "Python 3.6+"107108 ```Python hl_lines="7-12"109 {!> ../docs_src/options_autocompletion/tutorial003_an.py!}110 ```111112=== "Python 3.6+ non-Annotated"113114 !!! tip115 Prefer to use the `Annotated` version if possible.116117 ```Python hl_lines="6-11"118 {!> ../docs_src/options_autocompletion/tutorial003.py!}119 ```120121Now let's try it:122123<div class="termy">124
26 unmodified lines
151In 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.152153So, in the end, we return a `list` of `tuples` of `str`:154122```Python hl_lines="3 4 5 6 7 10 11 12 13 14 15 16"123{!../docs_src/options_autocompletion/tutorial004.py!}124```155=== "Python 3.6+"156157 ```Python hl_lines="4-8 11-17"158 {!> ../docs_src/options_autocompletion/tutorial004_an.py!}159 ```160161=== "Python 3.6+ non-Annotated"162163 !!! tip164 Prefer to use the `Annotated` version if possible.165166 ```Python hl_lines="3-7 10-16"167 {!> ../docs_src/options_autocompletion/tutorial004.py!}168 ```169170!!! tip171 If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.172173 Click checks specifically for a `tuple` when extracting the help text.
25 unmodified lines
199Instead of creating and returning a list with values (`str` or `tuple`), we can use `yield` with each value that we want in the completion.200201That 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:202159```Python hl_lines="10 11 12 13"160{!../docs_src/options_autocompletion/tutorial005.py!}161```203=== "Python 3.6+"204205 ```Python hl_lines="11-14"206 {!> ../docs_src/options_autocompletion/tutorial005_an.py!}207 ```208209=== "Python 3.6+ non-Annotated"210211 !!! tip212 Prefer to use the `Annotated` version if possible.213214 ```Python hl_lines="10-13"215 {!> ../docs_src/options_autocompletion/tutorial005.py!}216 ```217218That simplifies our code a bit and works the same.219220!!! tip221 If all the `yield` part seems complex for you, don't worry, you can just use the version with the `list` above.
17 unmodified lines
239 So, for now, take this as a sneak peek 😉.240241For this we use a `List` of `str`:242188```Python hl_lines="8-11"189{!../docs_src/options_autocompletion/tutorial006.py!}190```243=== "Python 3.6+"244245 ```Python hl_lines="9-14"246 {!> ../docs_src/options_autocompletion/tutorial006_an.py!}247 ```248249=== "Python 3.6+ non-Annotated"250251 !!! tip252 Prefer to use the `Annotated` version if possible.253254 ```Python hl_lines="8-11"255 {!> ../docs_src/options_autocompletion/tutorial006.py!}256 ```257258And then we can use it like:259260<div class="termy">261
15 unmodified lines
277But you can access the context by declaring a function parameter of type `typer.Context`.278279And from that context you can get the current values for each parameter.280215```Python hl_lines="12 13 15"216{!../docs_src/options_autocompletion/tutorial007.py!}217```281=== "Python 3.6+"282283 ```Python hl_lines="13-14 16"284 {!> ../docs_src/options_autocompletion/tutorial007_an.py!}285 ```286287=== "Python 3.6+ non-Annotated"288289 !!! tip290 Prefer to use the `Annotated` version if possible.291292 ```Python hl_lines="12-13 15"293 {!> ../docs_src/options_autocompletion/tutorial007.py!}294 ```295296We are getting the `names` already provided with `--name` in the command line before this completion was triggered.297298If 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.299
57 unmodified lines
357You can print to "standard error" with a **Rich** `Console(stderr=True)`.358359Using `stderr=True` tells **Rich** that the output should be shown in "standard error".360284```Python hl_lines="12 15-16"285{!../docs_src/options_autocompletion/tutorial008.py!}286```361=== "Python 3.6+"362363 ```Python hl_lines="13 16-17"364 {!> ../docs_src/options_autocompletion/tutorial008_an.py!}365 ```366367=== "Python 3.6+ non-Annotated"368369 !!! tip370 Prefer to use the `Annotated` version if possible.371372 ```Python hl_lines="12 15-16"373 {!> ../docs_src/options_autocompletion/tutorial008.py!}374 ```375376!!! 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.378379We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `List[str]`, here it's named `args`.
29 unmodified lines
409## Getting the Context and the raw *CLI parameters*410411Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:412325```Python hl_lines="15"326{!../docs_src/options_autocompletion/tutorial009.py!}327```413=== "Python 3.6+"414415 ```Python hl_lines="16"416 {!> ../docs_src/options_autocompletion/tutorial009_an.py!}417 ```418419=== "Python 3.6+ non-Annotated"420421 !!! tip422 Prefer to use the `Annotated` version if possible.423424 ```Python hl_lines="15"425 {!> ../docs_src/options_autocompletion/tutorial009.py!}426 ```427428Check it:429430<div class="termy">431
34 unmodified lines
modified:docs/tutorial/testing.md+14 added-3 removed
101 unmodified lines
102## Testing input103104If you have a CLI with prompts, like:105106```Python hl_lines="7"107{!../docs_src/testing/app02/main.py!}108```106=== "Python 3.6+"107108 ```Python hl_lines="8"109 {!> ../docs_src/testing/app02_an/main.py!}110 ```111112=== "Python 3.6+ non-Annotated"113114 !!! tip115 Prefer to use the `Annotated` version if possible.116117 ```Python hl_lines="7"118 {!> ../docs_src/testing/app02/main.py!}119 ```120121That you would use like:122123<div class="termy">124
100 unmodified lines
added:docs_src/arguments/default/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument()] = "Wade Wilson"):6 print(f"Hello {name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/arguments/default/tutorial002_an.py+16 added
1import random23import typer4from typing_extensions import Annotated567def get_name():8 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])91011def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):12 print(f"Hello {name}")131415if __name__ == "__main__":16 typer.run(main)
modified:docs_src/arguments/default/tutorial002.py+1 added-1 removed
5 unmodified lines
6def get_name():7 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])8910def main(name: str = typer.Argument(get_name)):10def main(name: str = typer.Argument(default_factory=get_name)):11 print(f"Hello {name}")121314if __name__ == "__main__":
1 unmodified line
added:docs_src/arguments/envvar/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument(envvar="AWESOME_NAME")] = "World"):6 print(f"Hello Mr. {name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/arguments/envvar/tutorial002_an.py+12 added
1import typer2from typing_extensions import Annotated345def main(6 name: Annotated[str, typer.Argument(envvar=["AWESOME_NAME", "GOD_NAME"])] = "World"7):8 print(f"Hello Mr. {name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs_src/arguments/envvar/tutorial003_an.py+14 added
1import typer2from typing_extensions import Annotated345def main(6 name: Annotated[7 str, typer.Argument(envvar="AWESOME_NAME", show_envvar=False)8 ] = "World"9):10 print(f"Hello Mr. {name}")111213if __name__ == "__main__":14 typer.run(main)
added:docs_src/arguments/help/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):6 print(f"Hello {name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/arguments/help/tutorial002_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):6 """7 Say hi to NAME very gently, like Dirk.8 """9 print(f"Hello {name}")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/arguments/help/tutorial003_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument(help="Who to greet")] = "World"):6 """7 Say hi to NAME very gently, like Dirk.8 """9 print(f"Hello {name}")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/arguments/help/tutorial004_an.py+17 added
1import typer2from typing_extensions import Annotated345def main(6 name: Annotated[7 str, typer.Argument(help="Who to greet", show_default=False)8 ] = "World"9):10 """11 Say hi to NAME very gently, like Dirk.12 """13 print(f"Hello {name}")141516if __name__ == "__main__":17 typer.run(main)
added:docs_src/arguments/help/tutorial005_an.py+17 added
1import typer2from typing_extensions import Annotated345def main(6 name: Annotated[7 str,8 typer.Argument(9 help="Who to greet", show_default="Deadpoolio the amazing's name"10 ),11 ] = "Wade Wilson"12):13 print(f"Hello {name}")141516if __name__ == "__main__":17 typer.run(main)
added:docs_src/arguments/help/tutorial006_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument(metavar="✨username✨")] = "World"):6 print(f"Hello {name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/arguments/help/tutorial007_an.py+22 added
1import typer2from typing_extensions import Annotated345def main(6 name: Annotated[str, typer.Argument(help="Who to greet")],7 lastname: Annotated[8 str, typer.Argument(help="The last name", rich_help_panel="Secondary Arguments")9 ] = "",10 age: Annotated[11 str,12 typer.Argument(help="The user's age", rich_help_panel="Secondary Arguments"),13 ] = "",14):15 """16 Say hi to NAME very gently, like Dirk.17 """18 print(f"Hello {name}")192021if __name__ == "__main__":22 typer.run(main)
added:docs_src/arguments/help/tutorial008_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument(hidden=True)] = "World"):6 """7 Say hi to NAME very gently, like Dirk.8 """9 print(f"Hello {name}")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/arguments/optional/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: Annotated[str, typer.Argument()]):6 print(f"Hello {name}")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/arguments/optional/tutorial001.py+1 added-1 removed
1import typer234def main(name: str = typer.Argument(...)):4def main(name: str = typer.Argument()):5 print(f"Hello {name}")678if __name__ == "__main__":
1 unmodified line
added:docs_src/arguments/optional/tutorial002_an.py+15 added
1from typing import Optional23import typer4from typing_extensions import Annotated567def main(name: Annotated[Optional[str], typer.Argument()] = None):8 if name is None:9 print("Hello World!")10 else:11 print(f"Hello {name}")121314if __name__ == "__main__":15 typer.run(main)
modified:docs_src/arguments/optional/tutorial002.py+1 added-1 removed
1 unmodified line
23import typer456def main(name: Optional[str] = typer.Argument(None)):6def main(name: Optional[str] = typer.Argument(default=None)):7 if name is None:8 print("Hello World!")9 else:10 print(f"Hello {name}")
4 unmodified lines
added:docs_src/arguments/optional/tutorial003.py+9 added
1import typer234def main(name: str = typer.Argument(default=...)):5 print(f"Hello {name}")678if __name__ == "__main__":9 typer.run(main)
added:docs_src/commands/help/tutorial001_an.py+67 added
1import typer2from typing_extensions import Annotated34app = typer.Typer(help="Awesome CLI user manager.")567@app.command()8def create(username: str):9 """10 Create a new user with USERNAME.11 """12 print(f"Creating user: {username}")131415@app.command()16def delete(17 username: str,18 force: Annotated[19 bool,20 typer.Option(21 prompt="Are you sure you want to delete the user?",22 help="Force deletion without confirmation.",23 ),24 ],25):26 """27 Delete a user with USERNAME.2829 If --force is not used, will ask for confirmation.30 """31 if force:32 print(f"Deleting user: {username}")33 else:34 print("Operation cancelled")353637@app.command()38def delete_all(39 force: Annotated[40 bool,41 typer.Option(42 prompt="Are you sure you want to delete ALL users?",43 help="Force deletion without confirmation.",44 ),45 ]46):47 """48 Delete ALL users in the database.4950 If --force is not used, will ask for confirmation.51 """52 if force:53 print("Deleting all users")54 else:55 print("Operation cancelled")565758@app.command()59def init():60 """61 Initialize the users database.62 """63 print("Initializing user database")646566if __name__ == "__main__":67 app()
added:docs_src/commands/help/tutorial004_an.py+37 added
1import typer2from typing_extensions import Annotated34app = typer.Typer(rich_markup_mode="rich")567@app.command()8def create(9 username: Annotated[10 str, typer.Argument(help="The username to be [green]created[/green]")11 ]12):13 """14 [bold green]Create[/bold green] a new [italic]shinny[/italic] user. :sparkles:1516 This requires a [underline]username[/underline].17 """18 print(f"Creating user: {username}")192021@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")22def delete(23 username: Annotated[24 str, typer.Argument(help="The username to be [red]deleted[/red]")25 ],26 force: Annotated[27 bool, typer.Option(help="Force the [bold red]deletion[/bold red] :boom:")28 ] = False,29):30 """31 Some internal utility function to delete.32 """33 print(f"Deleting user: {username}")343536if __name__ == "__main__":37 app()
added:docs_src/commands/help/tutorial005_an.py+37 added
1import typer2from typing_extensions import Annotated34app = typer.Typer(rich_markup_mode="markdown")567@app.command()8def create(9 username: Annotated[str, typer.Argument(help="The username to be **created**")]10):11 """12 **Create** a new *shinny* user. :sparkles:1314 * Create a username1516 * Show that the username is created1718 ---1920 Learn more at the [Typer docs website](https://typer.tiangolo.com)21 """22 print(f"Creating user: {username}")232425@app.command(help="**Delete** a user with *USERNAME*.")26def delete(27 username: Annotated[str, typer.Argument(help="The username to be **deleted**")],28 force: Annotated[bool, typer.Option(help="Force the **deletion** :boom:")] = False,29):30 """31 Some internal utility function to delete.32 """33 print(f"Deleting user: {username}")343536if __name__ == "__main__":37 app()
added:docs_src/commands/help/tutorial007_an.py+46 added
1from typing import Union23import typer4from typing_extensions import Annotated56app = typer.Typer(rich_markup_mode="rich")789@app.command()10def create(11 username: Annotated[str, typer.Argument(help="The username to create")],12 lastname: Annotated[13 str,14 typer.Argument(15 help="The last name of the new user", rich_help_panel="Secondary Arguments"16 ),17 ] = "",18 force: Annotated[bool, typer.Option(help="Force the creation of the user")] = False,19 age: Annotated[20 Union[int, None],21 typer.Option(help="The age of the new user", rich_help_panel="Additional Data"),22 ] = None,23 favorite_color: Annotated[24 Union[str, None],25 typer.Option(26 help="The favorite color of the new user",27 rich_help_panel="Additional Data",28 ),29 ] = None,30):31 """32 [green]Create[/green] a new user. :sparkles:33 """34 print(f"Creating user: {username}")353637@app.command(rich_help_panel="Utils and Configs")38def config(configuration: str):39 """40 [blue]Configure[/blue] the system. :wrench:41 """42 print(f"Configuring the system with: {configuration}")434445if __name__ == "__main__":46 app()
added:docs_src/commands/options/tutorial001_an.py+43 added
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def create(username: str):9 print(f"Creating user: {username}")101112@app.command()13def delete(14 username: str,15 force: Annotated[16 bool, typer.Option(prompt="Are you sure you want to delete the user?")17 ],18):19 if force:20 print(f"Deleting user: {username}")21 else:22 print("Operation cancelled")232425@app.command()26def delete_all(27 force: Annotated[28 bool, typer.Option(prompt="Are you sure you want to delete ALL users?")29 ]30):31 if force:32 print("Deleting all users")33 else:34 print("Operation cancelled")353637@app.command()38def init():39 print("Initializing user database")404142if __name__ == "__main__":43 app()
added:docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py+17 added
1from typing import Tuple23import typer4from typing_extensions import Annotated567def main(8 names: Annotated[9 Tuple[str, str, str], typer.Argument(help="Select 3 characters to play with")10 ] = ("Harry", "Hermione", "Ron")11):12 for name in names:13 print(f"Hello {name}")141516if __name__ == "__main__":17 typer.run(main)
added:docs_src/multiple_values/multiple_options/tutorial001_an.py+16 added
1from typing import List, Optional23import typer4from typing_extensions import Annotated567def main(user: Annotated[Optional[List[str]], typer.Option()] = None):8 if not user:9 print("No provided users")10 raise typer.Abort()11 for u in user:12 print(f"Processing user: {u}")131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/multiple_values/multiple_options/tutorial002_an.py+12 added
1from typing import List23import typer4from typing_extensions import Annotated567def main(number: Annotated[List[float], typer.Option()] = []):8 print(f"The sum is {sum(number)}")91011if __name__ == "__main__":12 typer.run(main)
added:docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py+18 added
1from typing import Tuple23import typer4from typing_extensions import Annotated567def main(user: Annotated[Tuple[str, int, bool], typer.Option()] = (None, None, None)):8 username, coins, is_wizard = user9 if not username:10 print("No user provided")11 raise typer.Abort()12 print(f"The username {username} has {coins} coins")13 if is_wizard:14 print("And this user is a wizard!")151617if __name__ == "__main__":18 typer.run(main)
added:docs_src/options/callback/tutorial001_an.py+16 added
1import typer2from typing_extensions import Annotated345def name_callback(value: str):6 if value != "Camila":7 raise typer.BadParameter("Only Camila is allowed")8 return value91011def main(name: Annotated[str, typer.Option(callback=name_callback)]):12 print(f"Hello {name}")131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/options/callback/tutorial002_an.py+17 added
1import typer2from typing_extensions import Annotated345def name_callback(value: str):6 print("Validating name")7 if value != "Camila":8 raise typer.BadParameter("Only Camila is allowed")9 return value101112def main(name: Annotated[str, typer.Option(callback=name_callback)]):13 print(f"Hello {name}")141516if __name__ == "__main__":17 typer.run(main)
added:docs_src/options/callback/tutorial003_an.py+19 added
1import typer2from typing_extensions import Annotated345def name_callback(ctx: typer.Context, value: str):6 if ctx.resilient_parsing:7 return8 print("Validating name")9 if value != "Camila":10 raise typer.BadParameter("Only Camila is allowed")11 return value121314def main(name: Annotated[str, typer.Option(callback=name_callback)]):15 print(f"Hello {name}")161718if __name__ == "__main__":19 typer.run(main)
added:docs_src/options/callback/tutorial004_an.py+19 added
1import typer2from typing_extensions import Annotated345def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):6 if ctx.resilient_parsing:7 return8 print(f"Validating param: {param.name}")9 if value != "Camila":10 raise typer.BadParameter("Only Camila is allowed")11 return value121314def main(name: Annotated[str, typer.Option(callback=name_callback)]):15 print(f"Hello {name}")161718if __name__ == "__main__":19 typer.run(main)
added:docs_src/options/help/tutorial001_an.py+22 added
1import typer2from typing_extensions import Annotated345def main(6 name: str,7 lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",8 formal: Annotated[bool, typer.Option(help="Say hi formally.")] = False,9):10 """11 Say hi to NAME, optionally with a --lastname.1213 If --formal is used, say hi very formally.14 """15 if formal:16 print(f"Good day Ms. {name} {lastname}.")17 else:18 print(f"Hello {name} {lastname}")192021if __name__ == "__main__":22 typer.run(main)
added:docs_src/options/help/tutorial002_an.py+33 added
1import typer2from typing_extensions import Annotated345def main(6 name: str,7 lastname: Annotated[str, typer.Option(help="Last name of person to greet.")] = "",8 formal: Annotated[9 bool,10 typer.Option(11 help="Say hi formally.", rich_help_panel="Customization and Utils"12 ),13 ] = False,14 debug: Annotated[15 bool,16 typer.Option(17 help="Enable debugging.", rich_help_panel="Customization and Utils"18 ),19 ] = False,20):21 """22 Say hi to NAME, optionally with a --lastname.2324 If --formal is used, say hi very formally.25 """26 if formal:27 print(f"Good day Ms. {name} {lastname}.")28 else:29 print(f"Hello {name} {lastname}")303132if __name__ == "__main__":33 typer.run(main)
added:docs_src/options/help/tutorial003_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(fullname: Annotated[str, typer.Option(show_default=False)] = "Wade Wilson"):6 print(f"Hello {fullname}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/options/name/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(user_name: Annotated[str, typer.Option("--name")]):6 print(f"Hello {user_name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/options/name/tutorial002_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(user_name: Annotated[str, typer.Option("--name", "-n")]):6 print(f"Hello {user_name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/options/name/tutorial003_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(user_name: Annotated[str, typer.Option("-n")]):6 print(f"Hello {user_name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/options/name/tutorial004_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(user_name: Annotated[str, typer.Option("--user-name", "-n")]):6 print(f"Hello {user_name}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/options/name/tutorial005_an.py+16 added
1import typer2from typing_extensions import Annotated345def main(6 name: Annotated[str, typer.Option("--name", "-n")],7 formal: Annotated[bool, typer.Option("--formal", "-f")] = False,8):9 if formal:10 print(f"Good day Ms. {name}.")11 else:12 print(f"Hello {name}")131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/options/password/tutorial001_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(6 name: str,7 email: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)],8):9 print(f"Hello {name}, your email is {email}")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/options/password/tutorial002_an.py+16 added
1import typer2from typing_extensions import Annotated345def main(6 name: str,7 password: Annotated[8 str, typer.Option(prompt=True, confirmation_prompt=True, hide_input=True)9 ],10):11 print(f"Hello {name}. Doing something very secure with password.")12 print(f"...just kidding, here it is, very insecure: {password}")131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/options/prompt/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):6 print(f"Hello {name} {lastname}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/options/prompt/tutorial002_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(6 name: str,7 lastname: Annotated[str, typer.Option(prompt="Please tell me your last name")],8):9 print(f"Hello {name} {lastname}")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/options/prompt/tutorial003_an.py+12 added
1import typer2from typing_extensions import Annotated345def main(6 project_name: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]7):8 print(f"Deleting project {project_name}")91011if __name__ == "__main__":12 typer.run(main)
added:docs_src/options/required/tutorial001_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(name: str, lastname: Annotated[str, typer.Option()]):6 print(f"Hello {name} {lastname}")789if __name__ == "__main__":10 typer.run(main)
modified:docs_src/options/required/tutorial001.py+1 added-1 removed
1import typer234def main(name: str, lastname: str = typer.Option(...)):4def main(name: str, lastname: str = typer.Option()):5 print(f"Hello {name} {lastname}")678if __name__ == "__main__":
1 unmodified line
added:docs_src/options/required/tutorial002.py+9 added
1import typer234def main(name: str, lastname: str = typer.Option(default=...)):5 print(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
added:docs_src/options/version/tutorial001_an.py+25 added
1from typing import Optional23import typer4from typing_extensions import Annotated56__version__ = "0.1.0"789def version_callback(value: bool):10 if value:11 print(f"Awesome CLI Version: {__version__}")12 raise typer.Exit()131415def main(16 name: Annotated[str, typer.Option()] = "World",17 version: Annotated[18 Optional[bool], typer.Option("--version", callback=version_callback)19 ] = None,20):21 print(f"Hello {name}")222324if __name__ == "__main__":25 typer.run(main)
added:docs_src/options/version/tutorial002_an.py+30 added
1from typing import Optional23import typer4from typing_extensions import Annotated56__version__ = "0.1.0"789def version_callback(value: bool):10 if value:11 print(f"Awesome CLI Version: {__version__}")12 raise typer.Exit()131415def name_callback(name: str):16 if name != "Camila":17 raise typer.BadParameter("Only Camila is allowed")181920def main(21 name: Annotated[str, typer.Option(callback=name_callback)],22 version: Annotated[23 Optional[bool], typer.Option("--version", callback=version_callback)24 ] = None,25):26 print(f"Hello {name}")272829if __name__ == "__main__":30 typer.run(main)
added:docs_src/options/version/tutorial003_an.py+32 added
1from typing import Optional23import typer4from typing_extensions import Annotated56__version__ = "0.1.0"789def version_callback(value: bool):10 if value:11 print(f"Awesome CLI Version: {__version__}")12 raise typer.Exit()131415def name_callback(name: str):16 if name != "Camila":17 raise typer.BadParameter("Only Camila is allowed")18 return name192021def main(22 name: Annotated[str, typer.Option(callback=name_callback)],23 version: Annotated[24 Optional[bool],25 typer.Option("--version", callback=version_callback, is_eager=True),26 ] = None,27):28 print(f"Hello {name}")293031if __name__ == "__main__":32 typer.run(main)
added:docs_src/options_autocompletion/tutorial001_an.py+13 added
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: Annotated[str, typer.Option(help="The name to say hi to.")] = "World"):9 print(f"Hello {name}")101112if __name__ == "__main__":13 app()
added:docs_src/options_autocompletion/tutorial002_an.py+22 added
1import typer2from typing_extensions import Annotated345def complete_name():6 return ["Camila", "Carlos", "Sebastian"]789app = typer.Typer()101112@app.command()13def main(14 name: Annotated[15 str, typer.Option(help="The name to say hi to.", autocompletion=complete_name)16 ] = "World",17):18 print(f"Hello {name}")192021if __name__ == "__main__":22 app()
added:docs_src/options_autocompletion/tutorial003_an.py+28 added
1import typer2from typing_extensions import Annotated34valid_names = ["Camila", "Carlos", "Sebastian"]567def complete_name(incomplete: str):8 completion = []9 for name in valid_names:10 if name.startswith(incomplete):11 completion.append(name)12 return completion131415app = typer.Typer()161718@app.command()19def main(20 name: Annotated[21 str, typer.Option(help="The name to say hi to.", autocompletion=complete_name)22 ] = "World",23):24 print(f"Hello {name}")252627if __name__ == "__main__":28 app()
added:docs_src/options_autocompletion/tutorial004_an.py+33 added
1import typer2from typing_extensions import Annotated34valid_completion_items = [5 ("Camila", "The reader of books."),6 ("Carlos", "The writer of scripts."),7 ("Sebastian", "The type hints guy."),8]91011def complete_name(incomplete: str):12 completion = []13 for name, help_text in valid_completion_items:14 if name.startswith(incomplete):15 completion_item = (name, help_text)16 completion.append(completion_item)17 return completion181920app = typer.Typer()212223@app.command()24def main(25 name: Annotated[26 str, typer.Option(help="The name to say hi to.", autocompletion=complete_name)27 ] = "World",28):29 print(f"Hello {name}")303132if __name__ == "__main__":33 app()
added:docs_src/options_autocompletion/tutorial005_an.py+30 added
1import typer2from typing_extensions import Annotated34valid_completion_items = [5 ("Camila", "The reader of books."),6 ("Carlos", "The writer of scripts."),7 ("Sebastian", "The type hints guy."),8]91011def complete_name(incomplete: str):12 for name, help_text in valid_completion_items:13 if name.startswith(incomplete):14 yield (name, help_text)151617app = typer.Typer()181920@app.command()21def main(22 name: Annotated[23 str, typer.Option(help="The name to say hi to.", autocompletion=complete_name)24 ] = "World",25):26 print(f"Hello {name}")272829if __name__ == "__main__":30 app()
added:docs_src/options_autocompletion/tutorial006_an.py+18 added
1from typing import List23import typer4from typing_extensions import Annotated56app = typer.Typer()789@app.command()10def main(11 name: Annotated[List[str], typer.Option(help="The name to say hi to.")] = ["World"]12):13 for each_name in name:14 print(f"Hello {each_name}")151617if __name__ == "__main__":18 app()
added:docs_src/options_autocompletion/tutorial007_an.py+35 added
1from typing import List23import typer4from typing_extensions import Annotated56valid_completion_items = [7 ("Camila", "The reader of books."),8 ("Carlos", "The writer of scripts."),9 ("Sebastian", "The type hints guy."),10]111213def complete_name(ctx: typer.Context, incomplete: str):14 names = ctx.params.get("name") or []15 for name, help_text in valid_completion_items:16 if name.startswith(incomplete) and name not in names:17 yield (name, help_text)181920app = typer.Typer()212223@app.command()24def main(25 name: Annotated[26 List[str],27 typer.Option(help="The name to say hi to.", autocompletion=complete_name),28 ] = ["World"],29):30 for n in name:31 print(f"Hello {n}")323334if __name__ == "__main__":35 app()
added:docs_src/options_autocompletion/tutorial008_an.py+38 added
1from typing import List23import typer4from rich.console import Console5from typing_extensions import Annotated67valid_completion_items = [8 ("Camila", "The reader of books."),9 ("Carlos", "The writer of scripts."),10 ("Sebastian", "The type hints guy."),11]1213err_console = Console(stderr=True)141516def complete_name(args: List[str], incomplete: str):17 err_console.print(f"{args}")18 for name, help_text in valid_completion_items:19 if name.startswith(incomplete):20 yield (name, help_text)212223app = typer.Typer()242526@app.command()27def main(28 name: Annotated[29 List[str],30 typer.Option(help="The name to say hi to.", autocompletion=complete_name),31 ] = ["World"],32):33 for n in name:34 print(f"Hello {n}")353637if __name__ == "__main__":38 app()
added:docs_src/options_autocompletion/tutorial009_an.py+39 added
1from typing import List23import typer4from rich.console import Console5from typing_extensions import Annotated67valid_completion_items = [8 ("Camila", "The reader of books."),9 ("Carlos", "The writer of scripts."),10 ("Sebastian", "The type hints guy."),11]1213err_console = Console(stderr=True)141516def complete_name(ctx: typer.Context, args: List[str], incomplete: str):17 err_console.print(f"{args}")18 names = ctx.params.get("name") or []19 for name, help_text in valid_completion_items:20 if name.startswith(incomplete) and name not in names:21 yield (name, help_text)222324app = typer.Typer()252627@app.command()28def main(29 name: Annotated[30 List[str],31 typer.Option(help="The name to say hi to.", autocompletion=complete_name),32 ] = ["World"],33):34 for n in name:35 print(f"Hello {n}")363738if __name__ == "__main__":39 app()
added:docs_src/parameter_types/bool/tutorial001_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(force: Annotated[bool, typer.Option("--force")] = False):6 if force:7 print("Forcing operation")8 else:9 print("Not forcing")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/parameter_types/bool/tutorial002_an.py+17 added
1from typing import Optional23import typer4from typing_extensions import Annotated567def main(accept: Annotated[Optional[bool], typer.Option("--accept/--reject")] = None):8 if accept is None:9 print("I don't know what you want yet")10 elif accept:11 print("Accepting!")12 else:13 print("Rejecting!")141516if __name__ == "__main__":17 typer.run(main)
added:docs_src/parameter_types/bool/tutorial003_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(force: Annotated[bool, typer.Option("--force/--no-force", "-f/-F")] = False):6 if force:7 print("Forcing operation")8 else:9 print("Not forcing")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/parameter_types/bool/tutorial004_an.py+13 added
1import typer2from typing_extensions import Annotated345def main(in_prod: Annotated[bool, typer.Option(" /--demo", " /-d")] = True):6 if in_prod:7 print("Running in production")8 else:9 print("Running demo")101112if __name__ == "__main__":13 typer.run(main)
added:docs_src/parameter_types/datetime/tutorial002_an.py+19 added
1from datetime import datetime23import typer4from typing_extensions import Annotated567def main(8 launch_date: Annotated[9 datetime,10 typer.Argument(11 formats=["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S", "%m/%d/%Y"]12 ),13 ]14):15 print(f"Launch will be at: {launch_date}")161718if __name__ == "__main__":19 typer.run(main)
added:docs_src/parameter_types/enum/tutorial002_an.py+22 added
1from enum import Enum23import typer4from typing_extensions import Annotated567class NeuralNetwork(str, Enum):8 simple = "simple"9 conv = "conv"10 lstm = "lstm"111213def main(14 network: Annotated[15 NeuralNetwork, typer.Option(case_sensitive=False)16 ] = NeuralNetwork.simple17):18 print(f"Training neural network of type: {network.value}")192021if __name__ == "__main__":22 typer.run(main)
added:docs_src/parameter_types/file/tutorial001_an.py+11 added
1import typer2from typing_extensions import Annotated345def main(config: Annotated[typer.FileText, typer.Option()]):6 for line in config:7 print(f"Config line: {line}")8910if __name__ == "__main__":11 typer.run(main)
added:docs_src/parameter_types/file/tutorial002_an.py+11 added
1import typer2from typing_extensions import Annotated345def main(config: Annotated[typer.FileTextWrite, typer.Option()]):6 config.write("Some config written by the app")7 print("Config written")8910if __name__ == "__main__":11 typer.run(main)
added:docs_src/parameter_types/file/tutorial003_an.py+14 added
1import typer2from typing_extensions import Annotated345def main(file: Annotated[typer.FileBinaryRead, typer.Option()]):6 processed_total = 07 for bytes_chunk in file:8 # Process the bytes in bytes_chunk9 processed_total += len(bytes_chunk)10 print(f"Processed bytes total: {processed_total}")111213if __name__ == "__main__":14 typer.run(main)
added:docs_src/parameter_types/file/tutorial004_an.py+18 added
1import typer2from typing_extensions import Annotated345def main(file: Annotated[typer.FileBinaryWrite, typer.Option()]):6 first_line_str = "some settings\n"7 # You cannot write str directly to a binary file, you have to encode it to get bytes8 first_line_bytes = first_line_str.encode("utf-8")9 # Then you can write the bytes10 file.write(first_line_bytes)11 # This is already bytes, it starts with b"12 second_line = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"13 file.write(second_line)14 print("Binary file written")151617if __name__ == "__main__":18 typer.run(main)
added:docs_src/parameter_types/file/tutorial005_an.py+11 added
1import typer2from typing_extensions import Annotated345def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):6 config.write("This is a single line\n")7 print("Config line written")8910if __name__ == "__main__":11 typer.run(main)
added:docs_src/parameter_types/number/tutorial001_an.py+16 added
1import typer2from typing_extensions import Annotated345def main(6 id: Annotated[int, typer.Argument(min=0, max=1000)],7 age: Annotated[int, typer.Option(min=18)] = 20,8 score: Annotated[float, typer.Option(max=100)] = 0,9):10 print(f"ID is {id}")11 print(f"--age is {age}")12 print(f"--score is {score}")131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/parameter_types/number/tutorial002_an.py+16 added
1import typer2from typing_extensions import Annotated345def main(6 id: Annotated[int, typer.Argument(min=0, max=1000)],7 rank: Annotated[int, typer.Option(max=10, clamp=True)] = 0,8 score: Annotated[float, typer.Option(min=0, max=100, clamp=True)] = 0,9):10 print(f"ID is {id}")11 print(f"--rank is {rank}")12 print(f"--score is {score}")131415if __name__ == "__main__":16 typer.run(main)
added:docs_src/parameter_types/number/tutorial003_an.py+10 added
1import typer2from typing_extensions import Annotated345def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):6 print(f"Verbose level is {verbose}")789if __name__ == "__main__":10 typer.run(main)
added:docs_src/parameter_types/path/tutorial001_an.py+22 added
1from pathlib import Path2from typing import Optional34import typer5from typing_extensions import Annotated678def main(config: Annotated[Optional[Path], typer.Option()] = None):9 if config is None:10 print("No config file")11 raise typer.Abort()12 if config.is_file():13 text = config.read_text()14 print(f"Config file contents: {text}")15 elif config.is_dir():16 print("Config is a directory, will use all its config files")17 elif not config.exists():18 print("The config doesn't exist")192021if __name__ == "__main__":22 typer.run(main)
added:docs_src/parameter_types/path/tutorial002_an.py+25 added
1from pathlib import Path23import typer4from typing_extensions import Annotated567def main(8 config: Annotated[9 Path,10 typer.Option(11 exists=True,12 file_okay=True,13 dir_okay=False,14 writable=False,15 readable=True,16 resolve_path=True,17 ),18 ]19):20 text = config.read_text()21 print(f"Config file contents: {text}")222324if __name__ == "__main__":25 typer.run(main)
added:docs_src/testing/app02_an/__init__.py
added:docs_src/testing/app02_an/main.py+13 added
1import typer2from typing_extensions import Annotated34app = typer.Typer()567@app.command()8def main(name: str, email: Annotated[str, typer.Option(prompt=True)]):9 print(f"Hello {name}, your email is: {email}")101112if __name__ == "__main__":13 app()
added:docs_src/testing/app02_an/test_main.py+11 added
1from typer.testing import CliRunner23from .main import app45runner = CliRunner()678def test_app():9 result = runner.invoke(app, ["Camila"], input="camila@example.com\n")10 assert result.exit_code == 011 assert "Hello Camila, your email is: camila@example.com" in result.stdout
added:tests/test_tutorial/test_arguments/test_default/test_tutorial001_an.py+42 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.default import tutorial001_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Arguments" in result.output20 assert "[default: Wade Wilson]" in result.output212223def test_call_no_arg():24 result = runner.invoke(app)25 assert result.exit_code == 0, result.output26 assert "Hello Wade Wilson" in result.output272829def test_call_arg():30 result = runner.invoke(app, ["Camila"])31 assert result.exit_code == 032 assert "Hello Camila" in result.output333435def test_script():36 result = subprocess.run(37 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],38 stdout=subprocess.PIPE,39 stderr=subprocess.PIPE,40 encoding="utf-8",41 )42 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_default/test_tutorial002_an.py+44 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.default import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Arguments" in result.output20 assert "[default: (dynamic)]" in result.output212223def test_call_no_arg():24 greetings = ["Hello Deadpool", "Hello Rick", "Hello Morty", "Hello Hiro"]25 for i in range(3):26 result = runner.invoke(app)27 assert result.exit_code == 028 assert any(greet in result.output for greet in greetings)293031def test_call_arg():32 result = runner.invoke(app, ["Camila"])33 assert result.exit_code == 034 assert "Hello Camila" in result.output353637def test_script():38 result = subprocess.run(39 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],40 stdout=subprocess.PIPE,41 stderr=subprocess.PIPE,42 encoding="utf-8",43 )44 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001_an.py+62 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.arguments.envvar import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "[OPTIONS] [NAME]" in result.output20 assert "Arguments" in result.output21 assert "env var: AWESOME_NAME" in result.output22 assert "default: World" in result.output232425def test_help_no_rich():26 rich = typer.core.rich27 typer.core.rich = None28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "[OPTIONS] [NAME]" in result.output31 assert "Arguments" in result.output32 assert "env var: AWESOME_NAME" in result.output33 assert "default: World" in result.output34 typer.core.rich = rich353637def test_call_arg():38 result = runner.invoke(app, ["Wednesday"])39 assert result.exit_code == 040 assert "Hello Mr. Wednesday" in result.output414243def test_call_env_var():44 result = runner.invoke(app, env={"AWESOME_NAME": "Wednesday"})45 assert result.exit_code == 046 assert "Hello Mr. Wednesday" in result.output474849def test_call_env_var_arg():50 result = runner.invoke(app, ["Czernobog"], env={"AWESOME_NAME": "Wednesday"})51 assert result.exit_code == 052 assert "Hello Mr. Czernobog" in result.output535455def test_script():56 result = subprocess.run(57 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],58 stdout=subprocess.PIPE,59 stderr=subprocess.PIPE,60 encoding="utf-8",61 )62 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_envvar/test_tutorial002_an.py+49 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.envvar import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Arguments" in result.output20 assert "env var: AWESOME_NAME, GOD_NAME" in result.output21 assert "default: World" in result.output222324def test_call_arg():25 result = runner.invoke(app, ["Wednesday"])26 assert result.exit_code == 027 assert "Hello Mr. Wednesday" in result.output282930def test_call_env_var1():31 result = runner.invoke(app, env={"AWESOME_NAME": "Wednesday"})32 assert result.exit_code == 033 assert "Hello Mr. Wednesday" in result.output343536def test_call_env_var2():37 result = runner.invoke(app, env={"GOD_NAME": "Anubis"})38 assert result.exit_code == 039 assert "Hello Mr. Anubis" in result.output404142def test_script():43 result = subprocess.run(44 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],45 stdout=subprocess.PIPE,46 stderr=subprocess.PIPE,47 encoding="utf-8",48 )49 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_envvar/test_tutorial003_an.py+49 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.envvar import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Arguments" in result.output20 assert "env var: AWESOME_NAME" not in result.output21 assert "default: World" in result.output222324def test_call_arg():25 result = runner.invoke(app, ["Wednesday"])26 assert result.exit_code == 027 assert "Hello Mr. Wednesday" in result.output282930def test_call_env_var():31 result = runner.invoke(app, env={"AWESOME_NAME": "Wednesday"})32 assert result.exit_code == 033 assert "Hello Mr. Wednesday" in result.output343536def test_call_env_var_arg():37 result = runner.invoke(app, ["Czernobog"], env={"AWESOME_NAME": "Wednesday"})38 assert result.exit_code == 039 assert "Hello Mr. Czernobog" in result.output404142def test_script():43 result = subprocess.run(44 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],45 stdout=subprocess.PIPE,46 stderr=subprocess.PIPE,47 encoding="utf-8",48 )49 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial001_an.py+52 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.arguments.help import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "[OPTIONS] NAME" in result.output20 assert "Arguments" in result.output21 assert "NAME" in result.output22 assert "The name of the user to greet" in result.output23 assert "[required]" in result.output242526def test_help_no_rich():27 rich = typer.core.rich28 typer.core.rich = None29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "[OPTIONS] NAME" in result.output32 assert "Arguments" in result.output33 assert "NAME" in result.output34 assert "The name of the user to greet" in result.output35 assert "[required]" in result.output36 typer.core.rich = rich373839def test_call_arg():40 result = runner.invoke(app, ["Camila"])41 assert result.exit_code == 042 assert "Hello Camila" in result.output434445def test_script():46 result = subprocess.run(47 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,49 stderr=subprocess.PIPE,50 encoding="utf-8",51 )52 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial002_an.py+39 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] NAME" in result.output19 assert "Say hi to NAME very gently, like Dirk." in result.output20 assert "Arguments" in result.output21 assert "NAME" in result.output22 assert "The name of the user to greet" in result.output23 assert "[required]" in result.output242526def test_call_arg():27 result = runner.invoke(app, ["Camila"])28 assert result.exit_code == 029 assert "Hello Camila" in result.output303132def test_script():33 result = subprocess.run(34 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial003_an.py+39 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Say hi to NAME very gently, like Dirk." in result.output20 assert "Arguments" in result.output21 assert "NAME" in result.output22 assert "Who to greet" in result.output23 assert "[default: World]" in result.output242526def test_call_arg():27 result = runner.invoke(app, ["Camila"])28 assert result.exit_code == 029 assert "Hello Camila" in result.output303132def test_script():33 result = subprocess.run(34 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial004_an.py+39 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial004_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Say hi to NAME very gently, like Dirk." in result.output20 assert "Arguments" in result.output21 assert "NAME" in result.output22 assert "Who to greet" in result.output23 assert "[default: World]" not in result.output242526def test_call_arg():27 result = runner.invoke(app, ["Camila"])28 assert result.exit_code == 029 assert "Hello Camila" in result.output303132def test_script():33 result = subprocess.run(34 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial005_an.py+37 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial005_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output19 assert "Arguments" in result.output20 assert "Who to greet" in result.output21 assert "[default: (Deadpoolio the amazing's name)]" in result.output222324def test_call_arg():25 result = runner.invoke(app, ["Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_script():31 result = subprocess.run(32 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],33 stdout=subprocess.PIPE,34 stderr=subprocess.PIPE,35 encoding="utf-8",36 )37 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial006_an.py+37 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.help import tutorial006_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] ✨username✨" in result.output19 assert "Arguments" in result.output20 assert "✨username✨" in result.output21 assert "[default: World]" in result.output222324def test_call_arg():25 result = runner.invoke(app, ["Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_script():31 result = subprocess.run(32 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],33 stdout=subprocess.PIPE,34 stderr=subprocess.PIPE,35 encoding="utf-8",36 )37 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial007_an.py+37 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.arguments.help import tutorial007_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "Say hi to NAME very gently, like Dirk." in result.output20 assert "Arguments" in result.output21 assert "Secondary Arguments" in result.output222324def test_call_arg():25 result = runner.invoke(app, ["Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_script():31 result = subprocess.run(32 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],33 stdout=subprocess.PIPE,34 stderr=subprocess.PIPE,35 encoding="utf-8",36 )37 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_help/test_tutorial008_an.py+50 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.arguments.help import tutorial008_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "[OPTIONS] [NAME]" in result.output20 assert "Say hi to NAME very gently, like Dirk." in result.output21 assert "Arguments" not in result.output22 assert "[default: World]" not in result.output232425def test_help_no_rich():26 rich = typer.core.rich27 typer.core.rich = None28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "[OPTIONS] [NAME]" in result.output31 assert "Say hi to NAME very gently, like Dirk." in result.output32 assert "Arguments" not in result.output33 assert "[default: World]" not in result.output34 typer.core.rich = rich353637def test_call_arg():38 result = runner.invoke(app, ["Camila"])39 assert result.exit_code == 040 assert "Hello Camila" in result.output414243def test_script():44 result = subprocess.run(45 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],46 stdout=subprocess.PIPE,47 stderr=subprocess.PIPE,48 encoding="utf-8",49 )50 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_optional/test_tutorial001_an.py+51 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.arguments.optional import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_call_no_arg():17 result = runner.invoke(app)18 assert result.exit_code != 019 assert "Missing argument 'NAME'." in result.output202122def test_call_no_arg_standalone():23 # Mainly for coverage24 result = runner.invoke(app, standalone_mode=False)25 assert result.exit_code != 0262728def test_call_no_arg_no_rich():29 # Mainly for coverage30 rich = typer.core.rich31 typer.core.rich = None32 result = runner.invoke(app)33 assert result.exit_code != 034 assert "Error: Missing argument 'NAME'" in result.stdout35 typer.core.rich = rich363738def test_call_arg():39 result = runner.invoke(app, ["Camila"])40 assert result.exit_code == 041 assert "Hello Camila" in result.output424344def test_script():45 result = subprocess.run(46 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],47 stdout=subprocess.PIPE,48 stderr=subprocess.PIPE,49 encoding="utf-8",50 )51 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_optional/test_tutorial002_an.py+40 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.arguments.optional import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "[OPTIONS] [NAME]" in result.output192021def test_call_no_arg():22 result = runner.invoke(app)23 assert result.exit_code == 024 assert "Hello World!" in result.output252627def test_call_arg():28 result = runner.invoke(app, ["Camila"])29 assert result.exit_code == 030 assert "Hello Camila" in result.output313233def test_script():34 result = subprocess.run(35 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],36 stdout=subprocess.PIPE,37 stderr=subprocess.PIPE,38 encoding="utf-8",39 )40 assert "Usage" in result.stdout
added:tests/test_tutorial/test_arguments/test_optional/test_tutorial003.py+51 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.arguments.optional import tutorial003 as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_call_no_arg():17 result = runner.invoke(app)18 assert result.exit_code != 019 assert "Missing argument 'NAME'." in result.output202122def test_call_no_arg_standalone():23 # Mainly for coverage24 result = runner.invoke(app, standalone_mode=False)25 assert result.exit_code != 0262728def test_call_no_arg_no_rich():29 # Mainly for coverage30 rich = typer.core.rich31 typer.core.rich = None32 result = runner.invoke(app)33 assert result.exit_code != 034 assert "Error: Missing argument 'NAME'" in result.stdout35 typer.core.rich = rich363738def test_call_arg():39 result = runner.invoke(app, ["Camila"])40 assert result.exit_code == 041 assert "Hello Camila" in result.output424344def test_script():45 result = subprocess.run(46 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],47 stdout=subprocess.PIPE,48 stderr=subprocess.PIPE,49 encoding="utf-8",50 )51 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial001_an.py+126 added
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.commands.help import tutorial001_an as mod78app = mod.app910runner = CliRunner()111213def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "Awesome CLI user manager." in result.output17 assert "create" in result.output18 assert "Create a new user with USERNAME." in result.output19 assert "delete" in result.output20 assert "Delete a user with USERNAME." in result.output21 assert "delete-all" in result.output22 assert "Delete ALL users in the database." in result.output23 assert "init" in result.output24 assert "Initialize the users database." in result.output252627def test_help_create():28 result = runner.invoke(app, ["create", "--help"])29 assert result.exit_code == 030 assert "create [OPTIONS] USERNAME" in result.output31 assert "Create a new user with USERNAME." in result.output323334def test_help_delete():35 result = runner.invoke(app, ["delete", "--help"])36 assert result.exit_code == 037 assert "delete [OPTIONS] USERNAME" in result.output38 assert "Delete a user with USERNAME." in result.output39 assert "--force" in result.output40 assert "--no-force" in result.output41 assert "Force deletion without confirmation." in result.output424344def test_help_delete_all():45 result = runner.invoke(app, ["delete-all", "--help"])46 assert result.exit_code == 047 assert "delete-all [OPTIONS]" in result.output48 assert "Delete ALL users in the database." in result.output49 assert "If --force is not used, will ask for confirmation." in result.output50 assert "[required]" in result.output51 assert "--force" in result.output52 assert "--no-force" in result.output53 assert "Force deletion without confirmation." in result.output545556def test_help_init():57 result = runner.invoke(app, ["init", "--help"])58 assert result.exit_code == 059 assert "init [OPTIONS]" in result.output60 assert "Initialize the users database." in result.output616263def test_create():64 result = runner.invoke(app, ["create", "Camila"])65 assert result.exit_code == 066 assert "Creating user: Camila" in result.output676869def test_delete():70 result = runner.invoke(app, ["delete", "Camila"], input="y\n")71 assert result.exit_code == 072 # TODO: when deprecating Click 7, remove second option73 assert (74 "Are you sure you want to delete the user? [y/n]:" in result.output75 or "Are you sure you want to delete the user? [y/N]:" in result.output76 )77 assert "Deleting user: Camila" in result.output787980def test_no_delete():81 result = runner.invoke(app, ["delete", "Camila"], input="n\n")82 assert result.exit_code == 083 # TODO: when deprecating Click 7, remove second option84 assert (85 "Are you sure you want to delete the user? [y/n]:" in result.output86 or "Are you sure you want to delete the user? [y/N]:" in result.output87 )88 assert "Operation cancelled" in result.output899091def test_delete_all():92 result = runner.invoke(app, ["delete-all"], input="y\n")93 assert result.exit_code == 094 # TODO: when deprecating Click 7, remove second option95 assert (96 "Are you sure you want to delete ALL users? [y/n]:" in result.output97 or "Are you sure you want to delete ALL users? [y/N]:" in result.output98 )99 assert "Deleting all users" in result.output100101102def test_no_delete_all():103 result = runner.invoke(app, ["delete-all"], input="n\n")104 assert result.exit_code == 0105 # TODO: when deprecating Click 7, remove second option106 assert (107 "Are you sure you want to delete ALL users? [y/n]:" in result.output108 or "Are you sure you want to delete ALL users? [y/N]:" in result.output109 )110 assert "Operation cancelled" in result.output111112113def test_init():114 result = runner.invoke(app, ["init"])115 assert result.exit_code == 0116 assert "Initializing user database" in result.output117118119def test_script():120 result = subprocess.run(121 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],122 stdout=subprocess.PIPE,123 stderr=subprocess.PIPE,124 encoding="utf-8",125 )126 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial004_an.py+60 added
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.commands.help import tutorial004_an as mod78app = mod.app910runner = CliRunner()111213def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "create" in result.output17 assert "Create a new shinny user. ✨" in result.output18 assert "delete" in result.output19 assert "Delete a user with USERNAME." in result.output20 assert "Some internal utility function to create." not in result.output21 assert "Some internal utility function to delete." not in result.output222324def test_help_create():25 result = runner.invoke(app, ["create", "--help"])26 assert result.exit_code == 027 assert "Create a new shinny user. ✨" in result.output28 assert "The username to be created" in result.output29 assert "Some internal utility function to create." not in result.output303132def test_help_delete():33 result = runner.invoke(app, ["delete", "--help"])34 assert result.exit_code == 035 assert "Delete a user with USERNAME." in result.output36 assert "The username to be deleted" in result.output37 assert "Force the deletion 💥" in result.output38 assert "Some internal utility function to delete." not in result.output394041def test_create():42 result = runner.invoke(app, ["create", "Camila"])43 assert result.exit_code == 044 assert "Creating user: Camila" in result.output454647def test_delete():48 result = runner.invoke(app, ["delete", "Camila"])49 assert result.exit_code == 050 assert "Deleting user: Camila" in result.output515253def test_script():54 result = subprocess.run(55 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],56 stdout=subprocess.PIPE,57 stderr=subprocess.PIPE,58 encoding="utf-8",59 )60 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial005_an.py+61 added
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.commands.help import tutorial005_an as mod78app = mod.app910runner = CliRunner()111213def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "create" in result.output17 assert "Create a new shinny user. ✨" in result.output18 assert "delete" in result.output19 assert "Delete a user with USERNAME." in result.output20 assert "Some internal utility function to create." not in result.output21 assert "Some internal utility function to delete." not in result.output222324def test_help_create():25 result = runner.invoke(app, ["create", "--help"])26 assert result.exit_code == 027 assert "Create a new shinny user. ✨" in result.output28 assert "The username to be created" in result.output29 assert "Learn more at the Typer docs website" in result.output30 assert "Some internal utility function to create." not in result.output313233def test_help_delete():34 result = runner.invoke(app, ["delete", "--help"])35 assert result.exit_code == 036 assert "Delete a user with USERNAME." in result.output37 assert "The username to be deleted" in result.output38 assert "Force the deletion 💥" in result.output39 assert "Some internal utility function to delete." not in result.output404142def test_create():43 result = runner.invoke(app, ["create", "Camila"])44 assert result.exit_code == 045 assert "Creating user: Camila" in result.output464748def test_delete():49 result = runner.invoke(app, ["delete", "Camila"])50 assert result.exit_code == 051 assert "Deleting user: Camila" in result.output525354def test_script():55 result = subprocess.run(56 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],57 stdout=subprocess.PIPE,58 stderr=subprocess.PIPE,59 encoding="utf-8",60 )61 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_help/test_tutorial007_an.py+56 added
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.commands.help import tutorial007_an as mod78app = mod.app910runner = CliRunner()111213def test_main_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "create" in result.output17 assert "Create a new user. ✨" in result.output18 assert "Utils and Configs" in result.output19 assert "config" in result.output20 assert "Configure the system. 🔧" in result.output212223def test_create_help():24 result = runner.invoke(app, ["create", "--help"])25 assert result.exit_code == 026 assert "username" in result.output27 assert "The username to create" in result.output28 assert "Secondary Arguments" in result.output29 assert "lastname" in result.output30 assert "The last name of the new user" in result.output31 assert "--force" in result.output32 assert "--no-force" in result.output33 assert "Force the creation of the user" in result.output34 assert "Additional Data" in result.output35 assert "--age" in result.output36 assert "The age of the new user" in result.output37 assert "--favorite-color" in result.output38 assert "The favorite color of the new user" in result.output394041def test_call():42 # Mainly for coverage43 result = runner.invoke(app, ["create", "Morty"])44 assert result.exit_code == 045 result = runner.invoke(app, ["config", "Morty"])46 assert result.exit_code == 0474849def test_script():50 result = subprocess.run(51 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],52 stdout=subprocess.PIPE,53 stderr=subprocess.PIPE,54 encoding="utf-8",55 )56 assert "Usage" in result.stdout
added:tests/test_tutorial/test_commands/test_options/test_tutorial001_an.py+97 added
1import subprocess2import sys34from typer.testing import CliRunner56from docs_src.commands.options import tutorial001_an as mod78app = mod.app910runner = CliRunner()111213def test_help():14 result = runner.invoke(app, ["--help"])15 assert result.exit_code == 016 assert "Commands" in result.output17 assert "create" in result.output18 assert "delete" in result.output19 assert "delete-all" in result.output20 assert "init" in result.output212223def test_create():24 result = runner.invoke(app, ["create", "Camila"])25 assert result.exit_code == 026 assert "Creating user: Camila" in result.output272829def test_delete():30 result = runner.invoke(app, ["delete", "Camila"], input="y\n")31 assert result.exit_code == 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Are you sure you want to delete the user? [y/n]:" in result.output35 or "Are you sure you want to delete the user? [y/N]:" in result.output36 )37 assert "Deleting user: Camila" in result.output383940def test_no_delete():41 result = runner.invoke(app, ["delete", "Camila"], input="n\n")42 assert result.exit_code == 043 # TODO: when deprecating Click 7, remove second option44 assert (45 "Are you sure you want to delete the user? [y/n]:" in result.output46 or "Are you sure you want to delete the user? [y/N]:" in result.output47 )48 assert "Operation cancelled" in result.output495051def test_delete_all():52 result = runner.invoke(app, ["delete-all"], input="y\n")53 assert result.exit_code == 054 # TODO: when deprecating Click 7, remove second option55 assert (56 "Are you sure you want to delete ALL users? [y/n]:" in result.output57 or "Are you sure you want to delete ALL users? [y/N]:" in result.output58 )59 assert "Deleting all users" in result.output606162def test_no_delete_all():63 result = runner.invoke(app, ["delete-all"], input="n\n")64 assert result.exit_code == 065 # TODO: when deprecating Click 7, remove second option66 assert (67 "Are you sure you want to delete ALL users? [y/n]:" in result.output68 or "Are you sure you want to delete ALL users? [y/N]:" in result.output69 )70 assert "Operation cancelled" in result.output717273def test_delete_all_force():74 result = runner.invoke(app, ["delete-all", "--force"])75 assert result.exit_code == 076 # TODO: when deprecating Click 7, remove second option77 assert (78 "Are you sure you want to delete ALL users? [y/n]:" not in result.output79 or "Are you sure you want to delete ALL users? [y/N]:" not in result.output80 )81 assert "Deleting all users" in result.output828384def test_init():85 result = runner.invoke(app, ["init"])86 assert result.exit_code == 087 assert "Initializing user database" in result.output888990def test_script():91 result = subprocess.run(92 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],93 stdout=subprocess.PIPE,94 stderr=subprocess.PIPE,95 encoding="utf-8",96 )97 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002_an.py+58 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.multiple_values.arguments_with_multiple_values import (8 tutorial002_an as mod,9)1011runner = CliRunner()12app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "[OPTIONS] [NAMES]..." in result.output20 assert "Arguments" in result.output21 assert "[default: Harry, Hermione, Ron]" in result.output222324def test_defaults():25 result = runner.invoke(app)26 assert result.exit_code == 027 assert "Hello Harry" in result.output28 assert "Hello Hermione" in result.output29 assert "Hello Ron" in result.output303132def test_invalid_args():33 result = runner.invoke(app, ["Draco", "Hagrid"])34 assert result.exit_code != 035 # TODO: when deprecating Click 7, remove second option3637 assert (38 "Argument 'names' takes 3 values" in result.stdout39 or "argument names takes 3 values" in result.stdout40 )414243def test_valid_args():44 result = runner.invoke(app, ["Draco", "Hagrid", "Dobby"])45 assert result.exit_code == 046 assert "Hello Draco" in result.stdout47 assert "Hello Hagrid" in result.stdout48 assert "Hello Dobby" in result.stdout495051def test_script():52 result = subprocess.run(53 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],54 stdout=subprocess.PIPE,55 stderr=subprocess.PIPE,56 encoding="utf-8",57 )58 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial001_an.py+44 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.multiple_values.multiple_options import tutorial001_an as mod89runner = CliRunner()10app = typer.Typer()11app.command()(mod.main)121314def test_main():15 result = runner.invoke(app)16 assert result.exit_code != 017 assert "No provided users" in result.output18 assert "Aborted" in result.output192021def test_1_user():22 result = runner.invoke(app, ["--user", "Camila"])23 assert result.exit_code == 024 assert "Processing user: Camila" in result.output252627def test_3_user():28 result = runner.invoke(29 app, ["--user", "Camila", "--user", "Rick", "--user", "Morty"]30 )31 assert result.exit_code == 032 assert "Processing user: Camila" in result.output33 assert "Processing user: Rick" in result.output34 assert "Processing user: Morty" in result.output353637def test_script():38 result = subprocess.run(39 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],40 stdout=subprocess.PIPE,41 stderr=subprocess.PIPE,42 encoding="utf-8",43 )44 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial002_an.py+39 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.multiple_values.multiple_options import tutorial002_an as mod89runner = CliRunner()10app = typer.Typer()11app.command()(mod.main)121314def test_main():15 result = runner.invoke(app)16 assert result.exit_code == 017 assert "The sum is 0" in result.output181920def test_1_number():21 result = runner.invoke(app, ["--number", "2"])22 assert result.exit_code == 023 assert "The sum is 2.0" in result.output242526def test_2_number():27 result = runner.invoke(app, ["--number", "2", "--number", "3", "--number", "4.5"])28 assert result.exit_code == 029 assert "The sum is 9.5" in result.output303132def test_script():33 result = subprocess.run(34 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],35 stdout=subprocess.PIPE,36 stderr=subprocess.PIPE,37 encoding="utf-8",38 )39 assert "Usage" in result.stdout
added:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001_an.py+53 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.multiple_values.options_with_multiple_values import tutorial001_an as mod89runner = CliRunner()10app = typer.Typer()11app.command()(mod.main)121314def test_main():15 result = runner.invoke(app)16 assert result.exit_code != 017 assert "No user provided" in result.output18 assert "Aborted" in result.output192021def test_user_1():22 result = runner.invoke(app, ["--user", "Camila", "50", "yes"])23 assert result.exit_code == 024 assert "The username Camila has 50 coins" in result.output25 assert "And this user is a wizard!" in result.output262728def test_user_2():29 result = runner.invoke(app, ["--user", "Morty", "3", "no"])30 assert result.exit_code == 031 assert "The username Morty has 3 coins" in result.output32 assert "And this user is a wizard!" not in result.output333435def test_invalid_user():36 result = runner.invoke(app, ["--user", "Camila", "50"])37 assert result.exit_code != 038 # TODO: when deprecating Click 7, remove second option3940 assert (41 "Option '--user' requires 3 arguments" in result.output42 or "--user option requires 3 arguments" in result.output43 )444546def test_script():47 result = subprocess.run(48 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],49 stdout=subprocess.PIPE,50 stderr=subprocess.PIPE,51 encoding="utf-8",52 )53 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_callback/test_tutorial001_an.py+34 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.callback import tutorial001_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_1():16 result = runner.invoke(app, ["--name", "Camila"])17 assert result.exit_code == 018 assert "Hello Camila" in result.output192021def test_2():22 result = runner.invoke(app, ["--name", "rick"])23 assert result.exit_code != 024 assert "Invalid value for '--name': Only Camila is allowed" in result.output252627def test_script():28 result = subprocess.run(29 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],30 stdout=subprocess.PIPE,31 stderr=subprocess.PIPE,32 encoding="utf-8",33 )34 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_callback/test_tutorial003_an.py+53 added
1import os2import subprocess3import sys45import typer6from typer.testing import CliRunner78from docs_src.options.callback import tutorial003_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_1():17 result = runner.invoke(app, ["--name", "Camila"])18 assert result.exit_code == 019 assert "Validating name" in result.output20 assert "Hello Camila" in result.output212223def test_2():24 result = runner.invoke(app, ["--name", "rick"])25 assert result.exit_code != 026 assert "Invalid value for '--name': Only Camila is allowed" in result.output272829def test_script():30 result = subprocess.run(31 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout373839def test_completion():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 env={46 **os.environ,47 "_TUTORIAL003_AN.PY_COMPLETE": "complete_bash",48 "COMP_WORDS": "tutorial003_an.py --",49 "COMP_CWORD": "1",50 "_TYPER_COMPLETE_TESTING": "True",51 },52 )53 assert "--name" in result.stdout
added:tests/test_tutorial/test_options/test_callback/test_tutorial004_an.py+53 added
1import os2import subprocess3import sys45import typer6from typer.testing import CliRunner78from docs_src.options.callback import tutorial004_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_1():17 result = runner.invoke(app, ["--name", "Camila"])18 assert result.exit_code == 019 assert "Validating param: name" in result.output20 assert "Hello Camila" in result.output212223def test_2():24 result = runner.invoke(app, ["--name", "rick"])25 assert result.exit_code != 026 assert "Invalid value for '--name': Only Camila is allowed" in result.output272829def test_script():30 result = subprocess.run(31 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout373839def test_completion():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 env={46 **os.environ,47 "_TUTORIAL004_AN.PY_COMPLETE": "complete_bash",48 "COMP_WORDS": "tutorial004_an.py --",49 "COMP_CWORD": "1",50 "_TYPER_COMPLETE_TESTING": "True",51 },52 )53 assert "--name" in result.stdout
added:tests/test_tutorial/test_options/test_help/test_tutorial001_an.py+49 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.help import tutorial001_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "Say hi to NAME, optionally with a --lastname." in result.output19 assert "If --formal is used, say hi very formally." in result.output20 assert "Last name of person to greet." in result.output21 assert "Say hi formally." in result.output222324def test_1():25 result = runner.invoke(app, ["Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_option_lastname():31 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])32 assert result.exit_code == 033 assert "Hello Camila Gutiérrez" in result.output343536def test_formal():37 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez", "--formal"])38 assert result.exit_code == 039 assert "Good day Ms. Camila Gutiérrez." in result.output404142def test_script():43 result = subprocess.run(44 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],45 stdout=subprocess.PIPE,46 stderr=subprocess.PIPE,47 encoding="utf-8",48 )49 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_help/test_tutorial002_an.py+45 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.help import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_call():16 result = runner.invoke(app, ["World"])17 assert result.exit_code == 018 assert "Hello World" in result.output192021def test_formal():22 result = runner.invoke(app, ["World", "--formal"])23 assert result.exit_code == 024 assert "Good day Ms. World" in result.output252627def test_help():28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "--lastname" in result.output31 assert "Customization and Utils" in result.output32 assert "--formal" in result.output33 assert "--no-formal" in result.output34 assert "--debug" in result.output35 assert "--no-debug" in result.output363738def test_script():39 result = subprocess.run(40 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],41 stdout=subprocess.PIPE,42 stderr=subprocess.PIPE,43 encoding="utf-8",44 )45 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_help/test_tutorial003_an.py+36 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.help import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_call():16 result = runner.invoke(app)17 assert result.exit_code == 018 assert "Hello Wade Wilson" in result.output192021def test_help():22 result = runner.invoke(app, ["--help"])23 assert result.exit_code == 024 assert "--fullname" in result.output25 assert "TEXT" in result.output26 assert "[default: Wade Wilson]" not in result.output272829def test_script():30 result = subprocess.run(31 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_name/test_tutorial001_an.py+46 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.name import tutorial001_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "--name" in result.output19 assert "TEXT" in result.output20 assert "--user-name" not in result.output212223def test_call():24 result = runner.invoke(app, ["--name", "Camila"])25 assert result.exit_code == 026 assert "Hello Camila" in result.output272829def test_call_no_args():30 result = runner.invoke(app, ["--name"])31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Option '--name' requires an argument" in result.output35 or "--name option requires an argument" in result.output36 )373839def test_script():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
modified:tests/test_tutorial/test_options/test_name/test_tutorial001.py+10 added
24 unmodified lines
25 assert result.exit_code == 026 assert "Hello Camila" in result.output272829def test_call_no_args():30 result = runner.invoke(app, ["--name"])31 assert result.exit_code != 032 # TODO: when deprecating Click 7, remove second option33 assert (34 "Option '--name' requires an argument" in result.output35 or "--name option requires an argument" in result.output36 )373839def test_script():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,
4 unmodified lines
added:tests/test_tutorial/test_options/test_name/test_tutorial002_an.py+43 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.name import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "-n" in result.output19 assert "--name" in result.output20 assert "TEXT" in result.output21 assert "--user-name" not in result.output222324def test_call():25 result = runner.invoke(app, ["-n", "Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_call_long():31 result = runner.invoke(app, ["--name", "Camila"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_name/test_tutorial003_an.py+37 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.name import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "-n" in result.output19 assert "TEXT" in result.output20 assert "--user-name" not in result.output21 assert "--name" not in result.output222324def test_call():25 result = runner.invoke(app, ["-n", "Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_script():31 result = subprocess.run(32 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],33 stdout=subprocess.PIPE,34 stderr=subprocess.PIPE,35 encoding="utf-8",36 )37 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_name/test_tutorial004_an.py+43 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.name import tutorial004_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "-n" in result.output19 assert "--user-name" in result.output20 assert "TEXT" in result.output21 assert "--name" not in result.output222324def test_call():25 result = runner.invoke(app, ["-n", "Camila"])26 assert result.exit_code == 027 assert "Hello Camila" in result.output282930def test_call_long():31 result = runner.invoke(app, ["--user-name", "Camila"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_name/test_tutorial005_an.py+55 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.name import tutorial005_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "-n" in result.output19 assert "--name" in result.output20 assert "TEXT" in result.output21 assert "-f" in result.output22 assert "--formal" in result.output232425def test_call():26 result = runner.invoke(app, ["-n", "Camila"])27 assert result.exit_code == 028 assert "Hello Camila" in result.output293031def test_call_formal():32 result = runner.invoke(app, ["-n", "Camila", "-f"])33 assert result.exit_code == 034 assert "Good day Ms. Camila." in result.output353637def test_call_formal_condensed():38 result = runner.invoke(app, ["-fn", "Camila"])39 assert result.exit_code == 040 assert "Good day Ms. Camila." in result.output414243def test_call_condensed_wrong_order():44 result = runner.invoke(app, ["-nf", "Camila"])45 assert result.exit_code != 0464748def test_script():49 result = subprocess.run(50 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],51 stdout=subprocess.PIPE,52 stderr=subprocess.PIPE,53 encoding="utf-8",54 )55 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_prompt/test_tutorial001_an.py+43 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.prompt import tutorial001_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_lastname():16 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])17 assert result.exit_code == 018 assert "Hello Camila Gutiérrez" in result.output192021def test_option_lastname_prompt():22 result = runner.invoke(app, ["Camila"], input="Gutiérrez")23 assert result.exit_code == 024 assert "Lastname: " in result.output25 assert "Hello Camila Gutiérrez" in result.output262728def test_help():29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "--lastname" in result.output32 assert "TEXT" in result.output33 assert "[required]" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_prompt/test_tutorial002_an.py+43 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.prompt import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_option_lastname():16 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])17 assert result.exit_code == 018 assert "Hello Camila Gutiérrez" in result.output192021def test_option_lastname_prompt():22 result = runner.invoke(app, ["Camila"], input="Gutiérrez")23 assert result.exit_code == 024 assert "Please tell me your last name: " in result.output25 assert "Hello Camila Gutiérrez" in result.output262728def test_help():29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "--lastname" in result.output32 assert "TEXT" in result.output33 assert "[required]" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_prompt/test_tutorial003_an.py+57 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.options.prompt import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_prompt():16 result = runner.invoke(app, input="Old Project\nOld Project\n")17 assert result.exit_code == 018 assert "Deleting project Old Project" in result.output192021def test_prompt_not_equal():22 result = runner.invoke(23 app, input="Old Project\nNew Spice\nOld Project\nOld Project\n"24 )25 assert result.exit_code == 026 # TODO: when deprecating Click 7, remove second option2728 assert (29 "Error: The two entered values do not match" in result.output30 or "Error: the two entered values do not match" in result.output31 )32 assert "Deleting project Old Project" in result.output333435def test_option():36 result = runner.invoke(app, ["--project-name", "Old Project"])37 assert result.exit_code == 038 assert "Deleting project Old Project" in result.output39 assert "Project name: " not in result.output404142def test_help():43 result = runner.invoke(app, ["--help"])44 assert result.exit_code == 045 assert "--project-name" in result.output46 assert "TEXT" in result.output47 assert "[required]" in result.output484950def test_script():51 result = subprocess.run(52 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],53 stdout=subprocess.PIPE,54 stderr=subprocess.PIPE,55 encoding="utf-8",56 )57 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_required/test_tutorial001_an.py+54 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.options.required import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_1():17 result = runner.invoke(app, ["Camila"])18 assert result.exit_code != 019 assert "Missing option '--lastname'." in result.output202122def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])24 assert result.exit_code == 025 assert "Hello Camila Gutiérrez" in result.output262728def test_help():29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "--lastname" in result.output32 assert "TEXT" in result.output33 assert "[required]" in result.output343536def test_help_no_rich():37 rich = typer.core.rich38 typer.core.rich = None39 result = runner.invoke(app, ["--help"])40 assert result.exit_code == 041 assert "--lastname" in result.output42 assert "TEXT" in result.output43 assert "[required]" in result.output44 typer.core.rich = rich454647def test_script():48 result = subprocess.run(49 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],50 stdout=subprocess.PIPE,51 stderr=subprocess.PIPE,52 encoding="utf-8",53 )54 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_required/test_tutorial001.py+54 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.options.required import tutorial001 as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_1():17 result = runner.invoke(app, ["Camila"])18 assert result.exit_code != 019 assert "Missing option '--lastname'." in result.output202122def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])24 assert result.exit_code == 025 assert "Hello Camila Gutiérrez" in result.output262728def test_help():29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "--lastname" in result.output32 assert "TEXT" in result.output33 assert "[required]" in result.output343536def test_help_no_rich():37 rich = typer.core.rich38 typer.core.rich = None39 result = runner.invoke(app, ["--help"])40 assert result.exit_code == 041 assert "--lastname" in result.output42 assert "TEXT" in result.output43 assert "[required]" in result.output44 typer.core.rich = rich454647def test_script():48 result = subprocess.run(49 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],50 stdout=subprocess.PIPE,51 stderr=subprocess.PIPE,52 encoding="utf-8",53 )54 assert "Usage" in result.stdout
deleted:tests/test_tutorial/test_options/test_required/test_tutorial002.py-54 removed
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.options.required import tutorial001 as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_1():17 result = runner.invoke(app, ["Camila"])18 assert result.exit_code != 019 assert "Missing option '--lastname'." in result.output202122def test_option_lastname():23 result = runner.invoke(app, ["Camila", "--lastname", "Gutiérrez"])24 assert result.exit_code == 025 assert "Hello Camila Gutiérrez" in result.output262728def test_help():29 result = runner.invoke(app, ["--help"])30 assert result.exit_code == 031 assert "--lastname" in result.output32 assert "TEXT" in result.output33 assert "[required]" in result.output343536def test_help_no_rich():37 rich = typer.core.rich38 typer.core.rich = None39 result = runner.invoke(app, ["--help"])40 assert result.exit_code == 041 assert "--lastname" in result.output42 assert "TEXT" in result.output43 assert "[required]" in result.output44 typer.core.rich = rich454647def test_script():48 result = subprocess.run(49 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],50 stdout=subprocess.PIPE,51 stderr=subprocess.PIPE,52 encoding="utf-8",53 )54 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options/test_version/test_tutorial003_an.py+58 added
1import os2import subprocess3import sys45import typer6from typer.testing import CliRunner78from docs_src.options.version import tutorial003_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_1():17 result = runner.invoke(app, ["--name", "Rick", "--version"])18 assert result.exit_code == 019 assert "Awesome CLI Version: 0.1.0" in result.output202122def test_2():23 result = runner.invoke(app, ["--name", "rick"])24 assert result.exit_code != 025 assert "Invalid value for '--name': Only Camila is allowed" in result.output262728def test_3():29 result = runner.invoke(app, ["--name", "Camila"])30 assert result.exit_code == 031 assert "Hello Camila" in result.output323334def test_script():35 result = subprocess.run(36 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],37 stdout=subprocess.PIPE,38 stderr=subprocess.PIPE,39 encoding="utf-8",40 )41 assert "Usage" in result.stdout424344def test_completion():45 result = subprocess.run(46 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],47 stdout=subprocess.PIPE,48 stderr=subprocess.PIPE,49 encoding="utf-8",50 env={51 **os.environ,52 "_TUTORIAL003_AN.PY_COMPLETE": "complete_bash",53 "COMP_WORDS": "tutorial003_an.py --name Rick --v",54 "COMP_CWORD": "3",55 "_TYPER_COMPLETE_TESTING": "True",56 },57 )58 assert "--version" in result.stdout
added:tests/test_tutorial/test_options_autocompletion/test_tutorial002_an.py+43 added
1import os2import subprocess3import sys45from typer.testing import CliRunner67from docs_src.options_autocompletion import tutorial002_an as mod89runner = CliRunner()101112def test_completion():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 env={19 **os.environ,20 "_TUTORIAL002_AN.PY_COMPLETE": "complete_zsh",21 "_TYPER_COMPLETE_ARGS": "tutorial002_an.py --name ",22 "_TYPER_COMPLETE_TESTING": "True",23 },24 )25 assert "Camila" in result.stdout26 assert "Carlos" in result.stdout27 assert "Sebastian" in result.stdout282930def test_1():31 result = runner.invoke(mod.app, ["--name", "Camila"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options_autocompletion/test_tutorial003_an.py+43 added
1import os2import subprocess3import sys45from typer.testing import CliRunner67from docs_src.options_autocompletion import tutorial003_an as mod89runner = CliRunner()101112def test_completion():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 env={19 **os.environ,20 "_TUTORIAL003_AN.PY_COMPLETE": "complete_zsh",21 "_TYPER_COMPLETE_ARGS": "tutorial003_an.py --name Seb",22 "_TYPER_COMPLETE_TESTING": "True",23 },24 )25 assert "Camila" not in result.stdout26 assert "Carlos" not in result.stdout27 assert "Sebastian" in result.stdout282930def test_1():31 result = runner.invoke(mod.app, ["--name", "Camila"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options_autocompletion/test_tutorial004_an.py+43 added
1import os2import subprocess3import sys45from typer.testing import CliRunner67from docs_src.options_autocompletion import tutorial004_an as mod89runner = CliRunner()101112def test_completion():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 env={19 **os.environ,20 "_TUTORIAL004_AN.PY_COMPLETE": "complete_zsh",21 "_TYPER_COMPLETE_ARGS": "tutorial004_an_aux.py --name ",22 "_TYPER_COMPLETE_TESTING": "True",23 },24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' in result.stdout282930def test_1():31 result = runner.invoke(mod.app, ["--name", "Camila"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options_autocompletion/test_tutorial007_an.py+44 added
1import os2import subprocess3import sys45from typer.testing import CliRunner67from docs_src.options_autocompletion import tutorial007_an as mod89runner = CliRunner()101112def test_completion():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 env={19 **os.environ,20 "_TUTORIAL007_AN.PY_COMPLETE": "complete_zsh",21 "_TYPER_COMPLETE_ARGS": "tutorial007_an.py --name Sebastian --name ",22 "_TYPER_COMPLETE_TESTING": "True",23 },24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' not in result.stdout282930def test_1():31 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])32 assert result.exit_code == 033 assert "Hello Camila" in result.output34 assert "Hello Sebastian" in result.output353637def test_script():38 result = subprocess.run(39 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],40 stdout=subprocess.PIPE,41 stderr=subprocess.PIPE,42 encoding="utf-8",43 )44 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options_autocompletion/test_tutorial008_an.py+46 added
1import os2import subprocess3import sys45from typer.testing import CliRunner67from docs_src.options_autocompletion import tutorial008_an as mod89runner = CliRunner()101112def test_completion():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 env={19 **os.environ,20 "_TUTORIAL008_AN.PY_COMPLETE": "complete_zsh",21 "_TYPER_COMPLETE_ARGS": "tutorial008_an.py --name ",22 "_TYPER_COMPLETE_TESTING": "True",23 },24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' in result.stdout28 # TODO: when deprecating Click 7, remove second option29 assert "[]" in result.stderr or "['--name']" in result.stderr303132def test_1():33 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])34 assert result.exit_code == 035 assert "Hello Camila" in result.output36 assert "Hello Sebastian" in result.output373839def test_script():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
added:tests/test_tutorial/test_options_autocompletion/test_tutorial009_an.py+46 added
1import os2import subprocess3import sys45from typer.testing import CliRunner67from docs_src.options_autocompletion import tutorial009_an as mod89runner = CliRunner()101112def test_completion():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, " "],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 env={19 **os.environ,20 "_TUTORIAL009_AN.PY_COMPLETE": "complete_zsh",21 "_TYPER_COMPLETE_ARGS": "tutorial009_an.py --name Sebastian --name ",22 "_TYPER_COMPLETE_TESTING": "True",23 },24 )25 assert '"Camila":"The reader of books."' in result.stdout26 assert '"Carlos":"The writer of scripts."' in result.stdout27 assert '"Sebastian":"The type hints guy."' not in result.stdout28 # TODO: when deprecating Click 7, remove second option29 assert "[]" in result.stderr or "['--name', 'Sebastian', '--name']" in result.stderr303132def test_1():33 result = runner.invoke(mod.app, ["--name", "Camila", "--name", "Sebastian"])34 assert result.exit_code == 035 assert "Hello Camila" in result.output36 assert "Hello Sebastian" in result.output373839def test_script():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,43 stderr=subprocess.PIPE,44 encoding="utf-8",45 )46 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001_an.py+52 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.bool import tutorial001_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "--force" in result.output19 assert "--no-force" not in result.output202122def test_no_force():23 result = runner.invoke(app)24 assert result.exit_code == 025 assert "Not forcing" in result.output262728def test_force():29 result = runner.invoke(app, ["--force"])30 assert result.exit_code == 031 assert "Forcing operation" in result.output323334def test_invalid_no_force():35 result = runner.invoke(app, ["--no-force"])36 assert result.exit_code != 037 # TODO: when deprecating Click 7, remove second option3839 assert (40 "No such option: --no-force" in result.output41 or "no such option: --no-force" in result.output42 )434445def test_script():46 result = subprocess.run(47 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],48 stdout=subprocess.PIPE,49 stderr=subprocess.PIPE,50 encoding="utf-8",51 )52 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002_an.py+71 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.parameter_types.bool import tutorial002_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "--accept" in result.output20 assert "--reject" in result.output21 assert "--no-accept" not in result.output222324def test_help_no_rich():25 rich = typer.core.rich26 typer.core.rich = None27 result = runner.invoke(app, ["--help"])28 assert result.exit_code == 029 assert "--accept" in result.output30 assert "--reject" in result.output31 assert "--no-accept" not in result.output32 typer.core.rich = rich333435def test_main():36 result = runner.invoke(app)37 assert result.exit_code == 038 assert "I don't know what you want yet" in result.output394041def test_accept():42 result = runner.invoke(app, ["--accept"])43 assert result.exit_code == 044 assert "Accepting!" in result.output454647def test_reject():48 result = runner.invoke(app, ["--reject"])49 assert result.exit_code == 050 assert "Rejecting!" in result.output515253def test_invalid_no_accept():54 result = runner.invoke(app, ["--no-accept"])55 assert result.exit_code != 056 # TODO: when deprecating Click 7, remove second option5758 assert (59 "No such option: --no-accept" in result.output60 or "no such option: --no-accept" in result.output61 )626364def test_script():65 result = subprocess.run(66 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],67 stdout=subprocess.PIPE,68 stderr=subprocess.PIPE,69 encoding="utf-8",70 )71 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial003_an.py+43 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.bool import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "-f" in result.output19 assert "--force" in result.output20 assert "-F" in result.output21 assert "--no-force" in result.output222324def test_force():25 result = runner.invoke(app, ["-f"])26 assert result.exit_code == 027 assert "Forcing operation" in result.output282930def test_no_force():31 result = runner.invoke(app, ["-F"])32 assert result.exit_code == 033 assert "Not forcing" in result.output343536def test_script():37 result = subprocess.run(38 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],39 stdout=subprocess.PIPE,40 stderr=subprocess.PIPE,41 encoding="utf-8",42 )43 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial004_an.py+47 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.bool import tutorial004_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_help():16 result = runner.invoke(app, ["--help"])17 assert result.exit_code == 018 assert "-d" in result.output19 assert "--demo" in result.output202122def test_main():23 result = runner.invoke(app)24 assert result.exit_code == 025 assert "Running in production" in result.output262728def test_demo():29 result = runner.invoke(app, ["--demo"])30 assert result.exit_code == 031 assert "Running demo" in result.output323334def test_short_demo():35 result = runner.invoke(app, ["-d"])36 assert result.exit_code == 037 assert "Running demo" in result.output383940def test_script():41 result = subprocess.run(42 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],43 stdout=subprocess.PIPE,44 stderr=subprocess.PIPE,45 encoding="utf-8",46 )47 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial002_an.py+34 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.datetime import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_main():16 result = runner.invoke(app, ["1969-10-29"])17 assert result.exit_code == 018 assert "Launch will be at: 1969-10-29 00:00:00" in result.output192021def test_usa_weird_date_format():22 result = runner.invoke(app, ["10/29/1969"])23 assert result.exit_code == 024 assert "Launch will be at: 1969-10-29 00:00:00" in result.output252627def test_script():28 result = subprocess.run(29 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],30 stdout=subprocess.PIPE,31 stderr=subprocess.PIPE,32 encoding="utf-8",33 )34 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial002_an.py+34 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.enum import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_upper():16 result = runner.invoke(app, ["--network", "CONV"])17 assert result.exit_code == 018 assert "Training neural network of type: conv" in result.output192021def test_mix():22 result = runner.invoke(app, ["--network", "LsTm"])23 assert result.exit_code == 024 assert "Training neural network of type: lstm" in result.output252627def test_script():28 result = subprocess.run(29 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],30 stdout=subprocess.PIPE,31 stderr=subprocess.PIPE,32 encoding="utf-8",33 )34 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial001_an.py+33 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.file import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_main(tmpdir):17 config_file = Path(tmpdir) / "config.txt"18 config_file.write_text("some settings\nsome more settings")19 result = runner.invoke(app, ["--config", f"{config_file}"])20 config_file.unlink()21 assert result.exit_code == 022 assert "Config line: some settings" in result.output23 assert "Config line: some more settings" in result.output242526def test_script():27 result = subprocess.run(28 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],29 stdout=subprocess.PIPE,30 stderr=subprocess.PIPE,31 encoding="utf-8",32 )33 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial002_an.py+35 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.file import tutorial002_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_main(tmpdir):17 config_file = Path(tmpdir) / "config.txt"18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 text = config_file.read_text()22 config_file.unlink()23 assert result.exit_code == 024 assert "Config written" in result.output25 assert "Some config written by the app" in text262728def test_script():29 result = subprocess.run(30 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],31 stdout=subprocess.PIPE,32 stderr=subprocess.PIPE,33 encoding="utf-8",34 )35 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial003_an.py+32 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.file import tutorial003_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_main(tmpdir):17 binary_file = Path(tmpdir) / "config.txt"18 binary_file.write_bytes(b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o")19 result = runner.invoke(app, ["--file", f"{binary_file}"])20 binary_file.unlink()21 assert result.exit_code == 022 assert "Processed bytes total:" in result.output232425def test_script():26 result = subprocess.run(27 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],28 stdout=subprocess.PIPE,29 stderr=subprocess.PIPE,30 encoding="utf-8",31 )32 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial004_an.py+36 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.file import tutorial004_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_main(tmpdir):17 binary_file = Path(tmpdir) / "config.txt"18 if binary_file.exists(): # pragma no cover19 binary_file.unlink()20 result = runner.invoke(app, ["--file", f"{binary_file}"])21 text = binary_file.read_text()22 binary_file.unlink()23 assert result.exit_code == 024 assert "Binary file written" in result.output25 assert "some settings" in text26 assert "la cigüeña trae al niño" in text272829def test_script():30 result = subprocess.run(31 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],32 stdout=subprocess.PIPE,33 stderr=subprocess.PIPE,34 encoding="utf-8",35 )36 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_file/test_tutorial005_an.py+38 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.file import tutorial005_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_main(tmpdir):17 config_file = Path(tmpdir) / "config.txt"18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 config_file.write_text("")21 result = runner.invoke(app, ["--config", f"{config_file}"])22 result = runner.invoke(app, ["--config", f"{config_file}"])23 result = runner.invoke(app, ["--config", f"{config_file}"])24 text = config_file.read_text()25 config_file.unlink()26 assert result.exit_code == 027 assert "Config line written"28 assert "This is a single line\nThis is a single line\nThis is a single line" in text293031def test_script():32 result = subprocess.run(33 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],34 stdout=subprocess.PIPE,35 stderr=subprocess.PIPE,36 encoding="utf-8",37 )38 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+99 added
1import subprocess2import sys34import typer5import typer.core6from typer.testing import CliRunner78from docs_src.parameter_types.number import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_help():17 result = runner.invoke(app, ["--help"])18 assert result.exit_code == 019 assert "--age" in result.output20 assert "INTEGER RANGE" in result.output21 assert "--score" in result.output22 assert "FLOAT RANGE" in result.output232425def test_help_no_rich():26 rich = typer.core.rich27 typer.core.rich = None28 result = runner.invoke(app, ["--help"])29 assert result.exit_code == 030 assert "--age" in result.output31 assert "INTEGER RANGE" in result.output32 assert "--score" in result.output33 assert "FLOAT RANGE" in result.output34 typer.core.rich = rich353637def test_params():38 result = runner.invoke(app, ["5", "--age", "20", "--score", "90"])39 assert result.exit_code == 040 assert "ID is 5" in result.output41 assert "--age is 20" in result.output42 assert "--score is 90.0" in result.output434445def test_invalid_id():46 result = runner.invoke(app, ["1002"])47 assert result.exit_code != 048 # TODO: when deprecating Click 7, remove second option49 assert (50 (51 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000."52 in result.output53 )54 or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."55 in result.output56 )575859def test_invalid_age():60 result = runner.invoke(app, ["5", "--age", "15"])61 assert result.exit_code != 062 # TODO: when deprecating Click 7, remove second option6364 assert (65 "Invalid value for '--age': 15 is not in the range x>=18" in result.output66 or "Invalid value for '--age': 15 is smaller than the minimum valid value 18."67 in result.output68 )697071def test_invalid_score():72 result = runner.invoke(app, ["5", "--age", "20", "--score", "100.5"])73 assert result.exit_code != 074 # TODO: when deprecating Click 7, remove second option7576 assert (77 "Invalid value for '--score': 100.5 is not in the range x<=100."78 in result.output79 or "Invalid value for '--score': 100.5 is bigger than the maximum valid value"80 in result.output81 )828384def test_negative_score():85 result = runner.invoke(app, ["5", "--age", "20", "--score", "-5"])86 assert result.exit_code == 087 assert "ID is 5" in result.output88 assert "--age is 20" in result.output89 assert "--score is -5.0" in result.output909192def test_script():93 result = subprocess.run(94 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],95 stdout=subprocess.PIPE,96 stderr=subprocess.PIPE,97 encoding="utf-8",98 )99 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002_an.py+42 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.number import tutorial002_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_invalid_id():16 result = runner.invoke(app, ["1002"])17 assert result.exit_code != 018 # TODO: when deprecating Click 7, remove second option1920 assert (21 "Invalid value for 'ID': 1002 is not in the range 0<=x<=1000" in result.output22 or "Invalid value for 'ID': 1002 is not in the valid range of 0 to 1000."23 in result.output24 )252627def test_clamped():28 result = runner.invoke(app, ["5", "--rank", "11", "--score", "-5"])29 assert result.exit_code == 030 assert "ID is 5" in result.output31 assert "--rank is 10" in result.output32 assert "--score is 0" in result.output333435def test_script():36 result = subprocess.run(37 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],38 stdout=subprocess.PIPE,39 stderr=subprocess.PIPE,40 encoding="utf-8",41 )42 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_number/test_tutorial003_an.py+58 added
1import subprocess2import sys34import typer5from typer.testing import CliRunner67from docs_src.parameter_types.number import tutorial003_an as mod89runner = CliRunner()1011app = typer.Typer()12app.command()(mod.main)131415def test_main():16 result = runner.invoke(app)17 assert result.exit_code == 018 assert "Verbose level is 0" in result.output192021def test_verbose_1():22 result = runner.invoke(app, ["--verbose"])23 assert result.exit_code == 024 assert "Verbose level is 1" in result.output252627def test_verbose_3():28 result = runner.invoke(app, ["--verbose", "--verbose", "--verbose"])29 assert result.exit_code == 030 assert "Verbose level is 3" in result.output313233def test_verbose_short_1():34 result = runner.invoke(app, ["-v"])35 assert result.exit_code == 036 assert "Verbose level is 1" in result.output373839def test_verbose_short_3():40 result = runner.invoke(app, ["-v", "-v", "-v"])41 assert result.exit_code == 042 assert "Verbose level is 3" in result.output434445def test_verbose_short_3_condensed():46 result = runner.invoke(app, ["-vvv"])47 assert result.exit_code == 048 assert "Verbose level is 3" in result.output495051def test_script():52 result = subprocess.run(53 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],54 stdout=subprocess.PIPE,55 stderr=subprocess.PIPE,56 encoding="utf-8",57 )58 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_path/test_tutorial001_an.py+55 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.path import tutorial001_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_no_path(tmpdir):17 Path(tmpdir) / "config.txt"18 result = runner.invoke(app)19 assert result.exit_code == 120 assert "No config file" in result.output21 assert "Aborted" in result.output222324def test_not_exists(tmpdir):25 config_file = Path(tmpdir) / "config.txt"26 if config_file.exists(): # pragma no cover27 config_file.unlink()28 result = runner.invoke(app, ["--config", f"{config_file}"])29 assert result.exit_code == 030 assert "The config doesn't exist" in result.output313233def test_exists(tmpdir):34 config_file = Path(tmpdir) / "config.txt"35 config_file.write_text("some settings")36 result = runner.invoke(app, ["--config", f"{config_file}"])37 config_file.unlink()38 assert result.exit_code == 039 assert "Config file contents: some settings" in result.output404142def test_dir():43 result = runner.invoke(app, ["--config", "./"])44 assert result.exit_code == 045 assert "Config is a directory, will use all its config files" in result.output464748def test_script():49 result = subprocess.run(50 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],51 stdout=subprocess.PIPE,52 stderr=subprocess.PIPE,53 encoding="utf-8",54 )55 assert "Usage" in result.stdout
added:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002_an.py+48 added
1import subprocess2import sys3from pathlib import Path45import typer6from typer.testing import CliRunner78from docs_src.parameter_types.path import tutorial002_an as mod910runner = CliRunner()1112app = typer.Typer()13app.command()(mod.main)141516def test_not_exists(tmpdir):17 config_file = Path(tmpdir) / "config.txt"18 if config_file.exists(): # pragma no cover19 config_file.unlink()20 result = runner.invoke(app, ["--config", f"{config_file}"])21 assert result.exit_code != 022 assert "Invalid value for '--config': File" in result.output23 assert "does not exist" in result.output242526def test_exists(tmpdir):27 config_file = Path(tmpdir) / "config.txt"28 config_file.write_text("some settings")29 result = runner.invoke(app, ["--config", f"{config_file}"])30 config_file.unlink()31 assert result.exit_code == 032 assert "Config file contents: some settings" in result.output333435def test_dir():36 result = runner.invoke(app, ["--config", "./"])37 assert result.exit_code != 038 assert "Invalid value for '--config': File './' is a directory." in result.output394041def test_script():42 result = subprocess.run(43 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44 stdout=subprocess.PIPE,45 stderr=subprocess.PIPE,46 encoding="utf-8",47 )48 assert "Usage" in result.stdout
added:tests/test_tutorial/test_testing/test_app02_an.py+19 added
1import subprocess2import sys34from docs_src.testing.app02_an import main as mod5from docs_src.testing.app02_an.test_main import test_app678def test_app02_an():9 test_app()101112def test_script():13 result = subprocess.run(14 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],15 stdout=subprocess.PIPE,16 stderr=subprocess.PIPE,17 encoding="utf-8",18 )19 assert "Usage" in result.stdout
added:tests/test_ambiguous_params.py+230 added
1import pytest2import typer3from typer.testing import CliRunner4from typer.utils import (5 AnnotatedParamWithDefaultValueError,6 DefaultFactoryAndDefaultValueError,7 MixedAnnotatedAndDefaultStyleError,8 MultipleTyperAnnotationsError,9 _split_annotation_from_typer_annotations,10)11from typing_extensions import Annotated1213runner = CliRunner()141516def test_split_annotations_from_typer_annotations_simple():17 # Simple sanity check that this utility works. If this isn't working on a given18 # python version, then no other tests for Annotated will work.19 given = Annotated[str, typer.Argument()]20 base, typer_annotations = _split_annotation_from_typer_annotations(given)21 assert base is str22 # No equality check on the param types. Checking the length is sufficient.23 assert len(typer_annotations) == 1242526def test_forbid_default_value_in_annotated_argument():27 app = typer.Typer()2829 # This test case only works with `typer.Argument`. `typer.Option` uses positionals30 # for param_decls too.31 @app.command()32 def cmd(my_param: Annotated[str, typer.Argument("foo")]):33 ... # pragma: no cover3435 with pytest.raises(AnnotatedParamWithDefaultValueError) as excinfo:36 runner.invoke(app)3738 assert vars(excinfo.value) == dict(39 param_type=typer.models.ArgumentInfo,40 argument_name="my_param",41 )424344def test_allow_options_to_have_names():45 app = typer.Typer()4647 @app.command()48 def cmd(my_param: Annotated[str, typer.Option("--some-opt")]):49 print(my_param)5051 result = runner.invoke(app, ["--some-opt", "hello"])52 assert result.exit_code == 0, result.output53 assert "hello" in result.output545556@pytest.mark.parametrize(57 ["param", "param_info_type"],58 [59 (typer.Argument, typer.models.ArgumentInfo),60 (typer.Option, typer.models.OptionInfo),61 ],62)63def test_forbid_annotated_param_and_default_param(param, param_info_type):64 app = typer.Typer()6566 @app.command()67 def cmd(my_param: Annotated[str, param()] = param("foo")):68 ... # pragma: no cover6970 with pytest.raises(MixedAnnotatedAndDefaultStyleError) as excinfo:71 runner.invoke(app)7273 assert vars(excinfo.value) == dict(74 argument_name="my_param",75 annotated_param_type=param_info_type,76 default_param_type=param_info_type,77 )787980def test_forbid_multiple_typer_params_in_annotated():81 app = typer.Typer()8283 @app.command()84 def cmd(my_param: Annotated[str, typer.Argument(), typer.Argument()]):85 ... # pragma: no cover8687 with pytest.raises(MultipleTyperAnnotationsError) as excinfo:88 runner.invoke(app)8990 assert vars(excinfo.value) == dict(argument_name="my_param")919293def test_allow_multiple_non_typer_params_in_annotated():94 app = typer.Typer()9596 @app.command()97 def cmd(my_param: Annotated[str, "someval", typer.Argument(), 4] = "hello"):98 print(my_param)99100 result = runner.invoke(app)101 # Should behave like normal102 assert result.exit_code == 0, result.output103 assert "hello" in result.output104105106@pytest.mark.parametrize(107 ["param", "param_info_type"],108 [109 (typer.Argument, typer.models.ArgumentInfo),110 (typer.Option, typer.models.OptionInfo),111 ],112)113def test_forbid_default_factory_and_default_value_in_annotated(param, param_info_type):114 def make_string():115 return "foo" # pragma: no cover116117 app = typer.Typer()118119 @app.command()120 def cmd(my_param: Annotated[str, param(default_factory=make_string)] = "hello"):121 ... # pragma: no cover122123 with pytest.raises(DefaultFactoryAndDefaultValueError) as excinfo:124 runner.invoke(app)125126 assert vars(excinfo.value) == dict(127 argument_name="my_param",128 param_type=param_info_type,129 )130131132@pytest.mark.parametrize(133 "param",134 [135 typer.Argument,136 typer.Option,137 ],138)139def test_allow_default_factory_with_default_param(param):140 def make_string():141 return "foo"142143 app = typer.Typer()144145 @app.command()146 def cmd(my_param: str = param(default_factory=make_string)):147 print(my_param)148149 result = runner.invoke(app)150 assert result.exit_code == 0, result.output151 assert "foo" in result.output152153154@pytest.mark.parametrize(155 ["param", "param_info_type"],156 [157 (typer.Argument, typer.models.ArgumentInfo),158 (typer.Option, typer.models.OptionInfo),159 ],160)161def test_forbid_default_and_default_factory_with_default_param(param, param_info_type):162 def make_string():163 return "foo" # pragma: no cover164165 app = typer.Typer()166167 @app.command()168 def cmd(my_param: str = param("hi", default_factory=make_string)):169 ... # pragma: no cover170171 with pytest.raises(DefaultFactoryAndDefaultValueError) as excinfo:172 runner.invoke(app)173174 assert vars(excinfo.value) == dict(175 argument_name="my_param",176 param_type=param_info_type,177 )178179180@pytest.mark.parametrize(181 ["error", "message"],182 [183 (184 AnnotatedParamWithDefaultValueError(185 argument_name="my_argument",186 param_type=typer.models.ArgumentInfo,187 ),188 "`Argument` default value cannot be set in `Annotated` for 'my_argument'. Set the default value with `=` instead.",189 ),190 (191 MixedAnnotatedAndDefaultStyleError(192 argument_name="my_argument",193 annotated_param_type=typer.models.OptionInfo,194 default_param_type=typer.models.ArgumentInfo,195 ),196 "Cannot specify `Option` in `Annotated` and `Argument` as a default value together for 'my_argument'",197 ),198 (199 MixedAnnotatedAndDefaultStyleError(200 argument_name="my_argument",201 annotated_param_type=typer.models.OptionInfo,202 default_param_type=typer.models.OptionInfo,203 ),204 "Cannot specify `Option` in `Annotated` and default value together for 'my_argument'",205 ),206 (207 MixedAnnotatedAndDefaultStyleError(208 argument_name="my_argument",209 annotated_param_type=typer.models.ArgumentInfo,210 default_param_type=typer.models.ArgumentInfo,211 ),212 "Cannot specify `Argument` in `Annotated` and default value together for 'my_argument'",213 ),214 (215 MultipleTyperAnnotationsError(216 argument_name="my_argument",217 ),218 "Cannot specify multiple `Annotated` Typer arguments for 'my_argument'",219 ),220 (221 DefaultFactoryAndDefaultValueError(222 argument_name="my_argument",223 param_type=typer.models.OptionInfo,224 ),225 "Cannot specify `default_factory` and a default value together for `Option`",226 ),227 ],228)229def test_error_rendering(error, message):230 assert str(error) == message
added:tests/test_annotated.py+59 added
1import typer2from typer.testing import CliRunner3from typing_extensions import Annotated45runner = CliRunner()678def test_annotated_argument_with_default():9 app = typer.Typer()1011 @app.command()12 def cmd(val: Annotated[int, typer.Argument()] = 0):13 print(f"hello {val}")1415 result = runner.invoke(app)16 assert result.exit_code == 0, result.output17 assert "hello 0" in result.output1819 result = runner.invoke(app, ["42"])20 assert result.exit_code == 0, result.output21 assert "hello 42" in result.output222324def test_annotated_argument_with_default_factory():25 app = typer.Typer()2627 def make_string():28 return "I made it"2930 @app.command()31 def cmd(val: Annotated[str, typer.Argument(default_factory=make_string)]):32 print(val)3334 result = runner.invoke(app)35 assert result.exit_code == 0, result.output36 assert "I made it" in result.output3738 result = runner.invoke(app, ["overridden"])39 assert result.exit_code == 0, result.output40 assert "overridden" in result.output414243def test_annotated_option_with_argname_doesnt_mutate_multiple_calls():44 app = typer.Typer()4546 @app.command()47 def cmd(force: Annotated[bool, typer.Option("--force")] = False):48 if force:49 print("Forcing operation")50 else:51 print("Not forcing")5253 result = runner.invoke(app)54 assert result.exit_code == 0, result.output55 assert "Not forcing" in result.output5657 result = runner.invoke(app, ["--force"])58 assert result.exit_code == 0, result.output59 assert "Forcing operation" in result.output
added:typer/_typing.py+631 added
1# Copied from pydantic 1.9.2 (the latest version to support python 3.6.)2# https://github.com/pydantic/pydantic/blob/v1.9.2/pydantic/typing.py3# mypy: ignore-errors45import sys6from os import PathLike7from typing import ( # type: ignore8 TYPE_CHECKING,9 AbstractSet,10 Any,11 ClassVar,12 Dict,13 Generator,14 Iterable,15 List,16 Mapping,17 NewType,18 Optional,19 Sequence,20 Set,21 Tuple,22 Type,23 Union,24 _eval_type,25 cast,26 get_type_hints,27)2829from typing_extensions import Annotated, Literal3031try:32 from typing import _TypingBase as typing_base # type: ignore33except ImportError:34 from typing import _Final as typing_base # type: ignore3536try:37 from typing import GenericAlias as TypingGenericAlias # type: ignore38except ImportError:39 # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on)40 TypingGenericAlias = ()4142try:43 from types import UnionType as TypesUnionType # type: ignore44except ImportError:45 # python < 3.10 does not have UnionType (str | int, byte | bool and so on)46 TypesUnionType = ()474849if sys.version_info < (3, 7):50 if TYPE_CHECKING:5152 class ForwardRef:53 def __init__(self, arg: Any):54 pass5556 def _eval_type(self, globalns: Any, localns: Any) -> Any:57 pass5859 else:60 from typing import _ForwardRef as ForwardRef61else:62 from typing import ForwardRef636465if sys.version_info < (3, 7):6667 def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:68 return type_._eval_type(globalns, localns)6970elif sys.version_info < (3, 9):7172 def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:73 return type_._evaluate(globalns, localns)7475else:7677 def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:78 # Even though it is the right signature for python 3.9, mypy complains with79 # `error: Too many arguments for "_evaluate" of "ForwardRef"` hence the cast...80 return cast(Any, type_)._evaluate(globalns, localns, set())818283if sys.version_info < (3, 9):84 # Ensure we always get all the whole `Annotated` hint, not just the annotated type.85 # For 3.6 to 3.8, `get_type_hints` doesn't recognize `typing_extensions.Annotated`,86 # so it already returns the full annotation87 get_all_type_hints = get_type_hints8889else:9091 def get_all_type_hints(obj: Any, globalns: Any = None, localns: Any = None) -> Any:92 return get_type_hints(obj, globalns, localns, include_extras=True)939495if sys.version_info < (3, 7):96 from typing import Callable as Callable9798 AnyCallable = Callable[..., Any]99 NoArgAnyCallable = Callable[[], Any]100else:101 from collections.abc import Callable as Callable102 from typing import Callable as TypingCallable103104 AnyCallable = TypingCallable[..., Any]105 NoArgAnyCallable = TypingCallable[[], Any]106107108# Annotated[...] is implemented by returning an instance of one of these classes, depending on109# python/typing_extensions version.110AnnotatedTypeNames = {"AnnotatedMeta", "_AnnotatedAlias"}111112113if sys.version_info < (3, 8):114115 def get_origin(t: Type[Any]) -> Optional[Type[Any]]:116 if type(t).__name__ in AnnotatedTypeNames:117 return cast(118 Type[Any], Annotated119 ) # mypy complains about _SpecialForm in py3.6120 return getattr(t, "__origin__", None)121122else:123 from typing import get_origin as _typing_get_origin124125 def get_origin(tp: Type[Any]) -> Optional[Type[Any]]:126 """127 We can't directly use `typing.get_origin` since we need a fallback to support128 custom generic classes like `ConstrainedList`129 It should be useless once https://github.com/cython/cython/issues/3537 is130 solved and https://github.com/samuelcolvin/pydantic/pull/1753 is merged.131 """132 if type(tp).__name__ in AnnotatedTypeNames:133 return cast(Type[Any], Annotated) # mypy complains about _SpecialForm134 return _typing_get_origin(tp) or getattr(tp, "__origin__", None)135136137if sys.version_info < (3, 7): # noqa: C901 (ignore complexity)138139 def get_args(t: Type[Any]) -> Tuple[Any, ...]:140 """Simplest get_args compatibility layer possible.141142 The Python 3.6 typing module does not have `_GenericAlias` so143 this won't work for everything. In particular this will not144 support the `generics` module (we don't support generic models in145 python 3.6).146147 """148 if type(t).__name__ in AnnotatedTypeNames:149 return t.__args__ + t.__metadata__150 return getattr(t, "__args__", ())151152elif sys.version_info < (3, 8): # noqa: C901153 from typing import _GenericAlias154155 def get_args(t: Type[Any]) -> Tuple[Any, ...]:156 """Compatibility version of get_args for python 3.7.157158 Mostly compatible with the python 3.8 `typing` module version159 and able to handle almost all use cases.160 """161 if type(t).__name__ in AnnotatedTypeNames:162 return t.__args__ + t.__metadata__163 if isinstance(t, _GenericAlias):164 res = t.__args__165 if t.__origin__ is Callable and res and res[0] is not Ellipsis:166 res = (list(res[:-1]), res[-1])167 return res168 return getattr(t, "__args__", ())169170else:171 from typing import get_args as _typing_get_args172173 def _generic_get_args(tp: Type[Any]) -> Tuple[Any, ...]:174 """175 In python 3.9, `typing.Dict`, `typing.List`, ...176 do have an empty `__args__` by default (instead of the generic ~T for example).177 In order to still support `Dict` for example and consider it as `Dict[Any, Any]`,178 we retrieve the `_nparams` value that tells us how many parameters it needs.179 """180 if hasattr(tp, "_nparams"):181 return (Any,) * tp._nparams182 return ()183184 def get_args(tp: Type[Any]) -> Tuple[Any, ...]:185 """Get type arguments with all substitutions performed.186187 For unions, basic simplifications used by Union constructor are performed.188 Examples::189 get_args(Dict[str, int]) == (str, int)190 get_args(int) == ()191 get_args(Union[int, Union[T, int], str][int]) == (int, str)192 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])193 get_args(Callable[[], T][int]) == ([], int)194 """195 if type(tp).__name__ in AnnotatedTypeNames:196 return tp.__args__ + tp.__metadata__197 # the fallback is needed for the same reasons as `get_origin` (see above)198 return (199 _typing_get_args(tp) or getattr(tp, "__args__", ()) or _generic_get_args(tp)200 )201202203if sys.version_info < (3, 9):204205 def convert_generics(tp: Type[Any]) -> Type[Any]:206 """Python 3.9 and older only supports generics from `typing` module.207 They convert strings to ForwardRef automatically.208209 Examples::210 typing.List['Hero'] == typing.List[ForwardRef('Hero')]211 """212 return tp213214else:215 from typing import _UnionGenericAlias # type: ignore216217 from typing_extensions import _AnnotatedAlias218219 def convert_generics(tp: Type[Any]) -> Type[Any]:220 """221 Recursively searches for `str` type hints and replaces them with ForwardRef.222223 Examples::224 convert_generics(list['Hero']) == list[ForwardRef('Hero')]225 convert_generics(dict['Hero', 'Team']) == dict[ForwardRef('Hero'), ForwardRef('Team')]226 convert_generics(typing.Dict['Hero', 'Team']) == typing.Dict[ForwardRef('Hero'), ForwardRef('Team')]227 convert_generics(list[str | 'Hero'] | int) == list[str | ForwardRef('Hero')] | int228 """229 origin = get_origin(tp)230 if not origin or not hasattr(tp, "__args__"):231 return tp232233 args = get_args(tp)234235 # typing.Annotated needs special treatment236 if origin is Annotated:237 return _AnnotatedAlias(convert_generics(args[0]), args[1:])238239 # recursively replace `str` instances inside of `GenericAlias` with `ForwardRef(arg)`240 converted = tuple(241 ForwardRef(arg)242 if isinstance(arg, str) and isinstance(tp, TypingGenericAlias)243 else convert_generics(arg)244 for arg in args245 )246247 if converted == args:248 return tp249 elif isinstance(tp, TypingGenericAlias):250 return TypingGenericAlias(origin, converted)251 elif isinstance(tp, TypesUnionType):252 # recreate types.UnionType (PEP604, Python >= 3.10)253 return _UnionGenericAlias(origin, converted)254 else:255 try:256 setattr(tp, "__args__", converted)257 except AttributeError:258 pass259 return tp260261262if sys.version_info < (3, 10):263264 def is_union(tp: Optional[Type[Any]]) -> bool:265 return tp is Union266267 WithArgsTypes = (TypingGenericAlias,)268269else:270 import types271 import typing272273 def is_union(tp: Optional[Type[Any]]) -> bool:274 return tp is Union or tp is types.UnionType # noqa: E721275276 WithArgsTypes = (typing._GenericAlias, types.GenericAlias, types.UnionType)277278279if sys.version_info < (3, 9):280 StrPath = Union[str, PathLike]281else:282 StrPath = Union[str, PathLike]283 # TODO: Once we switch to Cython 3 to handle generics properly284 # (https://github.com/cython/cython/issues/2753), use following lines instead285 # of the one above286 # # os.PathLike only becomes subscriptable from Python 3.9 onwards287 # StrPath = Union[str, PathLike[str]]288289290if TYPE_CHECKING:291 # Only in Pydantic292 # from .fields import ModelField293294 TupleGenerator = Generator[Tuple[str, Any], None, None]295 DictStrAny = Dict[str, Any]296 DictAny = Dict[Any, Any]297 SetStr = Set[str]298 ListStr = List[str]299 IntStr = Union[int, str]300 AbstractSetIntStr = AbstractSet[IntStr]301 DictIntStrAny = Dict[IntStr, Any]302 MappingIntStrAny = Mapping[IntStr, Any]303 CallableGenerator = Generator[AnyCallable, None, None]304 ReprArgs = Sequence[Tuple[Optional[str], Any]]305 AnyClassMethod = classmethod[Any]306307__all__ = (308 "ForwardRef",309 "Callable",310 "AnyCallable",311 "NoArgAnyCallable",312 "NoneType",313 "is_none_type",314 "display_as_type",315 "resolve_annotations",316 "is_callable_type",317 "is_literal_type",318 "all_literal_values",319 "is_namedtuple",320 "is_typeddict",321 "is_new_type",322 "new_type_supertype",323 "is_classvar",324 "update_field_forward_refs",325 "update_model_forward_refs",326 "TupleGenerator",327 "DictStrAny",328 "DictAny",329 "SetStr",330 "ListStr",331 "IntStr",332 "AbstractSetIntStr",333 "DictIntStrAny",334 "CallableGenerator",335 "ReprArgs",336 "AnyClassMethod",337 "CallableGenerator",338 "WithArgsTypes",339 "get_args",340 "get_origin",341 "get_sub_types",342 "typing_base",343 "get_all_type_hints",344 "is_union",345 "StrPath",346)347348349NoneType = None.__class__350351352NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None])353354355if sys.version_info < (3, 8):356 # Even though this implementation is slower, we need it for python 3.6/3.7:357 # In python 3.6/3.7 "Literal" is not a builtin type and uses a different358 # mechanism.359 # for this reason `Literal[None] is Literal[None]` evaluates to `False`,360 # breaking the faster implementation used for the other python versions.361362 def is_none_type(type_: Any) -> bool:363 return type_ in NONE_TYPES364365elif sys.version_info[:2] == (3, 8):366 # We can use the fast implementation for 3.8 but there is a very weird bug367 # where it can fail for `Literal[None]`.368 # We just need to redefine a useless `Literal[None]` inside the function body to fix this369370 def is_none_type(type_: Any) -> bool:371 Literal[None] # fix edge case372 for none_type in NONE_TYPES:373 if type_ is none_type:374 return True375 return False376377else:378379 def is_none_type(type_: Any) -> bool:380 for none_type in NONE_TYPES:381 if type_ is none_type:382 return True383 return False384385386def display_as_type(v: Type[Any]) -> str:387 if (388 not isinstance(v, typing_base)389 and not isinstance(v, WithArgsTypes)390 and not isinstance(v, type)391 ):392 v = v.__class__393394 if is_union(get_origin(v)):395 return f'Union[{", ".join(map(display_as_type, get_args(v)))}]'396397 if isinstance(v, WithArgsTypes):398 # Generic alias are constructs like `list[int]`399 return str(v).replace("typing.", "")400401 try:402 return v.__name__403 except AttributeError:404 # happens with typing objects405 return str(v).replace("typing.", "")406407408def resolve_annotations(409 raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]410) -> Dict[str, Type[Any]]:411 """412 Partially taken from typing.get_type_hints.413414 Resolve string or ForwardRef annotations into type objects if possible.415 """416 base_globals: Optional[Dict[str, Any]] = None417 if module_name:418 try:419 module = sys.modules[module_name]420 except KeyError:421 # happens occasionally, see https://github.com/samuelcolvin/pydantic/issues/2363422 pass423 else:424 base_globals = module.__dict__425426 annotations = {}427 for name, value in raw_annotations.items():428 if isinstance(value, str):429 if (3, 10) > sys.version_info >= (3, 9, 8) or sys.version_info >= (430 3,431 10,432 1,433 ):434 value = ForwardRef(value, is_argument=False, is_class=True)435 elif sys.version_info >= (3, 7):436 value = ForwardRef(value, is_argument=False)437 else:438 value = ForwardRef(value)439 try:440 value = _eval_type(value, base_globals, None)441 except NameError:442 # this is ok, it can be fixed with update_forward_refs443 pass444 annotations[name] = value445 return annotations446447448def is_callable_type(type_: Type[Any]) -> bool:449 return type_ is Callable or get_origin(type_) is Callable450451452if sys.version_info >= (3, 7):453454 def is_literal_type(type_: Type[Any]) -> bool:455 return Literal is not None and get_origin(type_) is Literal456457 def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:458 return get_args(type_)459460else:461462 def is_literal_type(type_: Type[Any]) -> bool:463 return (464 Literal is not None465 and hasattr(type_, "__values__")466 and type_ == Literal[type_.__values__]467 )468469 def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:470 return type_.__values__471472473def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]:474 """475 This method is used to retrieve all Literal values as476 Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586)477 e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`478 """479 if not is_literal_type(type_):480 return (type_,)481482 values = literal_values(type_)483 return tuple(x for value in values for x in all_literal_values(value))484485486def is_namedtuple(type_: Type[Any]) -> bool:487 """488 Check if a given class is a named tuple.489 It can be either a `typing.NamedTuple` or `collections.namedtuple`490 """491 from .utils import lenient_issubclass492493 return lenient_issubclass(type_, tuple) and hasattr(type_, "_fields")494495496def is_typeddict(type_: Type[Any]) -> bool:497 """498 Check if a given class is a typed dict (from `typing` or `typing_extensions`)499 In 3.10, there will be a public method (https://docs.python.org/3.10/library/typing.html#typing.is_typeddict)500 """501 from .utils import lenient_issubclass502503 return lenient_issubclass(type_, dict) and hasattr(type_, "__total__")504505506test_type = NewType("test_type", str)507508509def is_new_type(type_: Type[Any]) -> bool:510 """511 Check whether type_ was created using typing.NewType512 """513 return isinstance(type_, test_type.__class__) and hasattr(type_, "__supertype__") # type: ignore514515516def new_type_supertype(type_: Type[Any]) -> Type[Any]:517 while hasattr(type_, "__supertype__"):518 type_ = type_.__supertype__519 return type_520521522def _check_classvar(v: Optional[Type[Any]]) -> bool:523 if v is None:524 return False525526 return v.__class__ == ClassVar.__class__ and (527 sys.version_info < (3, 7) or getattr(v, "_name", None) == "ClassVar"528 )529530531def is_classvar(ann_type: Type[Any]) -> bool:532 if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)):533 return True534535 # this is an ugly workaround for class vars that contain forward references and are therefore themselves536 # forward references, see #3679537 if ann_type.__class__ == ForwardRef and ann_type.__forward_arg__.startswith(538 "ClassVar["539 ):540 return True541542 return False543544545# Only in Pydantic546# def update_field_forward_refs(field: "ModelField", globalns: Any, localns: Any) -> None:547# """548# Try to update ForwardRefs on fields based on this ModelField, globalns and localns.549# """550# if field.type_.__class__ == ForwardRef:551# field.type_ = evaluate_forwardref(field.type_, globalns, localns or None)552# field.prepare()553554# if field.sub_fields:555# for sub_f in field.sub_fields:556# update_field_forward_refs(sub_f, globalns=globalns, localns=localns)557558# if field.discriminator_key is not None:559# field.prepare_discriminated_union_sub_fields()560561562# Only in Pydantic563# def update_model_forward_refs(564# model: Type[Any],565# fields: Iterable["ModelField"],566# json_encoders: Dict[Union[Type[Any], str], AnyCallable],567# localns: "DictStrAny",568# exc_to_suppress: Tuple[Type[BaseException], ...] = (),569# ) -> None:570# """571# Try to update model fields ForwardRefs based on model and localns.572# """573# if model.__module__ in sys.modules:574# globalns = sys.modules[model.__module__].__dict__.copy()575# else:576# globalns = {}577578# globalns.setdefault(model.__name__, model)579580# for f in fields:581# try:582# update_field_forward_refs(f, globalns=globalns, localns=localns)583# except exc_to_suppress:584# pass585586# for key in set(json_encoders.keys()):587# if isinstance(key, str):588# fr: ForwardRef = ForwardRef(key)589# elif isinstance(key, ForwardRef):590# fr = key591# else:592# continue593594# try:595# new_key = evaluate_forwardref(fr, globalns, localns or None)596# except exc_to_suppress: # pragma: no cover597# continue598599# json_encoders[new_key] = json_encoders.pop(key)600601602def get_class(type_: Type[Any]) -> Union[None, bool, Type[Any]]:603 """604 Tries to get the class of a Type[T] annotation. Returns True if Type is used605 without brackets. Otherwise returns None.606 """607 try:608 origin = get_origin(type_)609 if origin is None: # Python 3.6610 origin = type_611 if issubclass(origin, Type): # type: ignore612 if not get_args(type_) or not isinstance(get_args(type_)[0], type):613 return True614 return get_args(type_)[0]615 except (AttributeError, TypeError):616 pass617 return None618619620def get_sub_types(tp: Any) -> List[Any]:621 """622 Return all the types that are allowed by type `tp`623 `tp` can be a `Union` of allowed types or an `Annotated` type624 """625 origin = get_origin(tp)626 if origin is Annotated:627 return get_sub_types(get_args(tp)[0])628 elif is_union(origin):629 return [x for t in get_args(tp) for x in get_sub_types(t)]630 else:631 return [tp]
modified:typer/models.py+6 added
182 unmodified lines
183 Union[List["click.shell_completion.CompletionItem"], List[str]],184 ]185 ] = None,186 autocompletion: Optional[Callable[..., Any]] = None,187 default_factory: Optional[Callable[[], Any]] = None,188 # Custom type189 parser: Optional[Callable[[str], Any]] = None,190 click_type: Optional[click.ParamType] = None,191 # TyperArgument
43 unmodified lines
235 self.is_eager = is_eager236 self.envvar = envvar237 self.shell_complete = shell_complete238 self.autocompletion = autocompletion239 self.default_factory = default_factory240 # Custom type241 self.parser = parser242 self.click_type = click_type243 # TyperArgument
47 unmodified lines
291 Union[List["click.shell_completion.CompletionItem"], List[str]],292 ]293 ] = None,294 autocompletion: Optional[Callable[..., Any]] = None,295 default_factory: Optional[Callable[[], Any]] = None,296 # Custom type297 parser: Optional[Callable[[str], Any]] = None,298 click_type: Optional[click.ParamType] = None,299 # Option
45 unmodified lines
345 is_eager=is_eager,346 envvar=envvar,347 shell_complete=shell_complete,348 autocompletion=autocompletion,349 default_factory=default_factory,350 # Custom type351 parser=parser,352 click_type=click_type,353 # TyperArgument
56 unmodified lines
410 Union[List["click.shell_completion.CompletionItem"], List[str]],411 ]412 ] = None,413 autocompletion: Optional[Callable[..., Any]] = None,414 default_factory: Optional[Callable[[], Any]] = None,415 # Custom type416 parser: Optional[Callable[[str], Any]] = None,417 click_type: Optional[click.ParamType] = None,418 # TyperArgument
37 unmodified lines
456 is_eager=is_eager,457 envvar=envvar,458 shell_complete=shell_complete,459 autocompletion=autocompletion,460 default_factory=default_factory,461 # Custom type462 parser=parser,463 click_type=click_type,464 # TyperArgument
59 unmodified lines
modified:typer/params.py+10 added-4 removed
9 unmodified lines
1011@overload12def Option(13 # Parameter14 default: Optional[Any],14 default: Optional[Any] = ...,15 *param_decls: str,16 callback: Optional[Callable[..., Any]] = None,17 metavar: Optional[str] = None,18 expose_value: bool = True,
5 unmodified lines
24 Union[List["click.shell_completion.CompletionItem"], List[str]],25 ]26 ] = None,27 autocompletion: Optional[Callable[..., Any]] = None,28 default_factory: Optional[Callable[[], Any]] = None,29 # Custom type30 parser: Optional[Callable[[str], Any]] = None,31 # Option32 show_default: bool = True,
40 unmodified lines
7374@overload75def Option(76 # Parameter76 default: Optional[Any],77 default: Optional[Any] = ...,78 *param_decls: str,79 callback: Optional[Callable[..., Any]] = None,80 metavar: Optional[str] = None,81 expose_value: bool = True,
5 unmodified lines
87 Union[List["click.shell_completion.CompletionItem"], List[str]],88 ]89 ] = None,90 autocompletion: Optional[Callable[..., Any]] = None,91 default_factory: Optional[Callable[[], Any]] = None,92 # Custom type93 click_type: Optional[click.ParamType] = None,94 # Option95 show_default: bool = True,
39 unmodified lines
135136137def Option(138 # Parameter137 default: Optional[Any],139 default: Optional[Any] = ...,140 *param_decls: str,141 callback: Optional[Callable[..., Any]] = None,142 metavar: Optional[str] = None,143 expose_value: bool = True,
5 unmodified lines
149 Union[List["click.shell_completion.CompletionItem"], List[str]],150 ]151 ] = None,152 autocompletion: Optional[Callable[..., Any]] = None,153 default_factory: Optional[Callable[[], Any]] = None,154 # Custom type155 parser: Optional[Callable[[str], Any]] = None,156 click_type: Optional[click.ParamType] = None,157 # Option
46 unmodified lines
204 is_eager=is_eager,205 envvar=envvar,206 shell_complete=shell_complete,207 autocompletion=autocompletion,208 default_factory=default_factory,209 # Custom type210 parser=parser,211 click_type=click_type,212 # Option
147 unmodified lines
360361362def Argument(363 # Parameter360 default: Optional[Any],364 default: Optional[Any] = ...,365 *,366 callback: Optional[Callable[..., Any]] = None,367 metavar: Optional[str] = None,368 expose_value: bool = True,
5 unmodified lines
374 Union[List["click.shell_completion.CompletionItem"], List[str]],375 ]376 ] = None,377 autocompletion: Optional[Callable[..., Any]] = None,378 default_factory: Optional[Callable[[], Any]] = None,379 # Custom type380 parser: Optional[Callable[[str], Any]] = None,381 click_type: Optional[click.ParamType] = None,382 # TyperArgument
40 unmodified lines
423 is_eager=is_eager,424 envvar=envvar,425 shell_complete=shell_complete,426 autocompletion=autocompletion,427 default_factory=default_factory,428 # Custom type429 parser=parser,430 click_type=click_type,431 # TyperArgument
31 unmodified lines
modified:typer/utils.py+174 added-5 removed
1import inspect2from copy import copy2from typing import Any, Callable, Dict, get_type_hints3from typing import Any, Callable, Dict, List, Tuple, Type, cast, get_type_hints44from .models import ParamMeta5from typing_extensions import Annotated67from ._typing import get_args, get_origin8from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta91011def _param_type_to_user_string(param_type: Type[ParameterInfo]) -> str:12 # Render a `ParameterInfo` subclass for use in error messages.13 # User code doesn't call `*Info` directly, so errors should present the classes how14 # they were (probably) defined in the user code.15 if param_type is OptionInfo:16 return "`Option`"17 elif param_type is ArgumentInfo:18 return "`Argument`"19 # This line shouldn't be reachable during normal use.20 return f"`{param_type.__name__}`" # pragma: no cover212223class AnnotatedParamWithDefaultValueError(Exception):24 argument_name: str25 param_type: Type[ParameterInfo]2627 def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):28 self.argument_name = argument_name29 self.param_type = param_type3031 def __str__(self) -> str:32 param_type_str = _param_type_to_user_string(self.param_type)33 return (34 f"{param_type_str} default value cannot be set in `Annotated`"35 f" for {self.argument_name!r}. Set the default value with `=` instead."36 )373839class MixedAnnotatedAndDefaultStyleError(Exception):40 argument_name: str41 annotated_param_type: Type[ParameterInfo]42 default_param_type: Type[ParameterInfo]4344 def __init__(45 self,46 argument_name: str,47 annotated_param_type: Type[ParameterInfo],48 default_param_type: Type[ParameterInfo],49 ):50 self.argument_name = argument_name51 self.annotated_param_type = annotated_param_type52 self.default_param_type = default_param_type5354 def __str__(self) -> str:55 annotated_param_type_str = _param_type_to_user_string(self.annotated_param_type)56 default_param_type_str = _param_type_to_user_string(self.default_param_type)57 msg = f"Cannot specify {annotated_param_type_str} in `Annotated` and"58 if self.annotated_param_type is self.default_param_type:59 msg += " default value"60 else:61 msg += f" {default_param_type_str} as a default value"62 msg += f" together for {self.argument_name!r}"63 return msg646566class MultipleTyperAnnotationsError(Exception):67 argument_name: str6869 def __init__(self, argument_name: str):70 self.argument_name = argument_name7172 def __str__(self) -> str:73 return (74 "Cannot specify multiple `Annotated` Typer arguments"75 f" for {self.argument_name!r}"76 )777879class DefaultFactoryAndDefaultValueError(Exception):80 argument_name: str81 param_type: Type[ParameterInfo]8283 def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):84 self.argument_name = argument_name85 self.param_type = param_type8687 def __str__(self) -> str:88 param_type_str = _param_type_to_user_string(self.param_type)89 return (90 "Cannot specify `default_factory` and a default value together"91 f" for {param_type_str}"92 )939495def _split_annotation_from_typer_annotations(96 base_annotation: Type[Any],97) -> Tuple[Type[Any], List[ParameterInfo]]:98 if get_origin(base_annotation) is not Annotated: # type: ignore99 return base_annotation, []100 base_annotation, *maybe_typer_annotations = get_args(base_annotation)101 return base_annotation, [102 annotation103 for annotation in maybe_typer_annotations104 if isinstance(annotation, ParameterInfo)105 ]106107108def get_params_from_function(func: Callable[..., Any]) -> Dict[str, ParamMeta]:109 signature = inspect.signature(func)110 type_hints = get_type_hints(func)111 params = {}112 for param in signature.parameters.values():12 annotation = param.annotation13 if param.name in type_hints:113 annotation, typer_annotations = _split_annotation_from_typer_annotations(114 param.annotation,115 )116 if len(typer_annotations) > 1:117 raise MultipleTyperAnnotationsError(param.name)118119 default = param.default120 if typer_annotations:121 # It's something like `my_param: Annotated[str, Argument()]`122 [parameter_info] = typer_annotations123124 # Forbid `my_param: Annotated[str, Argument()] = Argument("...")`125 if isinstance(param.default, ParameterInfo):126 raise MixedAnnotatedAndDefaultStyleError(127 argument_name=param.name,128 annotated_param_type=type(parameter_info),129 default_param_type=type(param.default),130 )131132 parameter_info = copy(parameter_info)133134 # When used as a default, `Option` takes a default value and option names135 # as positional arguments:136 # `Option(some_value, "--some-argument", "-s")`137 # When used in `Annotated` (ie, what this is handling), `Option` just takes138 # option names as positional arguments:139 # `Option("--some-argument", "-s")`140 # In this case, the `default` attribute of `parameter_info` is actually141 # meant to be the first item of `param_decls`.142 if (143 isinstance(parameter_info, OptionInfo)144 and parameter_info.default is not ...145 ):146 parameter_info.param_decls = (147 cast(str, parameter_info.default),148 *(parameter_info.param_decls or ()),149 )150 parameter_info.default = ...151152 # Forbid `my_param: Annotated[str, Argument('some-default')]`153 if parameter_info.default is not ...:154 raise AnnotatedParamWithDefaultValueError(155 param_type=type(parameter_info),156 argument_name=param.name,157 )158 if param.default is not param.empty:159 # Put the parameter's default (set by `=`) into `parameter_info`, where160 # typer can find it.161 parameter_info.default = param.default162163 default = parameter_info164 elif param.name in type_hints:165 # Resolve forward references.166 annotation = type_hints[param.name]167168 if isinstance(default, ParameterInfo):169 parameter_info = copy(default)170 # Click supports `default` as either171 # - an actual value; or172 # - a factory function (returning a default value.)173 # The two are not interchangeable for static typing, so typer allows174 # specifying `default_factory`. Move the `default_factory` into `default`175 # so click can find it.176 if parameter_info.default is ... and parameter_info.default_factory:177 parameter_info.default = parameter_info.default_factory178 elif parameter_info.default_factory:179 raise DefaultFactoryAndDefaultValueError(180 argument_name=param.name, param_type=type(parameter_info)181 )182 default = parameter_info183184 params[param.name] = ParamMeta(16 name=param.name, default=param.default, annotation=annotation185 name=param.name, default=default, annotation=annotation186 )187 return params
modified:.coveragerc+3 added
3 unmodified lines
4 typer5 tests6 docs_src78omit =9 typer/_typing.py1011parallel = True12context = '${CONTEXT}'1314[report]
9 unmodified lines
modified:mkdocs.yml+3 added
102 unmodified lines
103 - pymdownx.tabbed:104 alternate_style: true105 - mdx_include:106 base_path: docs107 # Enable while writing docs to simplify highlighting108 # - pymdownx.highlight:109 # linenums: true110111extra:112 analytics:113 provider: google
23 unmodified lines
modified:pyproject.toml+2 added-1 removed
28 unmodified lines
29 "Programming Language :: Python :: 3.11",30 "License :: OSI Approved :: MIT License"31 ]32requires = [33 "click >= 7.1.1, <9.0.0"33 "click >= 7.1.1, <9.0.0",34 "typing-extensions >= 3.7.4.3",35]36description-file = "README.md"37requires-python = ">=3.6"38
58 unmodified lines