✨ 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 ---------
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
Provenance
- Commit
458a492- Tree
e9ee810- Author
Ryan Miller Galamb <12422195+ryangalamb@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
1260b8d
179 files changed+6782 added−322 removed
modified:docs/tutorial/arguments/default.md+32 added-7 removed
4 unmodified lines567891011910111213141516171819202122232425262731 unmodified lines59606162526364545556656667686970717273747576777879808182838485868788899034 unmodified lines4 unmodified lines## An optional *CLI argument* with a default
We can also use `typer.Argument()` to make a *CLI argument* have a default value other than `None`:
```Python hl_lines="4"{!../docs_src/arguments/default/tutorial001.py!}```=== "Python 3.6+"
```Python hl_lines="5" {!> ../docs_src/arguments/default/tutorial001_an.py!} ```
=== "Python 3.6+ non-Annotated"
!!! tip Prefer to use the `Annotated` version if possible.
```Python hl_lines="4" {!> ../docs_src/arguments/default/tutorial001.py!} ```
!!! tip Because now the value will be a `str` passed by the user or the default value of `"Wade Wilson"` which is also a `str`, we know the value will never be `None`, so we don't have to (and shouldn't) use `Optional[str]`.
Have in mind that the `Optional[something]` tells Python that a value "could be `None`". But the use of `Optional` doesn't affect Typer in any way, e.g. it doesn't tell Typer if a value is required or not.31 unmodified lines</div>
## Dynamic default value
And we can even make the default value be dynamically generated by passing a function as the first function argument:And we can even make the default value be dynamically generated by passing a function as the `default_factory` argument:
```Python hl_lines="6 7 10"{!../docs_src/arguments/default/tutorial002.py!}```=== "Python 3.6+"
```Python hl_lines="7-8 11" {!> ../docs_src/arguments/default/tutorial002_an.py!} ```
=== "Python 3.6+ non-Annotated"
!!! tip Prefer to use the `Annotated` version if possible.
```Python hl_lines="6-7 10" {!> ../docs_src/arguments/default/tutorial002.py!} ```
In this case, we created the function `get_name` that will just return a random `str` each time.
And we pass it as the first function argument to `typer.Argument()`.
!!! tip The word "factory" in `default_factory` is just a fancy way of saying "function that will create the default value".
Check it:
<div class="termy">
34 unmodified linesmodified:docs/tutorial/arguments/envvar.md+42 added-9 removed
1 You 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*.2 3 To do that, use the `envvar` parameter for `typer.Argument()`:4 5-```Python hl_lines="4"6-{!../docs_src/arguments/envvar/tutorial001.py!}7-```5+=== "Python 3.6+"6 7+ ```Python hl_lines="5"8+ {!> ../docs_src/arguments/envvar/tutorial001_an.py!}9+ ```10+11+=== "Python 3.6+ non-Annotated"12+13+ !!! tip14+ Prefer to use the `Annotated` version if possible.15+16+ ```Python hl_lines="4"17+ {!> ../docs_src/arguments/envvar/tutorial001.py!}18+ ```19+20 In this case, the *CLI argument* `name` will have a default value of `"World"`, but will also read any value passed to the environment variable `AWESOME_NAME` if no value is provided in the command line:21 22 <div class="termy">23 37 unmodified lines61 ## Multiple environment variables62 63 You are not restricted to a single environment variable, you can declare a list of environment variables that could be used to get a value if it was not passed in the command line:64 54-```Python hl_lines="4"55-{!../docs_src/arguments/envvar/tutorial002.py!}56-```65+=== "Python 3.6+"66 67+ ```Python hl_lines="6"68+ {!> ../docs_src/arguments/envvar/tutorial002_an.py!}69+ ```70+71+=== "Python 3.6+ non-Annotated"72+73+ !!! tip74+ Prefer to use the `Annotated` version if possible.75+76+ ```Python hl_lines="4"77+ {!> ../docs_src/arguments/envvar/tutorial002.py!}78+ ```79+80 Check it:81 82 <div class="termy">83 27 unmodified lines111 ## Hide an env var from the help text112 113 By default, environment variables used will be shown in the help text, but you can disable them with `show_envvar=False`:114 93-```Python hl_lines="4"94-{!../docs_src/arguments/envvar/tutorial003.py!}95-```115+=== "Python 3.6+"116 117+ ```Python hl_lines="7"118+ {!> ../docs_src/arguments/envvar/tutorial003_an.py!}119+ ```120+121+=== "Python 3.6+ non-Annotated"122+123+ !!! tip124+ Prefer to use the `Annotated` version if possible.125+126+ ```Python hl_lines="4"127+ {!> ../docs_src/arguments/envvar/tutorial003.py!}128+ ```129+130 Check it:131 132 <div class="termy">133 27 unmodified linesmodified:docs/tutorial/arguments/help.md+112 added-24 removed
10 unmodified lines11 ## Add a `help` text for a *CLI argument*12 13 You can use the `help` parameter to add a help text for a *CLI argument*:14 15-```Python hl_lines="4"16-{!../docs_src/arguments/help/tutorial001.py!}17-```15+=== "Python 3.6+"16 17+ ```Python hl_lines="5"18+ {!> ../docs_src/arguments/help/tutorial001_an.py!}19+ ```20+21+=== "Python 3.6+ non-Annotated"22+23+ !!! tip24+ Prefer to use the `Annotated` version if possible.25+26+ ```Python hl_lines="4"27+ {!> ../docs_src/arguments/help/tutorial001.py!}28+ ```29+30 And it will be used in the automatic `--help` option:31 32 <div class="termy">33 17 unmodified lines51 ## Combine help text and docstrings52 53 And of course, you can also combine that `help` with the <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>:54 44-```Python hl_lines="4 5 6 7"45-{!../docs_src/arguments/help/tutorial002.py!}46-```55+=== "Python 3.6+"56 57+ ```Python hl_lines="5-8"58+ {!> ../docs_src/arguments/help/tutorial002_an.py!}59+ ```60+61+=== "Python 3.6+ non-Annotated"62+63+ !!! tip64+ Prefer to use the `Annotated` version if possible.65+66+ ```Python hl_lines="4-7"67+ {!> ../docs_src/arguments/help/tutorial002.py!}68+ ```69+70 And the `--help` option will combine all the information:71 72 <div class="termy">73 19 unmodified lines93 ## Help with defaults94 95 If you have a *CLI argument* with a default value, like `"World"`:96 75-```Python hl_lines="4"76-{!../docs_src/arguments/help/tutorial003.py!}77-```97+=== "Python 3.6+"98 99+ ```Python hl_lines="5"100+ {!> ../docs_src/arguments/help/tutorial003_an.py!}101+ ```102+103+=== "Python 3.6+ non-Annotated"104+105+ !!! tip106+ Prefer to use the `Annotated` version if possible.107+108+ ```Python hl_lines="4"109+ {!> ../docs_src/arguments/help/tutorial003.py!}110+ ```111+112 It will show that default value in the help text:113 114 <div class="termy">115 17 unmodified lines133 </div>134 135 But you can disable that if you want to, with `show_default=False`:136 104-```Python hl_lines="4"105-{!../docs_src/arguments/help/tutorial004.py!}106-```137+=== "Python 3.6+"138 139+ ```Python hl_lines="7"140+ {!> ../docs_src/arguments/help/tutorial004_an.py!}141+ ```142+143+=== "Python 3.6+ non-Annotated"144+145+ !!! tip146+ Prefer to use the `Annotated` version if possible.147+148+ ```Python hl_lines="4"149+ {!> ../docs_src/arguments/help/tutorial004.py!}150+ ```151+152 And then it won't show the default value:153 154 <div class="termy">155 25 unmodified lines181 ## Custom default string182 183 You can use the same `show_default` to pass a custom string (instead of a `bool`) to customize the default value to be shown in the help text:184 141-```Python hl_lines="6"142-{!../docs_src/arguments/help/tutorial005.py!}143-```185+=== "Python 3.6+"186 187+ ```Python hl_lines="9"188+ {!> ../docs_src/arguments/help/tutorial005_an.py!}189+ ```190+191+=== "Python 3.6+ non-Annotated"192+193+ !!! tip194+ Prefer to use the `Annotated` version if possible.195+196+ ```Python hl_lines="6"197+ {!> ../docs_src/arguments/help/tutorial005.py!}198+ ```199+200 And it will be used in the help text:201 202 <div class="termy">203 37 unmodified lines241 But you can customize it with the `metavar` parameter for `typer.Argument()`.242 243 For example, let's say you don't want to have the default of `NAME`, you want to have `username`, in lowercase, and you really want ✨ emojis ✨ everywhere:244 190-```Python hl_lines="4"191-{!../docs_src/arguments/help/tutorial006.py!}192-```245+=== "Python 3.6+"246 247+ ```Python hl_lines="5"248+ {!> ../docs_src/arguments/help/tutorial006_an.py!}249+ ```250+251+=== "Python 3.6+ non-Annotated"252+253+ !!! tip254+ Prefer to use the `Annotated` version if possible.255+256+ ```Python hl_lines="4"257+ {!> ../docs_src/arguments/help/tutorial006.py!}258+ ```259+260 Now the generated help text will have `✨username✨` instead of `NAME`:261 262 <div class="termy">263 18 unmodified lines282 You might want to show the help information for *CLI arguments* in different panels when using the `--help` option.283 284 If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel where you want this *CLI argument* to be shown:285 220-```Python hl_lines="7 10"221-{!../docs_src/arguments/help/tutorial007.py!}222-```286+=== "Python 3.6+"287 288+ ```Python hl_lines="8 12"289+ {!> ../docs_src/arguments/help/tutorial007_an.py!}290+ ```291+292+=== "Python 3.6+ non-Annotated"293+294+ !!! tip295+ Prefer to use the `Annotated` version if possible.296+297+ ```Python hl_lines="7 10"298+ {!> ../docs_src/arguments/help/tutorial007.py!}299+ ```300+301 Then, if you check the `--help` option, you will see a default panel named "`Arguments`" for the *CLI arguments* that don't have a custom `rich_help_panel`.302 303 And 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 lines343 If you want, you can make a *CLI argument* **not** show up in the `Arguments` section in the help text.344 345 You will probably not want to do this normally, but it's possible:346 270-```Python hl_lines="4"271-{!../docs_src/arguments/help/tutorial008.py!}272-```347+=== "Python 3.6+"348 349+ ```Python hl_lines="5"350+ {!> ../docs_src/arguments/help/tutorial008_an.py!}351+ ```352+353+=== "Python 3.6+ non-Annotated"354+355+ !!! tip356+ Prefer to use the `Annotated` version if possible.357+358+ ```Python hl_lines="4"359+ {!> ../docs_src/arguments/help/tutorial008.py!}360+ ```361+362 Check it:363 364 <div class="termy">365 43 unmodified linesmodified:docs/tutorial/arguments/optional.md+98 added-21 removed
27 unmodified lines28 ```29 30 </div>31 32-### An alternative *CLI argument* declaration32+## An alternative *CLI argument* declaration33 34 In the [First Steps](../first-steps.md#add-a-cli-argument){.internal-link target=_blank} you saw how to add a *CLI argument*:35 36 ```Python hl_lines="4"1 unmodified line38 ```39 40 Now let's see an alternative way to create the same *CLI argument*:41 42+42-```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 ```46 47+!!! info48+ Typer added support for `Annotated` (and started recommending it) in version 0.9.0.49+50+ If you have an older version, you would get errors when trying to use `Annotated`.51+52+ Make sure you Upgrade the Typer version to at least 0.9.0 before using `Annotated`.53+54 Before, you had this function parameter:55 56 ```Python57 name: str58 ```59 52-And because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.60+And now we wrap it with `Annotated`:61 54-**Typer** does the same and makes it a **required** *CLI argument*.55-56-And then we changed it to:57-62 ```Python59-name: str = typer.Argument(...)63+name: Annotated[str]64 ```65 62-But 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).66+Both of these versions mean the same thing, `Annotated` is part of standard Python and is there for this.67 64-As 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.68+But the second version using `Annotated` allows us to pass additional metadata that can be used by **Typer**:69 66-To make it *required*, we pass `...` as the first function argument passed to `typer.Argument(...)`.70+```Python71+name: Annotated[str, typer.Argument()]72+```73 68-!!! 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>.74+Now 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).75 76 All we did there achieves the same thing as before, a **required** *CLI argument*:77 78 <div class="termy">10 unmodified lines89 </div>90 91 It's still not very useful, but it works correctly.92 88-And 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.93+And being able to declare a **required** *CLI argument* using94 90-### Make an optional *CLI argument*95+```Python96+name: Annoated[str, typer.Argument()]97+```98 99+...that works exactly the same as100+101+```Python102+name: str103+```104+105+...will come handy later.106+107+## Make an optional *CLI argument*108+109 Now, finally what we came for, an optional *CLI argument*.110 111 To make a *CLI argument* optional, use `typer.Argument()` and pass a different "default" as the first parameter to `typer.Argument()`, for example `None`:112 96-```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 ```116 117 Now we have:118 119 ```Python103-name: Optional[str] = typer.Argument(None)120+name: Annotated[Optional[str], typer.Argument()] = None121 ```122 123 Because we are using `typer.Argument()` **Typer** will know that this is a *CLI argument* (no matter if *required* or *optional*).124 108-And 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`.109-125 !!! 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`.127 128 Check the help:41 unmodified lines170 </div>171 172 !!! 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.174+175+## Alternative (old) `typer.Argument()` as the default value176+177+**Typer** also supports another older alternative syntax for declaring *CLI arguments* with additional metadata.178+179+Instead of using `Annotated`, you can use `typer.Argument()` as the default value:180+181+```Python hl_lines="4"182+{!> ../docs_src/arguments/optional/tutorial001.py!}183+```184+185+!!! tip186+ Prefer to use the `Annotated` version if possible.187+188+Before, because `name` didn't have any default value it would be a **required parameter** for the Python function, in Python terms.189+190+When using `typer.Argument()` as the default value **Typer** does the same and makes it a **required** *CLI argument*.191+192+We changed it to:193+194+```Python195+name: str = typer.Argument()196+```197+198+But 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).199+200+As 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.201+202+Not 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=...)`.203+204+```Python205+name: str = typer.Argument(default=...)206+```207+208+!!! 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>.210+211+```Python hl_lines="4"212+{!> ../docs_src/arguments/optional/tutorial003.py!}213+```214+215+And the same way, you can make it optional by passing a different `default` value, for example `None`:216+217+```Python hl_lines="6"218+{!> ../docs_src/arguments/optional/tutorial002.py!}219+```220+221+Because the first parameter passed to `typer.Argument(default=None)` (the new "default" value) is `None`, **Typer** knows that this is an **optional** *CLI argument*, if no value is provided when calling it in the command line, it will have that default value of `None`.222+223+The `default` argument is the first one, so it's possible that you see code that passes the value without explicitly using `default=`, like:224+225+```Python226+name: str = typer.Argument(...)227+```228+229+...or like:230+231+```Python232+name: str = typer.Argument(None)233+```234+235+...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
1 The same as before, you can add help for the commands in the docstrings and the *CLI options*.2 3 And the `typer.Typer()` application receives a parameter `help` that you can pass with the main help text for your CLI program:4 5-```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+"6 7+ ```Python hl_lines="4 9-11 22 26-30 43 47-51 60-62"8+ {!> ../docs_src/commands/help/tutorial001_an.py!}9+ ```10+11+=== "Python 3.6+ non-Annotated"12+13+ !!! tip14+ Prefer to use the `Annotated` version if possible.15+16+ ```Python hl_lines="3 8-10 20 23-27 39 42-46 55-57"17+ {!> ../docs_src/commands/help/tutorial001.py!}18+ ```19+20 Check it:21 22 <div class="termy">23 176 unmodified lines200 ### Rich Markup201 202 If 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:203 193-```Python hl_lines="3 9 13-15 20 22 24"194-{!../docs_src/commands/help/tutorial004.py!}195-```204+=== "Python 3.6+"205 206+ ```Python hl_lines="4 10 14-16 21 24 27"207+ {!> ../docs_src/commands/help/tutorial004_an.py!}208+ ```209+210+=== "Python 3.6+ non-Annotated"211+212+ !!! tip213+ Prefer to use the `Annotated` version if possible.214+215+ ```Python hl_lines="3 9 13-15 20 22 24"216+ {!> ../docs_src/commands/help/tutorial004.py!}217+ ```218+219 With 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>.220 221 You can also use markup in the help for the `username` CLI Argument.222 53 unmodified lines276 ### Rich Markdown277 278 If you set `rich_markup_mode="markdown"` when creating the `typer.Typer()` app, you will be able to use Markdown in the docstring:279 258-```Python hl_lines="3 7 9-17 22 24-25"259-{!../docs_src/commands/help/tutorial005.py!}260-```280+=== "Python 3.6+"281 282+ ```Python hl_lines="4 9 12-20 25 27-28"283+ {!> ../docs_src/commands/help/tutorial005_an.py!}284+ ```285+286+=== "Python 3.6+ non-Annotated"287+288+ !!! tip289+ Prefer to use the `Annotated` version if possible.290+291+ ```Python hl_lines="3 7 9-17 22 24-25"292+ {!> ../docs_src/commands/help/tutorial005.py!}293+ ```294+295 With 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>.296 297 And the same as before, the help text overwritten for the command `delete` can also use Markdown.298 63 unmodified lines362 ### Help Panels for Commands363 364 To set the panel for a command you can pass the argument `rich_help_panel` with the name of the panel you want to use:365 333-```Python hl_lines="22 30 38 46"334-{!../docs_src/commands/help/tutorial006.py!}335-```366+=== "Python 3.6+"367 368+ ```Python hl_lines="22 30 38 46"369+ {!> ../docs_src/commands/help/tutorial006.py!}370+ ```371+372 Commands without a panel will be shown in the default panel `Commands`, and the rest will be shown in the next panels:373 374 <div class="termy">375 31 unmodified lines407 The same way, you can configure the panels for *CLI arguments* and *CLI options* with `rich_help_panel`.408 409 And of course, in the same application you can also set the `rich_help_panel` for commands.410 376-```Python hl_lines="12 16 21 30"377-{!../docs_src/commands/help/tutorial007.py!}378-```411+=== "Python 3.6+"412 413+ ```Python hl_lines="15 21 27 37"414+ {!> ../docs_src/commands/help/tutorial007_an.py!}415+ ```416+417+=== "Python 3.6+ non-Annotated"418+419+ !!! tip420+ Prefer to use the `Annotated` version if possible.421+422+ ```Python hl_lines="12 16 21 30"423+ {!> ../docs_src/commands/help/tutorial007.py!}424+ ```425+426 Then if you run the application you will see all the *CLI parameters* in their respective panels.427 428 * 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 linesmodified:docs/tutorial/commands/options.md+14 added-3 removed
1 Commands can also have their own *CLI options*.2 3 In fact, each command can have different *CLI arguments* and *CLI options*:4 5-```Python hl_lines="7 13 14 24 33"6-{!../docs_src/commands/options/tutorial001.py!}7-```5+=== "Python 3.6+"6 7+ ```Python hl_lines="8 14-17 27-29 38"8+ {!> ../docs_src/commands/options/tutorial001_an.py!}9+ ```10+11+=== "Python 3.6+ non-Annotated"12+13+ !!! tip14+ Prefer to use the `Annotated` version if possible.15+16+ ```Python hl_lines="7 13-14 24 33"17+ {!> ../docs_src/commands/options/tutorial001.py!}18+ ```19+20 Here we have multiple commands, with different *CLI parameters*:21 22 * `create`:23 * `username`: a *CLI argument*.84 unmodified linesmodified:docs/tutorial/multiple-values/arguments-with-multiple-values.md+14 added-3 removed
29 unmodified lines303132333435363435363738394041424344454647484950515235 unmodified lines29 unmodified lines## *CLI arguments* with tuples
If you want a specific number of values and types, you can use a tuple, and it can even have default values:
```Python hl_lines="7 8"{!../docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py!}```=== "Python 3.6+"
```Python hl_lines="8-10" {!> ../docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py!} ```
=== "Python 3.6+ non-Annotated"
!!! tip Prefer to use the `Annotated` version if possible.
```Python hl_lines="7-8" {!> ../docs_src/multiple_values/arguments_with_multiple_values/tutorial002.py!} ```
Check it:
<div class="termy">
35 unmodified linesmodified:docs/tutorial/multiple-values/multiple-options.md+28 added-6 removed
2 unmodified lines3 For example, let's say you want to accept several users in a single execution.4 5 For this, use the standard Python `typing.List` to declare it as a `list` of `str`:6 7-```Python hl_lines="1 6"8-{!../docs_src/multiple_values/multiple_options/tutorial001.py!}9-```7+=== "Python 3.6+"8 9+ ```Python hl_lines="1 7"10+ {!> ../docs_src/multiple_values/multiple_options/tutorial001_an.py!}11+ ```12+13+=== "Python 3.6+ non-Annotated"14+15+ !!! tip16+ Prefer to use the `Annotated` version if possible.17+18+ ```Python hl_lines="1 6"19+ {!> ../docs_src/multiple_values/multiple_options/tutorial001.py!}20+ ```21+22 You will receive the values as you declared them, as a `list` of `str`.23 24 Check it:25 23 unmodified lines49 ## Multiple `float`50 51 The same way, you can use other types and they will be converted by **Typer** to their declared type:52 42-```Python hl_lines="6"43-{!../docs_src/multiple_values/multiple_options/tutorial002.py!}44-```53+=== "Python 3.6+"54 55+ ```Python hl_lines="7"56+ {!> ../docs_src/multiple_values/multiple_options/tutorial002_an.py!}57+ ```58+59+=== "Python 3.6+ non-Annotated"60+61+ !!! tip62+ Prefer to use the `Annotated` version if possible.63+64+ ```Python hl_lines="6"65+ {!> ../docs_src/multiple_values/multiple_options/tutorial002.py!}66+ ```67+68 Check it:69 70 <div class="termy">71 17 unmodified linesmodified:docs/tutorial/multiple-values/options-with-multiple-values.md+14 added-3 removed
2 unmodified lines3 You can set the number of values and types to anything you want, but it has to be a fixed number of values.4 5 For this, use the standard Python `typing.Tuple`:6 7-```Python hl_lines="1 6"8-{!../docs_src/multiple_values/options_with_multiple_values/tutorial001.py!}9-```7+=== "Python 3.6+"8 9+ ```Python hl_lines="1 7"10+ {!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py!}11+ ```12+13+=== "Python 3.6+ non-Annotated"14+15+ !!! tip16+ Prefer to use the `Annotated` version if possible.17+18+ ```Python hl_lines="1 6"19+ {!> ../docs_src/multiple_values/options_with_multiple_values/tutorial001.py!}20+ ```21+22 Each of the internal types defines the type of each value in the tuple.23 24 So:25 78 unmodified linesmodified:docs/tutorial/options/callback-and-context.md+56 added-12 removed
4 unmodified lines5 ## Validate *CLI parameters*6 7 For example, you could do some validation before the rest of the code is executed.8 9-```Python hl_lines="4 5 6 7 10"10-{!../docs_src/options/callback/tutorial001.py!}11-```9+=== "Python 3.6+"10 11+ ```Python hl_lines="5-8 11"12+ {!> ../docs_src/options/callback/tutorial001_an.py!}13+ ```14+15+=== "Python 3.6+ non-Annotated"16+17+ !!! tip18+ Prefer to use the `Annotated` version if possible.19+20+ ```Python hl_lines="4-7 10"21+ {!> ../docs_src/options/callback/tutorial001.py!}22+ ```23+24 Here you pass a function to `typer.Option()` or `typer.Argument()` with the keyword argument `callback`.25 26 The function receives the value from the command line. It can do anything with it, and then return the value.27 76 unmodified lines104 ### Breaking completion in a callback105 106 Let's say that when the callback is running, we want to show a message saying that it's validating the name:107 97-```Python hl_lines="5"98-{!../docs_src/options/callback/tutorial002.py!}99-```108+=== "Python 3.6+"109 110+ ```Python hl_lines="6"111+ {!> ../docs_src/options/callback/tutorial002_an.py!}112+ ```113+114+=== "Python 3.6+ non-Annotated"115+116+ !!! tip117+ Prefer to use the `Annotated` version if possible.118+119+ ```Python hl_lines="5"120+ {!> ../docs_src/options/callback/tutorial002.py!}121+ ```122+123 And because the callback will be called when the shell calls your program asking for completion, that message `"Validating name"` will be printed and it will break completion.124 125 It will look something like:126 25 unmodified lines152 But you can access the context by declaring a function parameter of type `typer.Context`.153 154 The "context" has some additional data about the current execution of your program:155 134-```Python hl_lines="4 5 6"135-{!../docs_src/options/callback/tutorial003.py!}136-```156+=== "Python 3.6+"157 158+ ```Python hl_lines="5-7"159+ {!> ../docs_src/options/callback/tutorial003_an.py!}160+ ```161+162+=== "Python 3.6+ non-Annotated"163+164+ !!! tip165+ Prefer to use the `Annotated` version if possible.166+167+ ```Python hl_lines="4-6"168+ {!> ../docs_src/options/callback/tutorial003.py!}169+ ```170+171 The `ctx.resilient_parsing` will be `True` when handling completion, so you can just return without printing anything else.172 173 But it will be `False` when calling the program normally. So you can continue the execution of your previous code.174 22 unmodified lines197 ## Using the `CallbackParam` object198 199 The same way you can access the `typer.Context` by declaring a function parameter with its value, you can declare another function parameter with type `typer.CallbackParam` to get the specific Click `Parameter` object.200 168-```Python hl_lines="4 7"169-{!../docs_src/options/callback/tutorial004.py!}170-```201+=== "Python 3.6+"202 203+ ```Python hl_lines="5 8"204+ {!> ../docs_src/options/callback/tutorial004_an.py!}205+ ```206+207+=== "Python 3.6+ non-Annotated"208+209+ !!! tip210+ Prefer to use the `Annotated` version if possible.211+212+ ```Python hl_lines="4 7"213+ {!> ../docs_src/options/callback/tutorial004.py!}214+ ```215+216 It's probably not very common, but you could do it if you need it.217 218 For example if you had a callback that could be used by several *CLI parameters*, that way the callback could know which parameter is each time.219 42 unmodified linesmodified:docs/tutorial/options/help.md+45 added-22 removed
1 You already saw how to add a help text for *CLI arguments* with the `help` parameter.2 3 Let's now do the same for *CLI options*:4 5-```Python hl_lines="6 7"6-{!../docs_src/options/help/tutorial001.py!}7-```5+=== "Python 3.6+"6 9-We 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+ ```10 11-As 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"12 13-So, if we had:13+ !!! tip14+ Prefer to use the `Annotated` version if possible.15 15-```Python16-lastname: str = ""17-```16+ ```Python hl_lines="6-7"17+ {!> ../docs_src/options/help/tutorial001.py!}18+ ```19 19-now we write:20+The same way as with `typer.Argument()`, we can put `typer.Option()` inside of `Annotated`.21 22+We can then pass the `help` keyword parameter:23+24 ```Python22-lastname: str = typer.Option("")25+lastname: Annotated[str, typer.Option(help="this option does this and that")] = ""26 ```27 25-And 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*.29 27-And then we can pass the `help` keyword parameter:30+The same way as with `typer.Argument()`, **Typer** also supports the old style using the function parameter default value:31 32 ```Python30-lastname: str = typer.Option("", help="this option does this and that")33+lastname: str = typer.Option(default="", help="this option does this and that")34 ```35 33-to create the help for that *CLI option*.34-36 Copy that example from above to a file `main.py`.37 38 Test it:39 28 unmodified lines68 The same as with *CLI arguments*, you can put the help for some *CLI options* in different panels to be shown with the `--help` option.69 70 If you have installed Rich as described in the docs for [Printing and Colors](../printing.md){.internal-link target=_blank}, you can set the `rich_help_panel` parameter to the name of the panel you want for each *CLI option*:71 71-```Python hl_lines="8 11"72-{!../docs_src/options/help/tutorial002.py!}73-```72+=== "Python 3.6+"73 74+ ```Python hl_lines="11 17"75+ {!> ../docs_src/options/help/tutorial002_an.py!}76+ ```77+78+=== "Python 3.6+ non-Annotated"79+80+ !!! tip81+ Prefer to use the `Annotated` version if possible.82+83+ ```Python hl_lines="8 11"84+ {!> ../docs_src/options/help/tutorial002.py!}85+ ```86+87 Now, when you check the `--help` option, you will see a default panel named "`Options`" for the *CLI options* that don't have a custom `rich_help_panel`.88 89 And 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 lines132 ## Hide default from help133 134 You can tell Typer to not show the default value in the help text with `show_default=False`:135 124-```Python hl_lines="4"125-{!../docs_src/options/help/tutorial003.py!}126-```136+=== "Python 3.6+"137 138+ ```Python hl_lines="5"139+ {!> ../docs_src/options/help/tutorial003_an.py!}140+ ```141+142+=== "Python 3.6+ non-Annotated"143+144+ !!! tip145+ Prefer to use the `Annotated` version if possible.146+147+ ```Python hl_lines="4"148+ {!> ../docs_src/options/help/tutorial003.py!}149+ ```150+151 And it will no longer show the default value in the help text:152 153 <div class="termy">154 25 unmodified linesmodified:docs/tutorial/options/name.md+77 added-20 removed
8 unmodified lines9 10 or11 12 ```Python13-def main(user_name: Optional[str] = typer.Option(None)):13+def main(user_name: Annotated[Optional[str], typer.Option()] = None):14 pass15 ```16 17 **Typer** will create a *CLI option*:5 unmodified lines23 But you can customize it if you want to.24 25 Let's say the function parameter name is `user_name` as above, but you want the *CLI option* to be just `--name`.26 27-You can pass the *CLI option* name that you want to have in the next positional argument passed to `typer.Option()`:27+You can pass the *CLI option* name that you want to have in the following positional argument passed to `typer.Option()`:28 29-```Python hl_lines="4"30-{!../docs_src/options/name/tutorial001.py!}31-```29+=== "Python 3.6+"30 33-Here 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+ ```34 35+ Here you are passing the string `"--name"` as the first positional argument to `typer.Option()`.36+37+=== "Python 3.6+ non-Annotated"38+39+ !!! tip40+ Prefer to use the `Annotated` version if possible.41+42+ ```Python hl_lines="4"43+ {!> ../docs_src/options/name/tutorial001.py!}44+ ```45+46+ 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.47+48 !!! 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.50 51 For example `show_default=True` is a keyword argument. "`show_default`" is the keyword.52 40- 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()`.54 55 That's a "positional argument" in a function.56 57 Check it:126 unmodified lines184 ### Defining *CLI option* short names185 186 In **Typer** you can also define *CLI option* short names the same way you can customize the long names.187 175-`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).188+YOu can pass *positional* arguments to `typer.Option()` to define the *CLI option* name(s).189 190 !!! tip191 Remember the *positional* function arguments are those that don't have a keyword.192 2 unmodified lines195 You can overwrite the *CLI option* name to use as in the previous example, but you can also declare extra alternatives, including short names.196 197 For example, extending the previous example, let's add a *CLI option* short name `-n`:198 186-```Python hl_lines="4"187-{!../docs_src/options/name/tutorial002.py!}188-```199+=== "Python 3.6+"200 201+ ```Python hl_lines="5"202+ {!> ../docs_src/options/name/tutorial002_an.py!}203+ ```204+205+=== "Python 3.6+ non-Annotated"206+207+ !!! tip208+ Prefer to use the `Annotated` version if possible.209+210+ ```Python hl_lines="4"211+ {!> ../docs_src/options/name/tutorial002.py!}212+ ```213+214 Here we are overwriting the *CLI option* name that by default would be `--user-name`, and we are defining it to be `--name`. And we are also declaring a *CLI option* short name of `-n`.215 216 Check it:217 23 unmodified lines241 ### *CLI option* only short name242 243 If you only declare a short name like `-n` then that will be the only *CLI option* name. And neither `--name` nor `--user-name` will be available.244 221-```Python hl_lines="4"222-{!../docs_src/options/name/tutorial003.py!}223-```245+=== "Python 3.6+"246 247+ ```Python hl_lines="5"248+ {!> ../docs_src/options/name/tutorial003_an.py!}249+ ```250+251+=== "Python 3.6+ non-Annotated"252+253+ !!! tip254+ Prefer to use the `Annotated` version if possible.255+256+ ```Python hl_lines="4"257+ {!> ../docs_src/options/name/tutorial003.py!}258+ ```259+260 Check it:261 262 <div class="termy">263 20 unmodified lines284 ### *CLI option* short name and default285 286 Continuing with the example above, as **Typer** allows you to declare a *CLI option* as having only a short name, if you want to have the default long name plus a short name, you have to declare both explicitly:287 253-```Python hl_lines="4"254-{!../docs_src/options/name/tutorial004.py!}255-```288+=== "Python 3.6+"289 290+ ```Python hl_lines="5"291+ {!> ../docs_src/options/name/tutorial004_an.py!}292+ ```293+294+=== "Python 3.6+ non-Annotated"295+296+ !!! tip297+ Prefer to use the `Annotated` version if possible.298+299+ ```Python hl_lines="4"300+ {!> ../docs_src/options/name/tutorial004.py!}301+ ```302+303 Check it:304 305 <div class="termy">306 26 unmodified lines333 You can create multiple short names and use them together.334 335 You don't have to do anything special for it to work (apart from declaring those short versions):336 291-```Python hl_lines="5 6"292-{!../docs_src/options/name/tutorial005.py!}293-```337+=== "Python 3.6+"338 339+ ```Python hl_lines="6-7"340+ {!> ../docs_src/options/name/tutorial005_an.py!}341+ ```342+343+=== "Python 3.6+ non-Annotated"344+345+ !!! tip346+ Prefer to use the `Annotated` version if possible.347+348+ ```Python hl_lines="5-6"349+ {!> ../docs_src/options/name/tutorial005.py!}350+ ```351+352 !!! tip353 Notice that, again, we are declaring the long and short version of the *CLI option* names.354 355 Check it:30 unmodified linesmodified:docs/tutorial/options/password.md+28 added-6 removed
1 Apart from having a prompt, you can make a *CLI option* have a `confirmation_prompt=True`:2 3-```Python hl_lines="5"4-{!../docs_src/options/password/tutorial001.py!}5-```3+=== "Python 3.6+"4 5+ ```Python hl_lines="7"6+ {!> ../docs_src/options/password/tutorial001_an.py!}7+ ```8+9+=== "Python 3.6+ non-Annotated"10+11+ !!! tip12+ Prefer to use the `Annotated` version if possible.13+14+ ```Python hl_lines="5"15+ {!> ../docs_src/options/password/tutorial001.py!}16+ ```17+18 And the CLI program will ask for confirmation:19 20 <div class="termy">21 18 unmodified lines40 You can achieve the same using `hide_input=True`.41 42 And if you combine it with `confirmation_prompt=True` you can easily receive a password with double confirmation:43 33-```Python hl_lines="6 7 8"34-{!../docs_src/options/password/tutorial002.py!}35-```44+=== "Python 3.6+"45 46+ ```Python hl_lines="8"47+ {!> ../docs_src/options/password/tutorial002_an.py!}48+ ```49+50+=== "Python 3.6+ non-Annotated"51+52+ !!! tip53+ Prefer to use the `Annotated` version if possible.54+55+ ```Python hl_lines="6-8"56+ {!> ../docs_src/options/password/tutorial002.py!}57+ ```58+59 Check it:60 61 <div class="termy">62 13 unmodified linesmodified:docs/tutorial/options/prompt.md+42 added-9 removed
1 It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:2 3-```Python hl_lines="4"4-{!../docs_src/options/prompt/tutorial001.py!}5-```3+=== "Python 3.6+"4 5+ ```Python hl_lines="5"6+ {!> ../docs_src/options/prompt/tutorial001_an.py!}7+ ```8+9+=== "Python 3.6+ non-Annotated"10+11+ !!! tip12+ Prefer to use the `Annotated` version if possible.13+14+ ```Python hl_lines="4"15+ {!> ../docs_src/options/prompt/tutorial001.py!}16+ ```17+18 And then your program will ask the user for it in the terminal:19 20 <div class="termy">21 12 unmodified lines34 ## Customize the prompt35 36 You can also set a custom prompt, passing the string that you want to use instead of just `True`:37 27-```Python hl_lines="5"28-{!../docs_src/options/prompt/tutorial002.py!}29-```38+=== "Python 3.6+"39 40+ ```Python hl_lines="7"41+ {!> ../docs_src/options/prompt/tutorial002_an.py!}42+ ```43+44+=== "Python 3.6+ non-Annotated"45+46+ !!! tip47+ Prefer to use the `Annotated` version if possible.48+49+ ```Python hl_lines="5"50+ {!> ../docs_src/options/prompt/tutorial002.py!}51+ ```52+53 And then your program will ask for it using with your custom prompt:54 55 <div class="termy">56 16 unmodified lines73 You can do it passing the parameter `confirmation_prompt=True`.74 75 Let's say it's a CLI app to delete a project:76 55-```Python hl_lines="4"56-{!../docs_src/options/prompt/tutorial003.py!}57-```77+=== "Python 3.6+"78 79+ ```Python hl_lines="6"80+ {!> ../docs_src/options/prompt/tutorial003_an.py!}81+ ```82+83+=== "Python 3.6+ non-Annotated"84+85+ !!! tip86+ Prefer to use the `Annotated` version if possible.87+88+ ```Python hl_lines="4"89+ {!> ../docs_src/options/prompt/tutorial003.py!}90+ ```91+92 And it will prompt the user for a value and then for the confirmation:93 94 <div class="termy">95 26 unmodified linesmodified:docs/tutorial/options/required.md+27 added-6 removed
5 unmodified lines6 Well, that's how they work *by default*, and that's the convention in many CLI programs and systems.7 8 But if you really want, you can change that.9 10-To make a *CLI option* required, pass `...` to `typer.Option()`.10+To make a *CLI option* required, you can put `typer.Option()` inside of `Annotated` and leave the parameter without a default value.11 12+Let's make `--lastname` a required *CLI option*:13+14+=== "Python 3.6+"15+16+ ```Python hl_lines="5"17+ {!> ../docs_src/options/required/tutorial001_an.py!}18+ ```19+20+The same way as with `typer.Argument()`, the old style of using the function parameter default value is also supported, in that case you would just not pass anything to the `default` parameter.21+22+=== "Python 3.6+ non-Annotated"23+24+ ```Python hl_lines="4"25+ {!> ../docs_src/options/required/tutorial001.py!}26+ ```27+28+Or you can explictily pass `...` to `typer.Option(default=...)`:29+30+=== "Python 3.6+ non-Annotated"31+32+ ```Python hl_lines="4"33+ {!> ../docs_src/options/required/tutorial002.py!}34+ ```35+36 !!! 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>.38 39 That will tell **Typer** that it's still a *CLI option*, but it doesn't have a default value, and it's required.40 17-Let'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**.43 19-```Python hl_lines="4"20-{!../docs_src/options/required/tutorial001.py!}21-```22-44 And test it:45 46 <div class="termy">47 30 unmodified linesmodified:docs/tutorial/options/version.md+42 added-9 removed
4 unmodified lines5 ## First version of `--version`6 7 Let's see a first version of how it could look like:8 9-```Python hl_lines="8-11 16-18"10-{!../docs_src/options/version/tutorial001.py!}11-```9+=== "Python 3.6+"10 11+ ```Python hl_lines="9-12 17-19"12+ {!> ../docs_src/options/version/tutorial001_an.py!}13+ ```14+15+=== "Python 3.6+ non-Annotated"16+17+ !!! tip18+ Prefer to use the `Annotated` version if possible.19+20+ ```Python hl_lines="8-11 16-18"21+ {!> ../docs_src/options/version/tutorial001.py!}22+ ```23+24 !!! 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.26 27 If the `--version` *CLI option* is passed, we get a value `True` in the callback.39 unmodified lines67 ## Previous parameters and `is_eager`68 69 But now let's say that the `--name` *CLI option* that we declared before `--version` is required, and it has a callback that could exit the program:70 60-```Python hl_lines="14-16 21-23"61-{!../docs_src/options/version/tutorial002.py!}62-```71+=== "Python 3.6+"72 73+ ```Python hl_lines="15-17 22-24"74+ {!> ../docs_src/options/version/tutorial002_an.py!}75+ ```76+77+=== "Python 3.6+ non-Annotated"78+79+ !!! tip80+ Prefer to use the `Annotated` version if possible.81+82+ ```Python hl_lines="14-16 21-23"83+ {!> ../docs_src/options/version/tutorial002.py!}84+ ```85+86 Then our CLI program could not work as expected in some cases as it is *right now*, because if we use `--version` after `--name` then the callback for `--name` will be processed before and we can get its error:87 88 <div class="termy">89 20 unmodified lines110 For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.111 112 That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:113 92-```Python hl_lines="22-24"93-{!../docs_src/options/version/tutorial003.py!}94-```114+=== "Python 3.6+"115 116+ ```Python hl_lines="23-26"117+ {!> ../docs_src/options/version/tutorial003_an.py!}118+ ```119+120+=== "Python 3.6+ non-Annotated"121+122+ !!! tip123+ Prefer to use the `Annotated` version if possible.124+125+ ```Python hl_lines="22-24"126+ {!> ../docs_src/options/version/tutorial003.py!}127+ ```128+129 Check it:130 131 <div class="termy">132 8 unmodified linesmodified:docs/tutorial/parameter-types/bool.md+56 added-12 removed
6 unmodified lines7 Let's say that we want a `--force` *CLI option* only, we want to discard `--no-force`.8 9 We can do that by specifying the exact name we want:10 11-```Python hl_lines="4"12-{!../docs_src/parameter_types/bool/tutorial001.py!}13-```11+=== "Python 3.6+"12 13+ ```Python hl_lines="5"14+ {!> ../docs_src/parameter_types/bool/tutorial001_an.py!}15+ ```16+17+=== "Python 3.6+ non-Annotated"18+19+ !!! tip20+ Prefer to use the `Annotated` version if possible.21+22+ ```Python hl_lines="4"23+ {!> ../docs_src/parameter_types/bool/tutorial001.py!}24+ ```25+26 Now there's only a `--force` *CLI option*:27 28 <div class="termy">29 40 unmodified lines70 We might want to instead have `--accept` and `--reject`.71 72 We can do that by passing a single `str` with the 2 names for the `bool` *CLI option* separated by `/`:73 63-```Python hl_lines="6"64-{!../docs_src/parameter_types/bool/tutorial002.py!}65-```74+=== "Python 3.6+"75 76+ ```Python hl_lines="7"77+ {!> ../docs_src/parameter_types/bool/tutorial002_an.py!}78+ ```79+80+=== "Python 3.6+ non-Annotated"81+82+ !!! tip83+ Prefer to use the `Annotated` version if possible.84+85+ ```Python hl_lines="6"86+ {!> ../docs_src/parameter_types/bool/tutorial002.py!}87+ ```88+89 Check it:90 91 <div class="termy">92 33 unmodified lines126 The same way, you can declare short versions of the names for these *CLI options*.127 128 For example, let's say we want `-f` for `--force` and `-F` for `--no-force`:129 108-```Python hl_lines="4"109-{!../docs_src/parameter_types/bool/tutorial003.py!}110-```130+=== "Python 3.6+"131 132+ ```Python hl_lines="5"133+ {!> ../docs_src/parameter_types/bool/tutorial003_an.py!}134+ ```135+136+=== "Python 3.6+ non-Annotated"137+138+ !!! tip139+ Prefer to use the `Annotated` version if possible.140+141+ ```Python hl_lines="4"142+ {!> ../docs_src/parameter_types/bool/tutorial003.py!}143+ ```144+145 Check it:146 147 <div class="termy">148 28 unmodified lines177 If you want to (although it might not be a good idea), you can declare only *CLI option* names to set the `False` value.178 179 To do that, use a space and a single `/` and pass the negative name after:180 148-```Python hl_lines="4"149-{!../docs_src/parameter_types/bool/tutorial004.py!}150-```181+=== "Python 3.6+"182 183+ ```Python hl_lines="5"184+ {!> ../docs_src/parameter_types/bool/tutorial004_an.py!}185+ ```186+187+=== "Python 3.6+ non-Annotated"188+189+ !!! tip190+ Prefer to use the `Annotated` version if possible.191+192+ ```Python hl_lines="4"193+ {!> ../docs_src/parameter_types/bool/tutorial004.py!}194+ ```195+196 !!! tip197 Have in mind that it's a string with a preceding space and then a `/`.198 199 So, it's `" /-S"` not `"/-S"`.35 unmodified linesmodified:docs/tutorial/parameter-types/datetime.md+14 added-3 removed
58 unmodified lines59 * separated with "`/`"60 61 ...It's a crazy example, but let's say you also needed that strange format:62 63-```Python hl_lines="8"64-{!../docs_src/parameter_types/datetime/tutorial002.py!}65-```63+=== "Python 3.6+"64 65+ ```Python hl_lines="11"66+ {!> ../docs_src/parameter_types/datetime/tutorial002_an.py!}67+ ```68+69+=== "Python 3.6+ non-Annotated"70+71+ !!! tip72+ Prefer to use the `Annotated` version if possible.73+74+ ```Python hl_lines="8"75+ {!> ../docs_src/parameter_types/datetime/tutorial002.py!}76+ ```77+78 !!! tip79 Notice the last string in `formats`: `"%m/%d/%Y"`.80 81 Check it:16 unmodified linesmodified:docs/tutorial/parameter-types/enum.md+14 added-3 removed
43 unmodified lines44 ### Case insensitive Enum choices45 46 You can make an `Enum` (choice) *CLI parameter* be case-insensitive with the `case_sensitive` parameter:47 48-```Python hl_lines="13"49-{!../docs_src/parameter_types/enum/tutorial002.py!}50-```48+=== "Python 3.6+"49 50+ ```Python hl_lines="15"51+ {!> ../docs_src/parameter_types/enum/tutorial002_an.py!}52+ ```53+54+=== "Python 3.6+ non-Annotated"55+56+ !!! tip57+ Prefer to use the `Annotated` version if possible.58+59+ ```Python hl_lines="13"60+ {!> ../docs_src/parameter_types/enum/tutorial002.py!}61+ ```62+63 And then the values of the `Enum` will be checked no matter if lower case, upper case, or a mix:64 65 <div class="termy">66 13 unmodified linesmodified:docs/tutorial/parameter-types/file.md+71 added-16 removed
38 unmodified lines39 ```Python40 content = b"la cig\xc3\xbce\xc3\xb1a trae al ni\xc3\xb1o"41 ```42 43-You will get all the correct editor support, attributes, methods, etc for the file-like object:43+You will get all the correct editor support, attributes, methods, etc for the file-like object:`44 45-```Python hl_lines="4"46-{!../docs_src/parameter_types/file/tutorial001.py!}47-```45+=== "Python 3.6+"46 47+ ```Python hl_lines="5"48+ {!> ../docs_src/parameter_types/file/tutorial001_an.py!}49+ ```50+51+=== "Python 3.6+ non-Annotated"52+53+ !!! tip54+ Prefer to use the `Annotated` version if possible.55+56+ ```Python hl_lines="4"57+ {!> ../docs_src/parameter_types/file/tutorial001.py!}58+ ```59+60 Check it:61 62 <div class="termy">63 17 unmodified lines81 ## `FileTextWrite`82 83 For writing text, you can use `typer.FileTextWrite`:84 74-```Python hl_lines="4 5"75-{!../docs_src/parameter_types/file/tutorial002.py!}76-```85+=== "Python 3.6+"86 87+ ```Python hl_lines="5-6"88+ {!> ../docs_src/parameter_types/file/tutorial002_an.py!}89+ ```90+91+=== "Python 3.6+ non-Annotated"92+93+ !!! tip94+ Prefer to use the `Annotated` version if possible.95+96+ ```Python hl_lines="4-5"97+ {!> ../docs_src/parameter_types/file/tutorial002.py!}98+ ```99+100 This would be for writing human text, like:101 102 ```103 some settings31 unmodified lines135 You will receive `bytes` from it.136 137 It's useful for reading binary files like images:138 117-```Python hl_lines="4"118-{!../docs_src/parameter_types/file/tutorial003.py!}119-```139+=== "Python 3.6+"140 141+ ```Python hl_lines="5"142+ {!> ../docs_src/parameter_types/file/tutorial003_an.py!}143+ ```144+145+=== "Python 3.6+ non-Annotated"146+147+ !!! tip148+ Prefer to use the `Annotated` version if possible.149+150+ ```Python hl_lines="4"151+ {!> ../docs_src/parameter_types/file/tutorial003.py!}152+ ```153+154 Check it:155 156 <div class="termy">157 19 unmodified lines177 Have in mind that you have to pass `bytes` to its `.write()` method, not `str`.178 179 If you have a `str`, you have to encode it first to get `bytes`.180 148-```Python hl_lines="4"149-{!../docs_src/parameter_types/file/tutorial004.py!}150-```181+=== "Python 3.6+"182 183+ ```Python hl_lines="5"184+ {!> ../docs_src/parameter_types/file/tutorial004_an.py!}185+ ```186+187+=== "Python 3.6+ non-Annotated"188+189+ !!! tip190+ Prefer to use the `Annotated` version if possible.191+192+ ```Python hl_lines="4"193+ {!> ../docs_src/parameter_types/file/tutorial004.py!}194+ ```195+196 <div class="termy">197 198 ```console199 $ python main.py --file binary.dat40 unmodified lines240 You can override the `mode` from the defaults above.241 242 For example, you could use `mode="a"` to write "appending" to the same file:243 200-```Python hl_lines="4"201-{!../docs_src/parameter_types/file/tutorial005.py!}202-```244+=== "Python 3.6+"245 246+ ```Python hl_lines="5"247+ {!> ../docs_src/parameter_types/file/tutorial005_an.py!}248+ ```249+250+=== "Python 3.6+ non-Annotated"251+252+ !!! tip253+ Prefer to use the `Annotated` version if possible.254+255+ ```Python hl_lines="4"256+ {!> ../docs_src/parameter_types/file/tutorial005.py!}257+ ```258+259 !!! tip260 As you are manually setting `mode="a"`, you can use `typer.FileText` or `typer.FileTextWrite`, both will work.261 262 Check it:41 unmodified linesmodified:docs/tutorial/parameter-types/number.md+42 added-9 removed
1 You can define numeric validations with `max` and `min` values for `int` and `float` *CLI parameters*:2 3-```Python hl_lines="5 6 7"4-{!../docs_src/parameter_types/number/tutorial001.py!}5-```3+=== "Python 3.6+"4 5+ ```Python hl_lines="6-8"6+ {!> ../docs_src/parameter_types/number/tutorial001_an.py!}7+ ```8+9+=== "Python 3.6+ non-Annotated"10+11+ !!! tip12+ Prefer to use the `Annotated` version if possible.13+14+ ```Python hl_lines="5-7"15+ {!> ../docs_src/parameter_types/number/tutorial001.py!}16+ ```17+18 *CLI arguments* and *CLI options* can both use these validations.19 20 You can specify `min`, `max` or both.21 63 unmodified lines85 You might want to, instead of showing an error, use the closest minimum or maximum valid values.86 87 You can do it with the `clamp` parameter:88 78-```Python hl_lines="5 6 7"79-{!../docs_src/parameter_types/number/tutorial002.py!}80-```89+=== "Python 3.6+"90 91+ ```Python hl_lines="6-8"92+ {!> ../docs_src/parameter_types/number/tutorial002_an.py!}93+ ```94+95+=== "Python 3.6+ non-Annotated"96+97+ !!! tip98+ Prefer to use the `Annotated` version if possible.99+100+ ```Python hl_lines="5-7"101+ {!> ../docs_src/parameter_types/number/tutorial002.py!}102+ ```103+104 And then, when you pass data that is out of the valid range, it will be "clamped", the closest valid value will be used:105 106 <div class="termy">107 19 unmodified lines127 ## Counter *CLI options*128 129 You can make a *CLI option* work as a counter with the `counter` parameter:130 109-```Python hl_lines="4"110-{!../docs_src/parameter_types/number/tutorial003.py!}111-```131+=== "Python 3.6+"132 133+ ```Python hl_lines="5"134+ {!> ../docs_src/parameter_types/number/tutorial003_an.py!}135+ ```136+137+=== "Python 3.6+ non-Annotated"138+139+ !!! tip140+ Prefer to use the `Annotated` version if possible.141+142+ ```Python hl_lines="4"143+ {!> ../docs_src/parameter_types/number/tutorial003.py!}144+ ```145+146 It means that the *CLI option* will be like a boolean flag, e.g. `--verbose`.147 148 And the value you receive in the function will be the amount of times that `--verbose` was added:149 35 unmodified linesmodified:docs/tutorial/parameter-types/path.md+28 added-6 removed
1 You can declare a *CLI parameter* to be a standard Python <a href="https://docs.python.org/3/library/pathlib.html#basic-use" class="external-link" target="_blank">`pathlib.Path`</a>.2 3 This is what you would do for directory paths, file paths, etc:4 5-```Python hl_lines="1 7"6-{!../docs_src/parameter_types/path/tutorial001.py!}7-```5+=== "Python 3.6+"6 7+ ```Python hl_lines="1 8"8+ {!> ../docs_src/parameter_types/path/tutorial001_an.py!}9+ ```10+11+=== "Python 3.6+ non-Annotated"12+13+ !!! tip14+ Prefer to use the `Annotated` version if possible.15+16+ ```Python hl_lines="1 7"17+ {!> ../docs_src/parameter_types/path/tutorial001.py!}18+ ```19+20 And again, as you receive a standard Python `Path` object the same as the type annotation, your editor will give you autocompletion for all its attributes and methods.21 22 Check it:23 45 unmodified lines69 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>.70 71 For example:72 62-```Python hl_lines="9 10 11 12 13 14"63-{!../docs_src/parameter_types/path/tutorial002.py!}64-```73+=== "Python 3.6+"74 75+ ```Python hl_lines="11-16"76+ {!> ../docs_src/parameter_types/path/tutorial002_an.py!}77+ ```78+79+=== "Python 3.6+ non-Annotated"80+81+ !!! tip82+ Prefer to use the `Annotated` version if possible.83+84+ ```Python hl_lines="9-14"85+ {!> ../docs_src/parameter_types/path/tutorial002.py!}86+ ```87+88 Check it:89 90 <div class="termy">91 36 unmodified linesmodified:docs/tutorial/options-autocompletion.md+126 added-27 removed
12 unmodified lines13 To check it quickly without creating a new Python package, install [Typer CLI](../typer-cli.md){.internal-link target=_blank}.14 15 Then let's create small example program:16 17-```Python18-{!../docs_src/options_autocompletion/tutorial001.py!}19-```17+=== "Python 3.6+"18 19+ ```Python20+ {!> ../docs_src/options_autocompletion/tutorial001_an.py!}21+ ```22+23+=== "Python 3.6+ non-Annotated"24+25+ !!! tip26+ Prefer to use the `Annotated` version if possible.27+28+ ```Python29+ {!> ../docs_src/options_autocompletion/tutorial001.py!}30+ ```31+32 And let's try it with **Typer CLI** to get completion:33 34 <div class="termy">35 24 unmodified lines60 Right now we get completion for the *CLI option* names, but not for the values.61 62 We 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}:63 53-```Python hl_lines="4-5 14"54-{!../docs_src/options_autocompletion/tutorial002.py!}55-```64+=== "Python 3.6+"65 66+ ```Python hl_lines="5-6 15"67+ {!> ../docs_src/options_autocompletion/tutorial002_an.py!}68+ ```69+70+=== "Python 3.6+ non-Annotated"71+72+ !!! tip73+ Prefer to use the `Annotated` version if possible.74+75+ ```Python hl_lines="4-5 14"76+ {!> ../docs_src/options_autocompletion/tutorial002.py!}77+ ```78+79 We return a `list` of strings from the `complete_name()` function.80 81 And then we get those values when using completion:82 19 unmodified lines102 Modify the `complete_name()` function to receive a parameter of type `str`, it will contain the incomplete value.103 104 Then we can check and return only the values that start with the incomplete value from the command line:105 84-```Python hl_lines="6-11"85-{!../docs_src/options_autocompletion/tutorial003.py!}86-```106+=== "Python 3.6+"107 108+ ```Python hl_lines="7-12"109+ {!> ../docs_src/options_autocompletion/tutorial003_an.py!}110+ ```111+112+=== "Python 3.6+ non-Annotated"113+114+ !!! tip115+ Prefer to use the `Annotated` version if possible.116+117+ ```Python hl_lines="6-11"118+ {!> ../docs_src/options_autocompletion/tutorial003.py!}119+ ```120+121 Now let's try it:122 123 <div class="termy">124 26 unmodified lines151 In 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.152 153 So, in the end, we return a `list` of `tuples` of `str`:154 122-```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+"156 157+ ```Python hl_lines="4-8 11-17"158+ {!> ../docs_src/options_autocompletion/tutorial004_an.py!}159+ ```160+161+=== "Python 3.6+ non-Annotated"162+163+ !!! tip164+ Prefer to use the `Annotated` version if possible.165+166+ ```Python hl_lines="3-7 10-16"167+ {!> ../docs_src/options_autocompletion/tutorial004.py!}168+ ```169+170 !!! tip171 If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.172 173 Click checks specifically for a `tuple` when extracting the help text.25 unmodified lines199 Instead of creating and returning a list with values (`str` or `tuple`), we can use `yield` with each value that we want in the completion.200 201 That 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:202 159-```Python hl_lines="10 11 12 13"160-{!../docs_src/options_autocompletion/tutorial005.py!}161-```203+=== "Python 3.6+"204 205+ ```Python hl_lines="11-14"206+ {!> ../docs_src/options_autocompletion/tutorial005_an.py!}207+ ```208+209+=== "Python 3.6+ non-Annotated"210+211+ !!! tip212+ Prefer to use the `Annotated` version if possible.213+214+ ```Python hl_lines="10-13"215+ {!> ../docs_src/options_autocompletion/tutorial005.py!}216+ ```217+218 That simplifies our code a bit and works the same.219 220 !!! 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 lines239 So, for now, take this as a sneak peek 😉.240 241 For this we use a `List` of `str`:242 188-```Python hl_lines="8-11"189-{!../docs_src/options_autocompletion/tutorial006.py!}190-```243+=== "Python 3.6+"244 245+ ```Python hl_lines="9-14"246+ {!> ../docs_src/options_autocompletion/tutorial006_an.py!}247+ ```248+249+=== "Python 3.6+ non-Annotated"250+251+ !!! tip252+ Prefer to use the `Annotated` version if possible.253+254+ ```Python hl_lines="8-11"255+ {!> ../docs_src/options_autocompletion/tutorial006.py!}256+ ```257+258 And then we can use it like:259 260 <div class="termy">261 15 unmodified lines277 But you can access the context by declaring a function parameter of type `typer.Context`.278 279 And from that context you can get the current values for each parameter.280 215-```Python hl_lines="12 13 15"216-{!../docs_src/options_autocompletion/tutorial007.py!}217-```281+=== "Python 3.6+"282 283+ ```Python hl_lines="13-14 16"284+ {!> ../docs_src/options_autocompletion/tutorial007_an.py!}285+ ```286+287+=== "Python 3.6+ non-Annotated"288+289+ !!! tip290+ Prefer to use the `Annotated` version if possible.291+292+ ```Python hl_lines="12-13 15"293+ {!> ../docs_src/options_autocompletion/tutorial007.py!}294+ ```295+296 We are getting the `names` already provided with `--name` in the command line before this completion was triggered.297 298 If 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 lines357 You can print to "standard error" with a **Rich** `Console(stderr=True)`.358 359 Using `stderr=True` tells **Rich** that the output should be shown in "standard error".360 284-```Python hl_lines="12 15-16"285-{!../docs_src/options_autocompletion/tutorial008.py!}286-```361+=== "Python 3.6+"362 363+ ```Python hl_lines="13 16-17"364+ {!> ../docs_src/options_autocompletion/tutorial008_an.py!}365+ ```366+367+=== "Python 3.6+ non-Annotated"368+369+ !!! tip370+ Prefer to use the `Annotated` version if possible.371+372+ ```Python hl_lines="12 15-16"373+ {!> ../docs_src/options_autocompletion/tutorial008.py!}374+ ```375+376 !!! 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.378 379 We 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 lines409 ## Getting the Context and the raw *CLI parameters*410 411 Of course, you can declare everything if you need it, the context, the raw *CLI parameters*, and the incomplete `str`:412 325-```Python hl_lines="15"326-{!../docs_src/options_autocompletion/tutorial009.py!}327-```413+=== "Python 3.6+"414 415+ ```Python hl_lines="16"416+ {!> ../docs_src/options_autocompletion/tutorial009_an.py!}417+ ```418+419+=== "Python 3.6+ non-Annotated"420+421+ !!! tip422+ Prefer to use the `Annotated` version if possible.423+424+ ```Python hl_lines="15"425+ {!> ../docs_src/options_autocompletion/tutorial009.py!}426+ ```427+428 Check it:429 430 <div class="termy">431 34 unmodified linesmodified:docs/tutorial/testing.md+14 added-3 removed
101 unmodified lines102 ## Testing input103 104 If you have a CLI with prompts, like:105 106-```Python hl_lines="7"107-{!../docs_src/testing/app02/main.py!}108-```106+=== "Python 3.6+"107 108+ ```Python hl_lines="8"109+ {!> ../docs_src/testing/app02_an/main.py!}110+ ```111+112+=== "Python 3.6+ non-Annotated"113+114+ !!! tip115+ Prefer to use the `Annotated` version if possible.116+117+ ```Python hl_lines="7"118+ {!> ../docs_src/testing/app02/main.py!}119+ ```120+121 That you would use like:122 123 <div class="termy">124 100 unmodified linesadded:docs_src/arguments/default/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: Annotated[str, typer.Argument()] = "Wade Wilson"):6+ print(f"Hello {name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/arguments/default/tutorial002_an.py+16 added
1+import random2+3+import typer4+from typing_extensions import Annotated5+6+7+def get_name():8+ return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])9+10+11+def main(name: Annotated[str, typer.Argument(default_factory=get_name)]):12+ print(f"Hello {name}")13+14+15+if __name__ == "__main__":16+ typer.run(main)modified:docs_src/arguments/default/tutorial002.py+1 added-1 removed
5 unmodified lines6 def get_name():7 return random.choice(["Deadpool", "Rick", "Morty", "Hiro"])8 9 10-def main(name: str = typer.Argument(get_name)):10+def main(name: str = typer.Argument(default_factory=get_name)):11 print(f"Hello {name}")12 13 14 if __name__ == "__main__":1 unmodified lineadded:docs_src/arguments/envvar/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: Annotated[str, typer.Argument(envvar="AWESOME_NAME")] = "World"):6+ print(f"Hello Mr. {name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/arguments/envvar/tutorial002_an.py+12 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(6+ name: Annotated[str, typer.Argument(envvar=["AWESOME_NAME", "GOD_NAME"])] = "World"7+):8+ print(f"Hello Mr. {name}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs_src/arguments/envvar/tutorial003_an.py+14 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(6+ name: Annotated[7+ str, typer.Argument(envvar="AWESOME_NAME", show_envvar=False)8+ ] = "World"9+):10+ print(f"Hello Mr. {name}")11+12+13+if __name__ == "__main__":14+ typer.run(main)added:docs_src/arguments/help/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: Annotated[str, typer.Argument(help="The name of the user to greet")]):6+ print(f"Hello {name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/arguments/help/tutorial002_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/arguments/help/tutorial003_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/arguments/help/tutorial004_an.py+17 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/arguments/help/tutorial005_an.py+17 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/arguments/help/tutorial006_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: Annotated[str, typer.Argument(metavar="✨username✨")] = "World"):6+ print(f"Hello {name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/arguments/help/tutorial007_an.py+22 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")19+20+21+if __name__ == "__main__":22+ typer.run(main)added:docs_src/arguments/help/tutorial008_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/arguments/optional/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: Annotated[str, typer.Argument()]):6+ print(f"Hello {name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)modified:docs_src/arguments/optional/tutorial001.py+1 added-1 removed
1 import typer2 3 4-def main(name: str = typer.Argument(...)):4+def main(name: str = typer.Argument()):5 print(f"Hello {name}")6 7 8 if __name__ == "__main__":1 unmodified lineadded:docs_src/arguments/optional/tutorial002_an.py+15 added
1+from typing import Optional2+3+import typer4+from typing_extensions import Annotated5+6+7+def main(name: Annotated[Optional[str], typer.Argument()] = None):8+ if name is None:9+ print("Hello World!")10+ else:11+ print(f"Hello {name}")12+13+14+if __name__ == "__main__":15+ typer.run(main)modified:docs_src/arguments/optional/tutorial002.py+1 added-1 removed
1 unmodified line2 3 import typer4 5 6-def main(name: Optional[str] = typer.Argument(None)):6+def 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 linesadded:docs_src/arguments/optional/tutorial003.py+9 added
1+import typer2+3+4+def main(name: str = typer.Argument(default=...)):5+ print(f"Hello {name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs_src/commands/help/tutorial001_an.py+67 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer(help="Awesome CLI user manager.")5+6+7+@app.command()8+def create(username: str):9+ """10+ Create a new user with USERNAME.11+ """12+ print(f"Creating user: {username}")13+14+15+@app.command()16+def 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.28+29+ 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")35+36+37+@app.command()38+def 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.49+50+ If --force is not used, will ask for confirmation.51+ """52+ if force:53+ print("Deleting all users")54+ else:55+ print("Operation cancelled")56+57+58+@app.command()59+def init():60+ """61+ Initialize the users database.62+ """63+ print("Initializing user database")64+65+66+if __name__ == "__main__":67+ app()added:docs_src/commands/help/tutorial004_an.py+37 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer(rich_markup_mode="rich")5+6+7+@app.command()8+def 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:15+16+ This requires a [underline]username[/underline].17+ """18+ print(f"Creating user: {username}")19+20+21+@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")22+def 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}")34+35+36+if __name__ == "__main__":37+ app()added:docs_src/commands/help/tutorial005_an.py+37 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer(rich_markup_mode="markdown")5+6+7+@app.command()8+def create(9+ username: Annotated[str, typer.Argument(help="The username to be **created**")]10+):11+ """12+ **Create** a new *shinny* user. :sparkles:13+14+ * Create a username15+16+ * Show that the username is created17+18+ ---19+20+ Learn more at the [Typer docs website](https://typer.tiangolo.com)21+ """22+ print(f"Creating user: {username}")23+24+25+@app.command(help="**Delete** a user with *USERNAME*.")26+def 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}")34+35+36+if __name__ == "__main__":37+ app()added:docs_src/commands/help/tutorial007_an.py+46 added
1+from typing import Union2+3+import typer4+from typing_extensions import Annotated5+6+app = typer.Typer(rich_markup_mode="rich")7+8+9+@app.command()10+def 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}")35+36+37+@app.command(rich_help_panel="Utils and Configs")38+def config(configuration: str):39+ """40+ [blue]Configure[/blue] the system. :wrench:41+ """42+ print(f"Configuring the system with: {configuration}")43+44+45+if __name__ == "__main__":46+ app()added:docs_src/commands/options/tutorial001_an.py+43 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer()5+6+7+@app.command()8+def create(username: str):9+ print(f"Creating user: {username}")10+11+12+@app.command()13+def 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")23+24+25+@app.command()26+def 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")35+36+37+@app.command()38+def init():39+ print("Initializing user database")40+41+42+if __name__ == "__main__":43+ app()added:docs_src/multiple_values/arguments_with_multiple_values/tutorial002_an.py+17 added
1+from typing import Tuple2+3+import typer4+from typing_extensions import Annotated5+6+7+def 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}")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/multiple_values/multiple_options/tutorial001_an.py+16 added
1+from typing import List, Optional2+3+import typer4+from typing_extensions import Annotated5+6+7+def 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}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs_src/multiple_values/multiple_options/tutorial002_an.py+12 added
1+from typing import List2+3+import typer4+from typing_extensions import Annotated5+6+7+def main(number: Annotated[List[float], typer.Option()] = []):8+ print(f"The sum is {sum(number)}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs_src/multiple_values/options_with_multiple_values/tutorial001_an.py+18 added
1+from typing import Tuple2+3+import typer4+from typing_extensions import Annotated5+6+7+def 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!")15+16+17+if __name__ == "__main__":18+ typer.run(main)added:docs_src/options/callback/tutorial001_an.py+16 added
1+import typer2+from typing_extensions import Annotated3+4+5+def name_callback(value: str):6+ if value != "Camila":7+ raise typer.BadParameter("Only Camila is allowed")8+ return value9+10+11+def main(name: Annotated[str, typer.Option(callback=name_callback)]):12+ print(f"Hello {name}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs_src/options/callback/tutorial002_an.py+17 added
1+import typer2+from typing_extensions import Annotated3+4+5+def name_callback(value: str):6+ print("Validating name")7+ if value != "Camila":8+ raise typer.BadParameter("Only Camila is allowed")9+ return value10+11+12+def main(name: Annotated[str, typer.Option(callback=name_callback)]):13+ print(f"Hello {name}")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/options/callback/tutorial003_an.py+19 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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 value12+13+14+def main(name: Annotated[str, typer.Option(callback=name_callback)]):15+ print(f"Hello {name}")16+17+18+if __name__ == "__main__":19+ typer.run(main)added:docs_src/options/callback/tutorial004_an.py+19 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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 value12+13+14+def main(name: Annotated[str, typer.Option(callback=name_callback)]):15+ print(f"Hello {name}")16+17+18+if __name__ == "__main__":19+ typer.run(main)added:docs_src/options/help/tutorial001_an.py+22 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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.12+13+ 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}")19+20+21+if __name__ == "__main__":22+ typer.run(main)added:docs_src/options/help/tutorial002_an.py+33 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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.23+24+ 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}")30+31+32+if __name__ == "__main__":33+ typer.run(main)added:docs_src/options/help/tutorial003_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(fullname: Annotated[str, typer.Option(show_default=False)] = "Wade Wilson"):6+ print(f"Hello {fullname}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/options/name/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(user_name: Annotated[str, typer.Option("--name")]):6+ print(f"Hello {user_name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/options/name/tutorial002_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(user_name: Annotated[str, typer.Option("--name", "-n")]):6+ print(f"Hello {user_name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/options/name/tutorial003_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(user_name: Annotated[str, typer.Option("-n")]):6+ print(f"Hello {user_name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/options/name/tutorial004_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(user_name: Annotated[str, typer.Option("--user-name", "-n")]):6+ print(f"Hello {user_name}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/options/name/tutorial005_an.py+16 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs_src/options/password/tutorial001_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/options/password/tutorial002_an.py+16 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs_src/options/prompt/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: str, lastname: Annotated[str, typer.Option(prompt=True)]):6+ print(f"Hello {name} {lastname}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/options/prompt/tutorial002_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(6+ name: str,7+ lastname: Annotated[str, typer.Option(prompt="Please tell me your last name")],8+):9+ print(f"Hello {name} {lastname}")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/options/prompt/tutorial003_an.py+12 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(6+ project_name: Annotated[str, typer.Option(prompt=True, confirmation_prompt=True)]7+):8+ print(f"Deleting project {project_name}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs_src/options/required/tutorial001_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(name: str, lastname: Annotated[str, typer.Option()]):6+ print(f"Hello {name} {lastname}")7+8+9+if __name__ == "__main__":10+ typer.run(main)modified:docs_src/options/required/tutorial001.py+1 added-1 removed
1 import typer2 3 4-def main(name: str, lastname: str = typer.Option(...)):4+def main(name: str, lastname: str = typer.Option()):5 print(f"Hello {name} {lastname}")6 7 8 if __name__ == "__main__":1 unmodified lineadded:docs_src/options/required/tutorial002.py+9 added
1+import typer2+3+4+def main(name: str, lastname: str = typer.Option(default=...)):5+ print(f"Hello {name} {lastname}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs_src/options/version/tutorial001_an.py+25 added
1+from typing import Optional2+3+import typer4+from typing_extensions import Annotated5+6+__version__ = "0.1.0"7+8+9+def version_callback(value: bool):10+ if value:11+ print(f"Awesome CLI Version: {__version__}")12+ raise typer.Exit()13+14+15+def 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}")22+23+24+if __name__ == "__main__":25+ typer.run(main)added:docs_src/options/version/tutorial002_an.py+30 added
1+from typing import Optional2+3+import typer4+from typing_extensions import Annotated5+6+__version__ = "0.1.0"7+8+9+def version_callback(value: bool):10+ if value:11+ print(f"Awesome CLI Version: {__version__}")12+ raise typer.Exit()13+14+15+def name_callback(name: str):16+ if name != "Camila":17+ raise typer.BadParameter("Only Camila is allowed")18+19+20+def 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}")27+28+29+if __name__ == "__main__":30+ typer.run(main)added:docs_src/options/version/tutorial003_an.py+32 added
1+from typing import Optional2+3+import typer4+from typing_extensions import Annotated5+6+__version__ = "0.1.0"7+8+9+def version_callback(value: bool):10+ if value:11+ print(f"Awesome CLI Version: {__version__}")12+ raise typer.Exit()13+14+15+def name_callback(name: str):16+ if name != "Camila":17+ raise typer.BadParameter("Only Camila is allowed")18+ return name19+20+21+def 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}")29+30+31+if __name__ == "__main__":32+ typer.run(main)added:docs_src/options_autocompletion/tutorial001_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer()5+6+7+@app.command()8+def main(name: Annotated[str, typer.Option(help="The name to say hi to.")] = "World"):9+ print(f"Hello {name}")10+11+12+if __name__ == "__main__":13+ app()added:docs_src/options_autocompletion/tutorial002_an.py+22 added
1+import typer2+from typing_extensions import Annotated3+4+5+def complete_name():6+ return ["Camila", "Carlos", "Sebastian"]7+8+9+app = typer.Typer()10+11+12+@app.command()13+def 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}")19+20+21+if __name__ == "__main__":22+ app()added:docs_src/options_autocompletion/tutorial003_an.py+28 added
1+import typer2+from typing_extensions import Annotated3+4+valid_names = ["Camila", "Carlos", "Sebastian"]5+6+7+def complete_name(incomplete: str):8+ completion = []9+ for name in valid_names:10+ if name.startswith(incomplete):11+ completion.append(name)12+ return completion13+14+15+app = typer.Typer()16+17+18+@app.command()19+def 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}")25+26+27+if __name__ == "__main__":28+ app()added:docs_src/options_autocompletion/tutorial004_an.py+33 added
1+import typer2+from typing_extensions import Annotated3+4+valid_completion_items = [5+ ("Camila", "The reader of books."),6+ ("Carlos", "The writer of scripts."),7+ ("Sebastian", "The type hints guy."),8+]9+10+11+def 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 completion18+19+20+app = typer.Typer()21+22+23+@app.command()24+def 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}")30+31+32+if __name__ == "__main__":33+ app()added:docs_src/options_autocompletion/tutorial005_an.py+30 added
1+import typer2+from typing_extensions import Annotated3+4+valid_completion_items = [5+ ("Camila", "The reader of books."),6+ ("Carlos", "The writer of scripts."),7+ ("Sebastian", "The type hints guy."),8+]9+10+11+def complete_name(incomplete: str):12+ for name, help_text in valid_completion_items:13+ if name.startswith(incomplete):14+ yield (name, help_text)15+16+17+app = typer.Typer()18+19+20+@app.command()21+def 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}")27+28+29+if __name__ == "__main__":30+ app()added:docs_src/options_autocompletion/tutorial006_an.py+18 added
1+from typing import List2+3+import typer4+from typing_extensions import Annotated5+6+app = typer.Typer()7+8+9+@app.command()10+def 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}")15+16+17+if __name__ == "__main__":18+ app()added:docs_src/options_autocompletion/tutorial007_an.py+35 added
1+from typing import List2+3+import typer4+from typing_extensions import Annotated5+6+valid_completion_items = [7+ ("Camila", "The reader of books."),8+ ("Carlos", "The writer of scripts."),9+ ("Sebastian", "The type hints guy."),10+]11+12+13+def 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)18+19+20+app = typer.Typer()21+22+23+@app.command()24+def 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}")32+33+34+if __name__ == "__main__":35+ app()added:docs_src/options_autocompletion/tutorial008_an.py+38 added
1+from typing import List2+3+import typer4+from rich.console import Console5+from typing_extensions import Annotated6+7+valid_completion_items = [8+ ("Camila", "The reader of books."),9+ ("Carlos", "The writer of scripts."),10+ ("Sebastian", "The type hints guy."),11+]12+13+err_console = Console(stderr=True)14+15+16+def 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)21+22+23+app = typer.Typer()24+25+26+@app.command()27+def 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}")35+36+37+if __name__ == "__main__":38+ app()added:docs_src/options_autocompletion/tutorial009_an.py+39 added
1+from typing import List2+3+import typer4+from rich.console import Console5+from typing_extensions import Annotated6+7+valid_completion_items = [8+ ("Camila", "The reader of books."),9+ ("Carlos", "The writer of scripts."),10+ ("Sebastian", "The type hints guy."),11+]12+13+err_console = Console(stderr=True)14+15+16+def 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)22+23+24+app = typer.Typer()25+26+27+@app.command()28+def 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}")36+37+38+if __name__ == "__main__":39+ app()added:docs_src/parameter_types/bool/tutorial001_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(force: Annotated[bool, typer.Option("--force")] = False):6+ if force:7+ print("Forcing operation")8+ else:9+ print("Not forcing")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/parameter_types/bool/tutorial002_an.py+17 added
1+from typing import Optional2+3+import typer4+from typing_extensions import Annotated5+6+7+def 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!")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/parameter_types/bool/tutorial003_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/parameter_types/bool/tutorial004_an.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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")10+11+12+if __name__ == "__main__":13+ typer.run(main)added:docs_src/parameter_types/datetime/tutorial002_an.py+19 added
1+from datetime import datetime2+3+import typer4+from typing_extensions import Annotated5+6+7+def 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}")16+17+18+if __name__ == "__main__":19+ typer.run(main)added:docs_src/parameter_types/enum/tutorial002_an.py+22 added
1+from enum import Enum2+3+import typer4+from typing_extensions import Annotated5+6+7+class NeuralNetwork(str, Enum):8+ simple = "simple"9+ conv = "conv"10+ lstm = "lstm"11+12+13+def main(14+ network: Annotated[15+ NeuralNetwork, typer.Option(case_sensitive=False)16+ ] = NeuralNetwork.simple17+):18+ print(f"Training neural network of type: {network.value}")19+20+21+if __name__ == "__main__":22+ typer.run(main)added:docs_src/parameter_types/file/tutorial001_an.py+11 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(config: Annotated[typer.FileText, typer.Option()]):6+ for line in config:7+ print(f"Config line: {line}")8+9+10+if __name__ == "__main__":11+ typer.run(main)added:docs_src/parameter_types/file/tutorial002_an.py+11 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(config: Annotated[typer.FileTextWrite, typer.Option()]):6+ config.write("Some config written by the app")7+ print("Config written")8+9+10+if __name__ == "__main__":11+ typer.run(main)added:docs_src/parameter_types/file/tutorial003_an.py+14 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")11+12+13+if __name__ == "__main__":14+ typer.run(main)added:docs_src/parameter_types/file/tutorial004_an.py+18 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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")15+16+17+if __name__ == "__main__":18+ typer.run(main)added:docs_src/parameter_types/file/tutorial005_an.py+11 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(config: Annotated[typer.FileText, typer.Option(mode="a")]):6+ config.write("This is a single line\n")7+ print("Config line written")8+9+10+if __name__ == "__main__":11+ typer.run(main)added:docs_src/parameter_types/number/tutorial001_an.py+16 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs_src/parameter_types/number/tutorial002_an.py+16 added
1+import typer2+from typing_extensions import Annotated3+4+5+def 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}")13+14+15+if __name__ == "__main__":16+ typer.run(main)added:docs_src/parameter_types/number/tutorial003_an.py+10 added
1+import typer2+from typing_extensions import Annotated3+4+5+def main(verbose: Annotated[int, typer.Option("--verbose", "-v", count=True)] = 0):6+ print(f"Verbose level is {verbose}")7+8+9+if __name__ == "__main__":10+ typer.run(main)added:docs_src/parameter_types/path/tutorial001_an.py+22 added
1+from pathlib import Path2+from typing import Optional3+4+import typer5+from typing_extensions import Annotated6+7+8+def 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")19+20+21+if __name__ == "__main__":22+ typer.run(main)added:docs_src/parameter_types/path/tutorial002_an.py+25 added
1+from pathlib import Path2+3+import typer4+from typing_extensions import Annotated5+6+7+def 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}")22+23+24+if __name__ == "__main__":25+ typer.run(main)added:docs_src/testing/app02_an/__init__.py
added:docs_src/testing/app02_an/main.py+13 added
1+import typer2+from typing_extensions import Annotated3+4+app = typer.Typer()5+6+7+@app.command()8+def main(name: str, email: Annotated[str, typer.Option(prompt=True)]):9+ print(f"Hello {name}, your email is: {email}")10+11+12+if __name__ == "__main__":13+ app()added:docs_src/testing/app02_an/test_main.py+11 added
1+from typer.testing import CliRunner2+3+from .main import app4+5+runner = CliRunner()6+7+8+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_default/test_tutorial001_an.py+42 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.default import tutorial001_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output21+22+23+def test_call_no_arg():24+ result = runner.invoke(app)25+ assert result.exit_code == 0, result.output26+ assert "Hello Wade Wilson" in result.output27+28+29+def test_call_arg():30+ result = runner.invoke(app, ["Camila"])31+ assert result.exit_code == 032+ assert "Hello Camila" in result.output33+34+35+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_default/test_tutorial002_an.py+44 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.default import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output21+22+23+def 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)29+30+31+def test_call_arg():32+ result = runner.invoke(app, ["Camila"])33+ assert result.exit_code == 034+ assert "Hello Camila" in result.output35+36+37+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_envvar/test_tutorial001_an.py+62 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.arguments.envvar import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output23+24+25+def 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 = rich35+36+37+def test_call_arg():38+ result = runner.invoke(app, ["Wednesday"])39+ assert result.exit_code == 040+ assert "Hello Mr. Wednesday" in result.output41+42+43+def 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.output47+48+49+def 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.output53+54+55+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_envvar/test_tutorial002_an.py+49 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.envvar import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call_arg():25+ result = runner.invoke(app, ["Wednesday"])26+ assert result.exit_code == 027+ assert "Hello Mr. Wednesday" in result.output28+29+30+def 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.output34+35+36+def 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.output40+41+42+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_envvar/test_tutorial003_an.py+49 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.envvar import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call_arg():25+ result = runner.invoke(app, ["Wednesday"])26+ assert result.exit_code == 027+ assert "Hello Mr. Wednesday" in result.output28+29+30+def 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.output34+35+36+def 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.output40+41+42+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial001_an.py+52 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.arguments.help import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output24+25+26+def 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 = rich37+38+39+def test_call_arg():40+ result = runner.invoke(app, ["Camila"])41+ assert result.exit_code == 042+ assert "Hello Camila" in result.output43+44+45+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial002_an.py+39 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.help import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output24+25+26+def test_call_arg():27+ result = runner.invoke(app, ["Camila"])28+ assert result.exit_code == 029+ assert "Hello Camila" in result.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial003_an.py+39 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.help import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output24+25+26+def test_call_arg():27+ result = runner.invoke(app, ["Camila"])28+ assert result.exit_code == 029+ assert "Hello Camila" in result.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial004_an.py+39 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.help import tutorial004_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output24+25+26+def test_call_arg():27+ result = runner.invoke(app, ["Camila"])28+ assert result.exit_code == 029+ assert "Hello Camila" in result.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial005_an.py+37 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.help import tutorial005_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call_arg():25+ result = runner.invoke(app, ["Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial006_an.py+37 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.help import tutorial006_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call_arg():25+ result = runner.invoke(app, ["Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial007_an.py+37 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.arguments.help import tutorial007_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output22+23+24+def test_call_arg():25+ result = runner.invoke(app, ["Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_help/test_tutorial008_an.py+50 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.arguments.help import tutorial008_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output23+24+25+def 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 = rich35+36+37+def test_call_arg():38+ result = runner.invoke(app, ["Camila"])39+ assert result.exit_code == 040+ assert "Hello Camila" in result.output41+42+43+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_optional/test_tutorial001_an.py+51 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.arguments.optional import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def test_call_no_arg():17+ result = runner.invoke(app)18+ assert result.exit_code != 019+ assert "Missing argument 'NAME'." in result.output20+21+22+def test_call_no_arg_standalone():23+ # Mainly for coverage24+ result = runner.invoke(app, standalone_mode=False)25+ assert result.exit_code != 026+27+28+def 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 = rich36+37+38+def test_call_arg():39+ result = runner.invoke(app, ["Camila"])40+ assert result.exit_code == 041+ assert "Hello Camila" in result.output42+43+44+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_optional/test_tutorial002_an.py+40 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.arguments.optional import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+ assert "[OPTIONS] [NAME]" in result.output19+20+21+def test_call_no_arg():22+ result = runner.invoke(app)23+ assert result.exit_code == 024+ assert "Hello World!" in result.output25+26+27+def test_call_arg():28+ result = runner.invoke(app, ["Camila"])29+ assert result.exit_code == 030+ assert "Hello Camila" in result.output31+32+33+def 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.stdoutadded:tests/test_tutorial/test_arguments/test_optional/test_tutorial003.py+51 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.arguments.optional import tutorial003 as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def test_call_no_arg():17+ result = runner.invoke(app)18+ assert result.exit_code != 019+ assert "Missing argument 'NAME'." in result.output20+21+22+def test_call_no_arg_standalone():23+ # Mainly for coverage24+ result = runner.invoke(app, standalone_mode=False)25+ assert result.exit_code != 026+27+28+def 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 = rich36+37+38+def test_call_arg():39+ result = runner.invoke(app, ["Camila"])40+ assert result.exit_code == 041+ assert "Hello Camila" in result.output42+43+44+def 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.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial001_an.py+126 added
1+import subprocess2+import sys3+4+from typer.testing import CliRunner5+6+from docs_src.commands.help import tutorial001_an as mod7+8+app = mod.app9+10+runner = CliRunner()11+12+13+def 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.output25+26+27+def 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.output32+33+34+def 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.output42+43+44+def 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.output54+55+56+def 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.output61+62+63+def test_create():64+ result = runner.invoke(app, ["create", "Camila"])65+ assert result.exit_code == 066+ assert "Creating user: Camila" in result.output67+68+69+def 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.output78+79+80+def 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.output89+90+91+def 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.output100+101+102+def 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.output111+112+113+def test_init():114+ result = runner.invoke(app, ["init"])115+ assert result.exit_code == 0116+ assert "Initializing user database" in result.output117+118+119+def 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.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial004_an.py+60 added
1+import subprocess2+import sys3+4+from typer.testing import CliRunner5+6+from docs_src.commands.help import tutorial004_an as mod7+8+app = mod.app9+10+runner = CliRunner()11+12+13+def 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.output22+23+24+def 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.output30+31+32+def 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.output39+40+41+def test_create():42+ result = runner.invoke(app, ["create", "Camila"])43+ assert result.exit_code == 044+ assert "Creating user: Camila" in result.output45+46+47+def test_delete():48+ result = runner.invoke(app, ["delete", "Camila"])49+ assert result.exit_code == 050+ assert "Deleting user: Camila" in result.output51+52+53+def 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.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial005_an.py+61 added
1+import subprocess2+import sys3+4+from typer.testing import CliRunner5+6+from docs_src.commands.help import tutorial005_an as mod7+8+app = mod.app9+10+runner = CliRunner()11+12+13+def 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.output22+23+24+def 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.output31+32+33+def 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.output40+41+42+def test_create():43+ result = runner.invoke(app, ["create", "Camila"])44+ assert result.exit_code == 045+ assert "Creating user: Camila" in result.output46+47+48+def test_delete():49+ result = runner.invoke(app, ["delete", "Camila"])50+ assert result.exit_code == 051+ assert "Deleting user: Camila" in result.output52+53+54+def 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.stdoutadded:tests/test_tutorial/test_commands/test_help/test_tutorial007_an.py+56 added
1+import subprocess2+import sys3+4+from typer.testing import CliRunner5+6+from docs_src.commands.help import tutorial007_an as mod7+8+app = mod.app9+10+runner = CliRunner()11+12+13+def 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.output21+22+23+def 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.output39+40+41+def 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 == 047+48+49+def 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.stdoutadded:tests/test_tutorial/test_commands/test_options/test_tutorial001_an.py+97 added
1+import subprocess2+import sys3+4+from typer.testing import CliRunner5+6+from docs_src.commands.options import tutorial001_an as mod7+8+app = mod.app9+10+runner = CliRunner()11+12+13+def 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.output21+22+23+def test_create():24+ result = runner.invoke(app, ["create", "Camila"])25+ assert result.exit_code == 026+ assert "Creating user: Camila" in result.output27+28+29+def 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.output38+39+40+def 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.output49+50+51+def 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.output60+61+62+def 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.output71+72+73+def 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.output82+83+84+def test_init():85+ result = runner.invoke(app, ["init"])86+ assert result.exit_code == 087+ assert "Initializing user database" in result.output88+89+90+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/test_arguments_with_multiple_values/test_tutorial002_an.py+58 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.multiple_values.arguments_with_multiple_values import (8+ tutorial002_an as mod,9+)10+11+runner = CliRunner()12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output22+23+24+def 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.output30+31+32+def test_invalid_args():33+ result = runner.invoke(app, ["Draco", "Hagrid"])34+ assert result.exit_code != 035+ # TODO: when deprecating Click 7, remove second option36+37+ assert (38+ "Argument 'names' takes 3 values" in result.stdout39+ or "argument names takes 3 values" in result.stdout40+ )41+42+43+def 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.stdout49+50+51+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial001_an.py+44 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.multiple_values.multiple_options import tutorial001_an as mod8+9+runner = CliRunner()10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_main():15+ result = runner.invoke(app)16+ assert result.exit_code != 017+ assert "No provided users" in result.output18+ assert "Aborted" in result.output19+20+21+def test_1_user():22+ result = runner.invoke(app, ["--user", "Camila"])23+ assert result.exit_code == 024+ assert "Processing user: Camila" in result.output25+26+27+def 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.output35+36+37+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/test_multiple_options/test_tutorial002_an.py+39 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.multiple_values.multiple_options import tutorial002_an as mod8+9+runner = CliRunner()10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_main():15+ result = runner.invoke(app)16+ assert result.exit_code == 017+ assert "The sum is 0" in result.output18+19+20+def test_1_number():21+ result = runner.invoke(app, ["--number", "2"])22+ assert result.exit_code == 023+ assert "The sum is 2.0" in result.output24+25+26+def 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.output30+31+32+def 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.stdoutadded:tests/test_tutorial/test_multiple_values/test_options_with_multiple_values/test_tutorial001_an.py+53 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.multiple_values.options_with_multiple_values import tutorial001_an as mod8+9+runner = CliRunner()10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_main():15+ result = runner.invoke(app)16+ assert result.exit_code != 017+ assert "No user provided" in result.output18+ assert "Aborted" in result.output19+20+21+def 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.output26+27+28+def 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.output33+34+35+def test_invalid_user():36+ result = runner.invoke(app, ["--user", "Camila", "50"])37+ assert result.exit_code != 038+ # TODO: when deprecating Click 7, remove second option39+40+ assert (41+ "Option '--user' requires 3 arguments" in result.output42+ or "--user option requires 3 arguments" in result.output43+ )44+45+46+def 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.stdoutadded:tests/test_tutorial/test_options/test_callback/test_tutorial001_an.py+34 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.callback import tutorial001_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_1():16+ result = runner.invoke(app, ["--name", "Camila"])17+ assert result.exit_code == 018+ assert "Hello Camila" in result.output19+20+21+def 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.output25+26+27+def 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.stdoutadded:tests/test_tutorial/test_options/test_callback/test_tutorial003_an.py+53 added
1+import os2+import subprocess3+import sys4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.options.callback import tutorial003_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output21+22+23+def 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.output27+28+29+def 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.stdout37+38+39+def 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.stdoutadded:tests/test_tutorial/test_options/test_callback/test_tutorial004_an.py+53 added
1+import os2+import subprocess3+import sys4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.options.callback import tutorial004_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output21+22+23+def 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.output27+28+29+def 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.stdout37+38+39+def 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.stdoutadded:tests/test_tutorial/test_options/test_help/test_tutorial001_an.py+49 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.help import tutorial001_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_1():25+ result = runner.invoke(app, ["Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def 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.output34+35+36+def 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.output40+41+42+def 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.stdoutadded:tests/test_tutorial/test_options/test_help/test_tutorial002_an.py+45 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.help import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_call():16+ result = runner.invoke(app, ["World"])17+ assert result.exit_code == 018+ assert "Hello World" in result.output19+20+21+def test_formal():22+ result = runner.invoke(app, ["World", "--formal"])23+ assert result.exit_code == 024+ assert "Good day Ms. World" in result.output25+26+27+def 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.output36+37+38+def 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.stdoutadded:tests/test_tutorial/test_options/test_help/test_tutorial003_an.py+36 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.help import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_call():16+ result = runner.invoke(app)17+ assert result.exit_code == 018+ assert "Hello Wade Wilson" in result.output19+20+21+def 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.output27+28+29+def 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.stdoutadded:tests/test_tutorial/test_options/test_name/test_tutorial001_an.py+46 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.name import tutorial001_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output21+22+23+def test_call():24+ result = runner.invoke(app, ["--name", "Camila"])25+ assert result.exit_code == 026+ assert "Hello Camila" in result.output27+28+29+def 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+ )37+38+39+def 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.stdoutmodified:tests/test_tutorial/test_options/test_name/test_tutorial001.py+10 added
24 unmodified lines25 assert result.exit_code == 026 assert "Hello Camila" in result.output27 28 29+def 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+ )37+38+39 def test_script():40 result = subprocess.run(41 [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],42 stdout=subprocess.PIPE,4 unmodified linesadded:tests/test_tutorial/test_options/test_name/test_tutorial002_an.py+43 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.name import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call():25+ result = runner.invoke(app, ["-n", "Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def test_call_long():31+ result = runner.invoke(app, ["--name", "Camila"])32+ assert result.exit_code == 033+ assert "Hello Camila" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options/test_name/test_tutorial003_an.py+37 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.name import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call():25+ result = runner.invoke(app, ["-n", "Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def 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.stdoutadded:tests/test_tutorial/test_options/test_name/test_tutorial004_an.py+43 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.name import tutorial004_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_call():25+ result = runner.invoke(app, ["-n", "Camila"])26+ assert result.exit_code == 027+ assert "Hello Camila" in result.output28+29+30+def test_call_long():31+ result = runner.invoke(app, ["--user-name", "Camila"])32+ assert result.exit_code == 033+ assert "Hello Camila" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options/test_name/test_tutorial005_an.py+55 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.name import tutorial005_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output23+24+25+def test_call():26+ result = runner.invoke(app, ["-n", "Camila"])27+ assert result.exit_code == 028+ assert "Hello Camila" in result.output29+30+31+def test_call_formal():32+ result = runner.invoke(app, ["-n", "Camila", "-f"])33+ assert result.exit_code == 034+ assert "Good day Ms. Camila." in result.output35+36+37+def test_call_formal_condensed():38+ result = runner.invoke(app, ["-fn", "Camila"])39+ assert result.exit_code == 040+ assert "Good day Ms. Camila." in result.output41+42+43+def test_call_condensed_wrong_order():44+ result = runner.invoke(app, ["-nf", "Camila"])45+ assert result.exit_code != 046+47+48+def 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.stdoutadded:tests/test_tutorial/test_options/test_prompt/test_tutorial001_an.py+43 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.prompt import tutorial001_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output19+20+21+def 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.output26+27+28+def 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.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options/test_prompt/test_tutorial002_an.py+43 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.prompt import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output19+20+21+def 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.output26+27+28+def 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.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options/test_prompt/test_tutorial003_an.py+57 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.options.prompt import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output19+20+21+def 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 option27+28+ 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.output33+34+35+def 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.output40+41+42+def 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.output48+49+50+def 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.stdoutadded:tests/test_tutorial/test_options/test_required/test_tutorial001_an.py+54 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.options.required import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def test_1():17+ result = runner.invoke(app, ["Camila"])18+ assert result.exit_code != 019+ assert "Missing option '--lastname'." in result.output20+21+22+def 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.output26+27+28+def 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.output34+35+36+def 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 = rich45+46+47+def 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.stdoutadded:tests/test_tutorial/test_options/test_required/test_tutorial001.py+54 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.options.required import tutorial001 as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def test_1():17+ result = runner.invoke(app, ["Camila"])18+ assert result.exit_code != 019+ assert "Missing option '--lastname'." in result.output20+21+22+def 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.output26+27+28+def 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.output34+35+36+def 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 = rich45+46+47+def 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.stdoutdeleted:tests/test_tutorial/test_options/test_required/test_tutorial002.py-54 removed
1-import subprocess2-import sys3-4-import typer5-import typer.core6-from typer.testing import CliRunner7-8-from docs_src.options.required import tutorial001 as mod9-10-runner = CliRunner()11-12-app = typer.Typer()13-app.command()(mod.main)14-15-16-def test_1():17- result = runner.invoke(app, ["Camila"])18- assert result.exit_code != 019- assert "Missing option '--lastname'." in result.output20-21-22-def 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.output26-27-28-def 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.output34-35-36-def 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 = rich45-46-47-def 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.stdoutadded:tests/test_tutorial/test_options/test_version/test_tutorial003_an.py+58 added
1+import os2+import subprocess3+import sys4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.options.version import tutorial003_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output20+21+22+def 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.output26+27+28+def test_3():29+ result = runner.invoke(app, ["--name", "Camila"])30+ assert result.exit_code == 031+ assert "Hello Camila" in result.output32+33+34+def 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.stdout42+43+44+def 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.stdoutadded:tests/test_tutorial/test_options_autocompletion/test_tutorial002_an.py+43 added
1+import os2+import subprocess3+import sys4+5+from typer.testing import CliRunner6+7+from docs_src.options_autocompletion import tutorial002_an as mod8+9+runner = CliRunner()10+11+12+def 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.stdout28+29+30+def test_1():31+ result = runner.invoke(mod.app, ["--name", "Camila"])32+ assert result.exit_code == 033+ assert "Hello Camila" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options_autocompletion/test_tutorial003_an.py+43 added
1+import os2+import subprocess3+import sys4+5+from typer.testing import CliRunner6+7+from docs_src.options_autocompletion import tutorial003_an as mod8+9+runner = CliRunner()10+11+12+def 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.stdout28+29+30+def test_1():31+ result = runner.invoke(mod.app, ["--name", "Camila"])32+ assert result.exit_code == 033+ assert "Hello Camila" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options_autocompletion/test_tutorial004_an.py+43 added
1+import os2+import subprocess3+import sys4+5+from typer.testing import CliRunner6+7+from docs_src.options_autocompletion import tutorial004_an as mod8+9+runner = CliRunner()10+11+12+def 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.stdout28+29+30+def test_1():31+ result = runner.invoke(mod.app, ["--name", "Camila"])32+ assert result.exit_code == 033+ assert "Hello Camila" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_options_autocompletion/test_tutorial007_an.py+44 added
1+import os2+import subprocess3+import sys4+5+from typer.testing import CliRunner6+7+from docs_src.options_autocompletion import tutorial007_an as mod8+9+runner = CliRunner()10+11+12+def 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.stdout28+29+30+def 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.output35+36+37+def 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.stdoutadded:tests/test_tutorial/test_options_autocompletion/test_tutorial008_an.py+46 added
1+import os2+import subprocess3+import sys4+5+from typer.testing import CliRunner6+7+from docs_src.options_autocompletion import tutorial008_an as mod8+9+runner = CliRunner()10+11+12+def 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.stderr30+31+32+def 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.output37+38+39+def 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.stdoutadded:tests/test_tutorial/test_options_autocompletion/test_tutorial009_an.py+46 added
1+import os2+import subprocess3+import sys4+5+from typer.testing import CliRunner6+7+from docs_src.options_autocompletion import tutorial009_an as mod8+9+runner = CliRunner()10+11+12+def 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.stderr30+31+32+def 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.output37+38+39+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial001_an.py+52 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.bool import tutorial001_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output20+21+22+def test_no_force():23+ result = runner.invoke(app)24+ assert result.exit_code == 025+ assert "Not forcing" in result.output26+27+28+def test_force():29+ result = runner.invoke(app, ["--force"])30+ assert result.exit_code == 031+ assert "Forcing operation" in result.output32+33+34+def test_invalid_no_force():35+ result = runner.invoke(app, ["--no-force"])36+ assert result.exit_code != 037+ # TODO: when deprecating Click 7, remove second option38+39+ assert (40+ "No such option: --no-force" in result.output41+ or "no such option: --no-force" in result.output42+ )43+44+45+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial002_an.py+71 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.bool import tutorial002_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output22+23+24+def 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 = rich33+34+35+def test_main():36+ result = runner.invoke(app)37+ assert result.exit_code == 038+ assert "I don't know what you want yet" in result.output39+40+41+def test_accept():42+ result = runner.invoke(app, ["--accept"])43+ assert result.exit_code == 044+ assert "Accepting!" in result.output45+46+47+def test_reject():48+ result = runner.invoke(app, ["--reject"])49+ assert result.exit_code == 050+ assert "Rejecting!" in result.output51+52+53+def test_invalid_no_accept():54+ result = runner.invoke(app, ["--no-accept"])55+ assert result.exit_code != 056+ # TODO: when deprecating Click 7, remove second option57+58+ assert (59+ "No such option: --no-accept" in result.output60+ or "no such option: --no-accept" in result.output61+ )62+63+64+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial003_an.py+43 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.bool import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output22+23+24+def test_force():25+ result = runner.invoke(app, ["-f"])26+ assert result.exit_code == 027+ assert "Forcing operation" in result.output28+29+30+def test_no_force():31+ result = runner.invoke(app, ["-F"])32+ assert result.exit_code == 033+ assert "Not forcing" in result.output34+35+36+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_bool/test_tutorial004_an.py+47 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.bool import tutorial004_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_help():16+ result = runner.invoke(app, ["--help"])17+ assert result.exit_code == 018+ assert "-d" in result.output19+ assert "--demo" in result.output20+21+22+def test_main():23+ result = runner.invoke(app)24+ assert result.exit_code == 025+ assert "Running in production" in result.output26+27+28+def test_demo():29+ result = runner.invoke(app, ["--demo"])30+ assert result.exit_code == 031+ assert "Running demo" in result.output32+33+34+def test_short_demo():35+ result = runner.invoke(app, ["-d"])36+ assert result.exit_code == 037+ assert "Running demo" in result.output38+39+40+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_datetime/test_tutorial002_an.py+34 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.datetime import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def 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.output19+20+21+def 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.output25+26+27+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_enum/test_tutorial002_an.py+34 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.enum import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_upper():16+ result = runner.invoke(app, ["--network", "CONV"])17+ assert result.exit_code == 018+ assert "Training neural network of type: conv" in result.output19+20+21+def test_mix():22+ result = runner.invoke(app, ["--network", "LsTm"])23+ assert result.exit_code == 024+ assert "Training neural network of type: lstm" in result.output25+26+27+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_file/test_tutorial001_an.py+33 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.file import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output24+25+26+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_file/test_tutorial002_an.py+35 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.file import tutorial002_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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 text26+27+28+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_file/test_tutorial003_an.py+32 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.file import tutorial003_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output23+24+25+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_file/test_tutorial004_an.py+36 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.file import tutorial004_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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 text27+28+29+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_file/test_tutorial005_an.py+38 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.file import tutorial005_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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 text29+30+31+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_number/test_tutorial001_an.py+99 added
1+import subprocess2+import sys3+4+import typer5+import typer.core6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.number import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output23+24+25+def 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 = rich35+36+37+def 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.output43+44+45+def 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+ )57+58+59+def test_invalid_age():60+ result = runner.invoke(app, ["5", "--age", "15"])61+ assert result.exit_code != 062+ # TODO: when deprecating Click 7, remove second option63+64+ 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+ )69+70+71+def 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 option75+76+ 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+ )82+83+84+def 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.output90+91+92+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_number/test_tutorial002_an.py+42 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.number import tutorial002_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_invalid_id():16+ result = runner.invoke(app, ["1002"])17+ assert result.exit_code != 018+ # TODO: when deprecating Click 7, remove second option19+20+ 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+ )25+26+27+def 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.output33+34+35+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_number/test_tutorial003_an.py+58 added
1+import subprocess2+import sys3+4+import typer5+from typer.testing import CliRunner6+7+from docs_src.parameter_types.number import tutorial003_an as mod8+9+runner = CliRunner()10+11+app = typer.Typer()12+app.command()(mod.main)13+14+15+def test_main():16+ result = runner.invoke(app)17+ assert result.exit_code == 018+ assert "Verbose level is 0" in result.output19+20+21+def test_verbose_1():22+ result = runner.invoke(app, ["--verbose"])23+ assert result.exit_code == 024+ assert "Verbose level is 1" in result.output25+26+27+def test_verbose_3():28+ result = runner.invoke(app, ["--verbose", "--verbose", "--verbose"])29+ assert result.exit_code == 030+ assert "Verbose level is 3" in result.output31+32+33+def test_verbose_short_1():34+ result = runner.invoke(app, ["-v"])35+ assert result.exit_code == 036+ assert "Verbose level is 1" in result.output37+38+39+def 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.output43+44+45+def test_verbose_short_3_condensed():46+ result = runner.invoke(app, ["-vvv"])47+ assert result.exit_code == 048+ assert "Verbose level is 3" in result.output49+50+51+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_path/test_tutorial001_an.py+55 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.path import tutorial001_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output22+23+24+def 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.output31+32+33+def 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.output40+41+42+def 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.output46+47+48+def 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.stdoutadded:tests/test_tutorial/test_parameter_types/test_path/test_tutorial002_an.py+48 added
1+import subprocess2+import sys3+from pathlib import Path4+5+import typer6+from typer.testing import CliRunner7+8+from docs_src.parameter_types.path import tutorial002_an as mod9+10+runner = CliRunner()11+12+app = typer.Typer()13+app.command()(mod.main)14+15+16+def 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.output24+25+26+def 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.output33+34+35+def 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.output39+40+41+def 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.stdoutadded:tests/test_tutorial/test_testing/test_app02_an.py+19 added
1+import subprocess2+import sys3+4+from docs_src.testing.app02_an import main as mod5+from docs_src.testing.app02_an.test_main import test_app6+7+8+def test_app02_an():9+ test_app()10+11+12+def 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.stdoutadded:tests/test_ambiguous_params.py+230 added
1+import pytest2+import typer3+from typer.testing import CliRunner4+from typer.utils import (5+ AnnotatedParamWithDefaultValueError,6+ DefaultFactoryAndDefaultValueError,7+ MixedAnnotatedAndDefaultStyleError,8+ MultipleTyperAnnotationsError,9+ _split_annotation_from_typer_annotations,10+)11+from typing_extensions import Annotated12+13+runner = CliRunner()14+15+16+def 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) == 124+25+26+def test_forbid_default_value_in_annotated_argument():27+ app = typer.Typer()28+29+ # 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 cover34+35+ with pytest.raises(AnnotatedParamWithDefaultValueError) as excinfo:36+ runner.invoke(app)37+38+ assert vars(excinfo.value) == dict(39+ param_type=typer.models.ArgumentInfo,40+ argument_name="my_param",41+ )42+43+44+def test_allow_options_to_have_names():45+ app = typer.Typer()46+47+ @app.command()48+ def cmd(my_param: Annotated[str, typer.Option("--some-opt")]):49+ print(my_param)50+51+ result = runner.invoke(app, ["--some-opt", "hello"])52+ assert result.exit_code == 0, result.output53+ assert "hello" in result.output54+55+56+@pytest.mark.parametrize(57+ ["param", "param_info_type"],58+ [59+ (typer.Argument, typer.models.ArgumentInfo),60+ (typer.Option, typer.models.OptionInfo),61+ ],62+)63+def test_forbid_annotated_param_and_default_param(param, param_info_type):64+ app = typer.Typer()65+66+ @app.command()67+ def cmd(my_param: Annotated[str, param()] = param("foo")):68+ ... # pragma: no cover69+70+ with pytest.raises(MixedAnnotatedAndDefaultStyleError) as excinfo:71+ runner.invoke(app)72+73+ 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+ )78+79+80+def test_forbid_multiple_typer_params_in_annotated():81+ app = typer.Typer()82+83+ @app.command()84+ def cmd(my_param: Annotated[str, typer.Argument(), typer.Argument()]):85+ ... # pragma: no cover86+87+ with pytest.raises(MultipleTyperAnnotationsError) as excinfo:88+ runner.invoke(app)89+90+ assert vars(excinfo.value) == dict(argument_name="my_param")91+92+93+def test_allow_multiple_non_typer_params_in_annotated():94+ app = typer.Typer()95+96+ @app.command()97+ def cmd(my_param: Annotated[str, "someval", typer.Argument(), 4] = "hello"):98+ print(my_param)99+100+ result = runner.invoke(app)101+ # Should behave like normal102+ assert result.exit_code == 0, result.output103+ assert "hello" in result.output104+105+106+@pytest.mark.parametrize(107+ ["param", "param_info_type"],108+ [109+ (typer.Argument, typer.models.ArgumentInfo),110+ (typer.Option, typer.models.OptionInfo),111+ ],112+)113+def test_forbid_default_factory_and_default_value_in_annotated(param, param_info_type):114+ def make_string():115+ return "foo" # pragma: no cover116+117+ app = typer.Typer()118+119+ @app.command()120+ def cmd(my_param: Annotated[str, param(default_factory=make_string)] = "hello"):121+ ... # pragma: no cover122+123+ with pytest.raises(DefaultFactoryAndDefaultValueError) as excinfo:124+ runner.invoke(app)125+126+ assert vars(excinfo.value) == dict(127+ argument_name="my_param",128+ param_type=param_info_type,129+ )130+131+132+@pytest.mark.parametrize(133+ "param",134+ [135+ typer.Argument,136+ typer.Option,137+ ],138+)139+def test_allow_default_factory_with_default_param(param):140+ def make_string():141+ return "foo"142+143+ app = typer.Typer()144+145+ @app.command()146+ def cmd(my_param: str = param(default_factory=make_string)):147+ print(my_param)148+149+ result = runner.invoke(app)150+ assert result.exit_code == 0, result.output151+ assert "foo" in result.output152+153+154+@pytest.mark.parametrize(155+ ["param", "param_info_type"],156+ [157+ (typer.Argument, typer.models.ArgumentInfo),158+ (typer.Option, typer.models.OptionInfo),159+ ],160+)161+def test_forbid_default_and_default_factory_with_default_param(param, param_info_type):162+ def make_string():163+ return "foo" # pragma: no cover164+165+ app = typer.Typer()166+167+ @app.command()168+ def cmd(my_param: str = param("hi", default_factory=make_string)):169+ ... # pragma: no cover170+171+ with pytest.raises(DefaultFactoryAndDefaultValueError) as excinfo:172+ runner.invoke(app)173+174+ assert vars(excinfo.value) == dict(175+ argument_name="my_param",176+ param_type=param_info_type,177+ )178+179+180+@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+)229+def test_error_rendering(error, message):230+ assert str(error) == messageadded:tests/test_annotated.py+59 added
1+import typer2+from typer.testing import CliRunner3+from typing_extensions import Annotated4+5+runner = CliRunner()6+7+8+def test_annotated_argument_with_default():9+ app = typer.Typer()10+11+ @app.command()12+ def cmd(val: Annotated[int, typer.Argument()] = 0):13+ print(f"hello {val}")14+15+ result = runner.invoke(app)16+ assert result.exit_code == 0, result.output17+ assert "hello 0" in result.output18+19+ result = runner.invoke(app, ["42"])20+ assert result.exit_code == 0, result.output21+ assert "hello 42" in result.output22+23+24+def test_annotated_argument_with_default_factory():25+ app = typer.Typer()26+27+ def make_string():28+ return "I made it"29+30+ @app.command()31+ def cmd(val: Annotated[str, typer.Argument(default_factory=make_string)]):32+ print(val)33+34+ result = runner.invoke(app)35+ assert result.exit_code == 0, result.output36+ assert "I made it" in result.output37+38+ result = runner.invoke(app, ["overridden"])39+ assert result.exit_code == 0, result.output40+ assert "overridden" in result.output41+42+43+def test_annotated_option_with_argname_doesnt_mutate_multiple_calls():44+ app = typer.Typer()45+46+ @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")52+53+ result = runner.invoke(app)54+ assert result.exit_code == 0, result.output55+ assert "Not forcing" in result.output56+57+ result = runner.invoke(app, ["--force"])58+ assert result.exit_code == 0, result.output59+ assert "Forcing operation" in result.outputadded: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-errors4+5+import sys6+from os import PathLike7+from 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+)28+29+from typing_extensions import Annotated, Literal30+31+try:32+ from typing import _TypingBase as typing_base # type: ignore33+except ImportError:34+ from typing import _Final as typing_base # type: ignore35+36+try:37+ from typing import GenericAlias as TypingGenericAlias # type: ignore38+except ImportError:39+ # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on)40+ TypingGenericAlias = ()41+42+try:43+ from types import UnionType as TypesUnionType # type: ignore44+except ImportError:45+ # python < 3.10 does not have UnionType (str | int, byte | bool and so on)46+ TypesUnionType = ()47+48+49+if sys.version_info < (3, 7):50+ if TYPE_CHECKING:51+52+ class ForwardRef:53+ def __init__(self, arg: Any):54+ pass55+56+ def _eval_type(self, globalns: Any, localns: Any) -> Any:57+ pass58+59+ else:60+ from typing import _ForwardRef as ForwardRef61+else:62+ from typing import ForwardRef63+64+65+if sys.version_info < (3, 7):66+67+ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:68+ return type_._eval_type(globalns, localns)69+70+elif sys.version_info < (3, 9):71+72+ def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any:73+ return type_._evaluate(globalns, localns)74+75+else:76+77+ 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())81+82+83+if 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_hints88+89+else:90+91+ 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)93+94+95+if sys.version_info < (3, 7):96+ from typing import Callable as Callable97+98+ AnyCallable = Callable[..., Any]99+ NoArgAnyCallable = Callable[[], Any]100+else:101+ from collections.abc import Callable as Callable102+ from typing import Callable as TypingCallable103+104+ AnyCallable = TypingCallable[..., Any]105+ NoArgAnyCallable = TypingCallable[[], Any]106+107+108+# Annotated[...] is implemented by returning an instance of one of these classes, depending on109+# python/typing_extensions version.110+AnnotatedTypeNames = {"AnnotatedMeta", "_AnnotatedAlias"}111+112+113+if sys.version_info < (3, 8):114+115+ 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)121+122+else:123+ from typing import get_origin as _typing_get_origin124+125+ 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)135+136+137+if sys.version_info < (3, 7): # noqa: C901 (ignore complexity)138+139+ def get_args(t: Type[Any]) -> Tuple[Any, ...]:140+ """Simplest get_args compatibility layer possible.141+142+ 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).146+147+ """148+ if type(t).__name__ in AnnotatedTypeNames:149+ return t.__args__ + t.__metadata__150+ return getattr(t, "__args__", ())151+152+elif sys.version_info < (3, 8): # noqa: C901153+ from typing import _GenericAlias154+155+ def get_args(t: Type[Any]) -> Tuple[Any, ...]:156+ """Compatibility version of get_args for python 3.7.157+158+ 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__", ())169+170+else:171+ from typing import get_args as _typing_get_args172+173+ 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 ()183+184+ def get_args(tp: Type[Any]) -> Tuple[Any, ...]:185+ """Get type arguments with all substitutions performed.186+187+ 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+ )201+202+203+if sys.version_info < (3, 9):204+205+ 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.208+209+ Examples::210+ typing.List['Hero'] == typing.List[ForwardRef('Hero')]211+ """212+ return tp213+214+else:215+ from typing import _UnionGenericAlias # type: ignore216+217+ from typing_extensions import _AnnotatedAlias218+219+ def convert_generics(tp: Type[Any]) -> Type[Any]:220+ """221+ Recursively searches for `str` type hints and replaces them with ForwardRef.222+223+ 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 tp232+233+ args = get_args(tp)234+235+ # typing.Annotated needs special treatment236+ if origin is Annotated:237+ return _AnnotatedAlias(convert_generics(args[0]), args[1:])238+239+ # 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+ )246+247+ 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 tp260+261+262+if sys.version_info < (3, 10):263+264+ def is_union(tp: Optional[Type[Any]]) -> bool:265+ return tp is Union266+267+ WithArgsTypes = (TypingGenericAlias,)268+269+else:270+ import types271+ import typing272+273+ def is_union(tp: Optional[Type[Any]]) -> bool:274+ return tp is Union or tp is types.UnionType # noqa: E721275+276+ WithArgsTypes = (typing._GenericAlias, types.GenericAlias, types.UnionType)277+278+279+if sys.version_info < (3, 9):280+ StrPath = Union[str, PathLike]281+else: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]]288+289+290+if TYPE_CHECKING:291+ # Only in Pydantic292+ # from .fields import ModelField293+294+ 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]306+307+__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+)347+348+349+NoneType = None.__class__350+351+352+NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None])353+354+355+if 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.361+362+ def is_none_type(type_: Any) -> bool:363+ return type_ in NONE_TYPES364+365+elif 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 this369+370+ 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 False376+377+else:378+379+ def is_none_type(type_: Any) -> bool:380+ for none_type in NONE_TYPES:381+ if type_ is none_type:382+ return True383+ return False384+385+386+def 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__393+394+ if is_union(get_origin(v)):395+ return f'Union[{", ".join(map(display_as_type, get_args(v)))}]'396+397+ if isinstance(v, WithArgsTypes):398+ # Generic alias are constructs like `list[int]`399+ return str(v).replace("typing.", "")400+401+ try:402+ return v.__name__403+ except AttributeError:404+ # happens with typing objects405+ return str(v).replace("typing.", "")406+407+408+def 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.413+414+ 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__425+426+ 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 annotations446+447+448+def is_callable_type(type_: Type[Any]) -> bool:449+ return type_ is Callable or get_origin(type_) is Callable450+451+452+if sys.version_info >= (3, 7):453+454+ def is_literal_type(type_: Type[Any]) -> bool:455+ return Literal is not None and get_origin(type_) is Literal456+457+ def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:458+ return get_args(type_)459+460+else:461+462+ 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+ )468+469+ def literal_values(type_: Type[Any]) -> Tuple[Any, ...]:470+ return type_.__values__471+472+473+def 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_,)481+482+ values = literal_values(type_)483+ return tuple(x for value in values for x in all_literal_values(value))484+485+486+def 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_issubclass492+493+ return lenient_issubclass(type_, tuple) and hasattr(type_, "_fields")494+495+496+def 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_issubclass502+503+ return lenient_issubclass(type_, dict) and hasattr(type_, "__total__")504+505+506+test_type = NewType("test_type", str)507+508+509+def 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: ignore514+515+516+def new_type_supertype(type_: Type[Any]) -> Type[Any]:517+ while hasattr(type_, "__supertype__"):518+ type_ = type_.__supertype__519+ return type_520+521+522+def _check_classvar(v: Optional[Type[Any]]) -> bool:523+ if v is None:524+ return False525+526+ return v.__class__ == ClassVar.__class__ and (527+ sys.version_info < (3, 7) or getattr(v, "_name", None) == "ClassVar"528+ )529+530+531+def is_classvar(ann_type: Type[Any]) -> bool:532+ if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)):533+ return True534+535+ # 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 True541+542+ return False543+544+545+# 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()553+554+# if field.sub_fields:555+# for sub_f in field.sub_fields:556+# update_field_forward_refs(sub_f, globalns=globalns, localns=localns)557+558+# if field.discriminator_key is not None:559+# field.prepare_discriminated_union_sub_fields()560+561+562+# 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 = {}577+578+# globalns.setdefault(model.__name__, model)579+580+# for f in fields:581+# try:582+# update_field_forward_refs(f, globalns=globalns, localns=localns)583+# except exc_to_suppress:584+# pass585+586+# 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+# continue593+594+# try:595+# new_key = evaluate_forwardref(fr, globalns, localns or None)596+# except exc_to_suppress: # pragma: no cover597+# continue598+599+# json_encoders[new_key] = json_encoders.pop(key)600+601+602+def 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 None618+619+620+def 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 lines183 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 # TyperArgument43 unmodified lines235 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 # TyperArgument47 unmodified lines291 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 # Option45 unmodified lines345 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 # TyperArgument56 unmodified lines410 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 # TyperArgument37 unmodified lines456 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 # TyperArgument59 unmodified linesmodified:typer/params.py+10 added-4 removed
9 unmodified lines10 11 @overload12 def 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 lines24 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 lines73 74 @overload75 def 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 lines87 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 lines135 136 137 def 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 lines149 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 # Option46 unmodified lines204 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 # Option147 unmodified lines360 361 362 def 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 lines374 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 # TyperArgument40 unmodified lines423 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 # TyperArgument31 unmodified linesmodified:typer/utils.py+174 added-5 removed
1 import inspect2+from copy import copy2-from typing import Any, Callable, Dict, get_type_hints3+from typing import Any, Callable, Dict, List, Tuple, Type, cast, get_type_hints4 4-from .models import ParamMeta5+from typing_extensions import Annotated6 7+from ._typing import get_args, get_origin8+from .models import ArgumentInfo, OptionInfo, ParameterInfo, ParamMeta9 10+11+def _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 cover21+22+23+class AnnotatedParamWithDefaultValueError(Exception):24+ argument_name: str25+ param_type: Type[ParameterInfo]26+27+ def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):28+ self.argument_name = argument_name29+ self.param_type = param_type30+31+ 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+ )37+38+39+class MixedAnnotatedAndDefaultStyleError(Exception):40+ argument_name: str41+ annotated_param_type: Type[ParameterInfo]42+ default_param_type: Type[ParameterInfo]43+44+ 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_type53+54+ 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 msg64+65+66+class MultipleTyperAnnotationsError(Exception):67+ argument_name: str68+69+ def __init__(self, argument_name: str):70+ self.argument_name = argument_name71+72+ def __str__(self) -> str:73+ return (74+ "Cannot specify multiple `Annotated` Typer arguments"75+ f" for {self.argument_name!r}"76+ )77+78+79+class DefaultFactoryAndDefaultValueError(Exception):80+ argument_name: str81+ param_type: Type[ParameterInfo]82+83+ def __init__(self, argument_name: str, param_type: Type[ParameterInfo]):84+ self.argument_name = argument_name85+ self.param_type = param_type86+87+ 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+ )93+94+95+def _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+ ]106+107+108 def 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)118+119+ default = param.default120+ if typer_annotations:121+ # It's something like `my_param: Annotated[str, Argument()]`122+ [parameter_info] = typer_annotations123+124+ # 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+ )131+132+ parameter_info = copy(parameter_info)133+134+ # 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 = ...151+152+ # 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.default162+163+ default = parameter_info164+ elif param.name in type_hints:165+ # Resolve forward references.166 annotation = type_hints[param.name]167+168+ 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_info183+184 params[param.name] = ParamMeta(16- name=param.name, default=param.default, annotation=annotation185+ name=param.name, default=default, annotation=annotation186 )187 return paramsmodified:.coveragerc+3 added
3 unmodified lines4 typer5 tests6 docs_src7 8+omit =9+ typer/_typing.py10+11 parallel = True12 context = '${CONTEXT}'13 14 [report]9 unmodified linesmodified:mkdocs.yml+3 added
102 unmodified lines103 - pymdownx.tabbed:104 alternate_style: true105 - mdx_include:106 base_path: docs107+ # Enable while writing docs to simplify highlighting108+ # - pymdownx.highlight:109+ # linenums: true110 111 extra:112 analytics:113 provider: google23 unmodified linesmodified:pyproject.toml+2 added-1 removed
28 unmodified lines29 "Programming Language :: Python :: 3.11",30 "License :: OSI Approved :: MIT License"31 ]32 requires = [33- "click >= 7.1.1, <9.0.0"33+ "click >= 7.1.1, <9.0.0",34+ "typing-extensions >= 3.7.4.3",35 ]36 description-file = "README.md"37 requires-python = ">=3.6"38 58 unmodified lines