📝 Remove documentation pages that reference using Click directly (#1538)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sofie Van Landeghem · committed by GitHub · parent 40430e1 · Browse files · 37 files·+26 added−790 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>
Diff stats
37 files+26 added−790 removed
- tests:+0 added−209 removed
- other:+26 added−581 removed
Provenance
- Commit
2f265f2- Tree
dc0caf5- Author
Sofie Van Landeghem <svlandeg@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
40430e1
37 files changed+26 added−790 removed
modified:docs/reference/context.md+6 added-5 removed
12345345678789101112131425 unmodified lines# Context
When you create a Typer application it uses Click underneath.And every Click application has a special object called a [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) that is normally hidden.But you can access the context by declaring a function parameter of type `typer.Context`.Every app has a special internal object that keeps track of state relevant to the script's execution.For some advanced use-cases, you may want to access it directly.This can be done by declaring a function parameter of type `typer.Context`.
The same way you can access the 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`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.Similarly, you can also declare a function parameter with type `typer.CallbackParam` in case a callback could be usedby several CLI parameters, and you need to figure out which one it was.
```pythonfrom typing import Annotated
import typer25 unmodified linesmodified:docs/tutorial/arguments/envvar.md-8 removed
114 unmodified linesExpand all115116117118119120121122123124125126114 unmodified linesExpand allHello Mr. Wednesday```
</div>
/// note | Technical Details
In Click applications the env vars are hidden by default. 🙈
In **Typer** these env vars are shown by default. 👀
///modified:docs/tutorial/arguments/help.md+3 added-29 removed
110 unmodified lines111 ```112 113 </div>114 115-/// note | Technical Details116-117-In Click applications the default values are hidden by default. 🙈118-119-In **Typer** these default values are shown by default. 👀120-121-///122-115 ## Custom default string116 117 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:118 138 unmodified lines257 But it won't show up in the main help text under the `Arguments` section.258 259 ///260 269-### Help text for *CLI arguments* in Click261+### Help text for *CLI arguments*262 271-Click itself doesn't support adding help for *CLI arguments*, and it doesn't generate help for them as in the "`Arguments:`" sections in the examples above.263+**Typer supports `help` for *CLI arguments*** to make it easier to have consistent help texts with a consistent format for your CLI programs. 🎨264 273-Not supporting `help` in *CLI arguments* is an intentional <a href="https://click.palletsprojects.com/en/7.x/documentation/#documenting-arguments" class="external-link" target="_blank">design decision in Click</a>:274-275-> This is to follow the general convention of Unix tools of using arguments for only the most necessary things, and to document them in the command help text by referring to them by name.276-277-So, in Click applications, you are expected to write all the documentation for *CLI arguments* by hand in the <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.278-279----280-281-Nevertheless, **Typer supports `help` for *CLI arguments***. ✨ 🤷♂282-283-**Typer** doesn't follow that convention and instead supports `help` to make it easier to have consistent help texts with a consistent format for your CLI programs. 🎨284-265 This is also to help you create CLI programs that are ✨ awesome ✨ *by default*. With very little code.266 287-If you want to keep Click's convention in a **Typer** app, you can do it with the `hidden` parameter as described above.288-289-/// note | Technical Details290-291-To support `help` in *CLI arguments* **Typer** does a lot of internal work in its own sub-classes of Click's internal classes.292-293-///267+If you don't want the CLI Argument to be shown in help outputs, you can set the `hidden` parameter to `True`.modified:docs/tutorial/commands/callback.md-24 removed
157 unmodified lines158 Creating user: Camila159 ```160 161 </div>162-163-## Click Group164-165-If you come from Click, this **Typer** callback is the equivalent of the function in a <a href="https://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands" class="external-link" target="_blank">Click Group</a>.166-167-For example:168-169-```Python170-import click171-172-@click.group()173-def cli():174- pass175-```176-177-The original function `cli` would be the equivalent of a Typer callback.178-179-/// note | Technical Details180-181-When using Click, it converts that `cli` variable to a Click `Group` object. And then the original function no longer exists in that variable.182-183-**Typer** doesn't do that, the callback function is not modified, only registered in the `typer.Typer` app. This is intentional, it's part of **Typer**'s design, to allow having editor auto completion and type checks.184-185-///modified:docs/tutorial/commands/context.md+1 added-3 removed
1 # Using the Context2 3-When you create a **Typer** application it uses Click underneath. And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/8.1.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.3+When you create a **Typer** application it always has a special, hidden object underneath called the "Context".4 5 But you can access the context by declaring a function parameter of type `typer.Context`.6 7 You might have read it in [CLI Option Callback and Context](../options/callback-and-context.md){.internal-link target=_blank}.90 unmodified lines98 ## Configuring the context99 100 You can pass configurations for the context when creating a command or callback.101 102-To read more about the available configurations check the docs for <a href="https://click.palletsprojects.com/en/7.x/api/#context" class="external-link" target="_blank">Click's `Context`</a>.103-102 For example, you could keep additional *CLI parameters* not declared in your CLI program with `ignore_unknown_options` and `allow_extra_args`.103 104 Then you can access those extra raw *CLI parameters* as a `list` of `str` in `ctx.args`:105 20 unmodified linesmodified:docs/tutorial/commands/index.md-20 removed
160 unmodified lines161 ```162 163 </div>164 165-## Click Group166-167-If you come from Click, a `typer.Typer` app with subcommands is more or less the equivalent of a <a href="https://click.palletsprojects.com/en/7.x/quickstart/#nesting-commands" class="external-link" target="_blank">Click Group</a>.168-169-/// note | Technical Details170-171-A `typer.Typer` app is *not* a Click Group, but it provides the equivalent functionality. And it creates a Click Group when calling it.172-173-It is not directly a Group because **Typer** doesn't modify the functions in your code to convert them to another type of object, it only registers them.174-175-///176-165 ## Decorator Technical Details166 167 When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.168 169 But Typer doesn't modify that function itself, the function is left as is.170 171 That means that if your function is simple enough that you could create it without using `typer.Option()` or `typer.Argument()`, you could use the same function for a **Typer** application and a **FastAPI** application putting both decorators on top, or similar tricks.184-185-/// note | Click Technical Details186-187-This behavior is a design difference with Click.188-189-In Click, when you add a `@click.command()` decorator it actually modifies the function underneath and replaces it with an object.190-191-///modified:docs/tutorial/multiple-values/options-with-multiple-values.md-8 removed
46 unmodified lines47 coins = user[1]48 is_wizard = user[2]49 ```50 51-/// tip52-53-Notice that the default is a tuple with `(None, None, None)`.54-55-You cannot simply use `None` here as the default because <a href="https://github.com/pallets/click/issues/472" class="external-link" target="_blank">Click doesn't support it</a>.56-57-///58-51 ## Check it52 53 Now let's see how this works in the terminal:54 31 unmodified linesmodified:docs/tutorial/options/callback-and-context.md+2 added-8 removed
119 unmodified lines120 </div>121 122 ### Fix completion - using the `Context`123 124-When you create a **Typer** application it uses Click underneath.124+Every Typer application has a special object called a "Context" that is normally hidden.125 126-And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.127-126 But you can access the context by declaring a function parameter of type `typer.Context`.127 128 The "context" has some additional data about the current execution of your program:129 26 unmodified lines156 </div>157 158 ## Using the `CallbackParam` object159 162-The same way you can access the `typer.Context` by declaring a function parameter with its value, you can declare another function parameter with type `typer.CallbackParam` to get the specific Click `Parameter` object.160+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 `Parameter` object.161 162 {* docs_src/options/callback/tutorial004_an_py310.py hl[8,11] *}163 164 It's probably not very common, but you could do it if you need it.22 unmodified lines187 You don't have to worry about their names, their order, etc.188 189 As it's based on standard Python types, it "**just works**". ✨190 193-### Click's `Parameter`194-195-The `typer.CallbackParam` is actually just a sub-class of Click's <a href="https://click.palletsprojects.com/en/7.x/api/#click.Parameter" class="external-link" target="_blank">`Parameter`</a>, so you get all the right completion in your editor.196-191 ### Callback with type annotations192 193 You can get the `typer.Context` and the `typer.CallbackParam` simply by declaring a function parameter of each type.194 11 unmodified linesmodified:docs/tutorial/options/help.md-8 removed
125 unmodified lines126 ```127 128 </div>129 130-/// note | Technical Details131-132-In Click applications the default values are hidden by default. 🙈133-134-In **Typer** these default values are shown by default. 👀135-136-///137-130 ## Custom default string131 132 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:133 24 unmodified linesmodified:docs/tutorial/options/version.md+1 added-1 removed
92 unmodified lines93 ### Fix with `is_eager`94 95 For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.96 97-That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:97+That will tell **Typer** that it should process this *CLI parameter* before the others:98 99 {* docs_src/options/version/tutorial003_an_py310.py hl[25:28] *}100 101 Check it:11 unmodified linesmodified:docs/tutorial/parameter-types/custom-types.md-11 removed
2 unmodified lines3 You can easily use your own custom types in your **Typer** applications.4 5 The way to do it is by providing a way to <abbr title="convert from some plain format, like the input text in the CLI, into Python objects">parse</abbr> input into your own types.6 7-There are two ways to achieve this:8-9-* Adding a type `parser`10-* Expanding Click's custom types11-7 ## Type Parser8 9 `typer.Argument` and `typer.Option` can create custom parameter types with a `parser` <abbr title="something that can be called like a function">callable</abbr>.10 11 {* docs_src/parameter_types/custom_types/tutorial001_an_py39.py hl[14:15,23:24] *}12 13 The function (or callable) that you pass to the parameter `parser` will receive the input value as a string and should return the parsed value with your own custom type.19-20-## Click Custom Type21-22-If you already have a <a href="https://click.palletsprojects.com/en/8.1.x/parameters/#implementing-custom-types" class="external-link" target="_blank">Click Custom Type</a>, you can use it in `typer.Argument()` and `typer.Option()` with the `click_type` parameter.23-24-{* docs_src/parameter_types/custom_types/tutorial002_an_py39.py hl[15:19,27:30] *}modified:docs/tutorial/parameter-types/file.md+1 added-19 removed
171 unmodified lines172 * It's automatically set for you by using the classes above.173 * Read more about it below.174 * `encoding`: to force a specific encoding, e.g. `"utf-8"`.175 * `lazy`: delay <abbr title="input and output, reading and writing files">I/O</abbr> operations. Automatic by default.176- * By default, when writing files, Click will generate a file-like object that is not yet the actual file. Once you start writing, it will go, open the file and start writing to it, but not before. This is mainly useful to avoid creating the file until you start writing to it. It's normally safe to leave this automatic. But you can overwrite it setting `lazy=False`. By default, it's `lazy=True` for writing and `lazy=False` for reading.176+ * By default, when writing files, Typer will generate a file-like object that is not yet the actual file. Once you start writing, it will go, open the file and start writing to it, but not before. This is mainly useful to avoid creating the file until you start writing to it. It's normally safe to leave this automatic. But you can overwrite it setting `lazy=False`. By default, it's `lazy=True` for writing and `lazy=False` for reading.177 * `atomic`: if true, all writes will actually go to a temporal file and then moved to the final destination after completing. This is useful with files modified frequently by several users/programs.178 179 ## Advanced `mode`180 50 unmodified lines231 This is a single line232 ```233 234 </div>235-236-## About the different types237-238-/// info239-240-These are technical details about why the different types/classes provided by **Typer**.241-242-But you don't need this information to be able to use them. You can skip it.243-244-///245-246-**Typer** provides you these different types (classes) because they inherit directly from the actual Python implementation that will be provided underneath for each case.247-248-This way your editor will give you the right type checks and completion for each type.249-250-Even if you use `lazy`. When you use `lazy` Click creates a especial object to delay writes, and serves as a "proxy" to the actual file that will be written. But this especial proxy object doesn't expose the attributes and methods needed for type checks and completion in the editor. If you access those attributes or call the methods, the "proxy" lazy object will call them in the final object and it will all work. But you wouldn't get autocompletion for them.251-252-But because these **Typer** classes inherit from the actual implementation that will be provided underneath (not the lazy object), you will get all the autocompletion and type checks in the editor.modified:docs/tutorial/parameter-types/index.md-7 removed
58 unmodified lines59 60 ## Watch next61 62 See more about specific types and validations in the next sections...63-64-65-/// info | Technical Details66-67-All the types you will see in the next sections are handled underneath by <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click's Parameter Types</a>.68-69-///modified:docs/tutorial/parameter-types/path.md+1 added-7 removed
55 unmodified lines56 It will not expand a tilde-prefix (something with `~`, like `~/Documents/`), as this is supposed to be done by the shell only.57 58 ///59 60-/// tip61-62-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>.63-64-///65-60 For example:61 62 {* docs_src/parameter_types/path/tutorial002_an_py39.py hl[14:19] *}63 38 unmodified lines102 103 ///104 105 * `allow_dash`: If this is set to True, a single dash to indicate standard streams is permitted.112-* `path_type`: optionally a string type that should be used to represent the path. The default is None which means the return value will be either bytes or unicode depending on what makes most sense given the input data Click deals with.106+* `path_type`: optionally a string type that should be used to represent the path. The default is `None` which means the return value will be either bytes or unicode depending on what makes most sense given the input data.modified:docs/tutorial/subcommands/add-typer.md+1 added-1 removed
163 unmodified lines164 Do you need sub-sub-sub-subcommands? Go ahead, create all the `typer.Typer()`s you need and put them together with `app.add_typer()`.165 166 In the next sections we'll update this with more features, but you already have the core idea.167 168-This way, in the same spirit of Click, **Typer** applications are composable, each `typer.Typer()` can be a *CLI app* by itself, but it can also be added as a command group to another Typer app.168+This way, **Typer** applications are composable, each `typer.Typer()` can be a *CLI app* by itself, but it can also be added as a command group to another Typer app.modified:docs/tutorial/exceptions.md+2 added-2 removed
14 unmodified lines15 ## Exceptions with Rich16 17 **Typer** will automatically use Rich to automatically show you nicely printed errors.18 19-It will **omit** all the parts of the traceback (the chain of things that called your function) that come from the internal parts in Typer and Click.19+It will **omit** all the parts of the traceback (the chain of things that called your function) that come from the internal parts in Typer.20 21 So, the error you see will be **much clearer** and simpler, to help you detect the problem in your code quickly:22 23 <div class="termy">87 unmodified lines111 But you should only enable it if you're not dealing with delicate information.112 113 ## Disable Short Output114 115-If you want to show the full exception, including the parts in Typer and Click, you can use the parameter `pretty_exceptions_short=False`:115+If you want to show the full exception, including the internal parts in Typer, you can use the parameter `pretty_exceptions_short=False`:116 117 {* docs_src/exceptions/tutorial003_py39.py hl[3] *}118 119 Now when you run it, you will see the whole output:150 unmodified linesmodified:docs/tutorial/options-autocompletion.md+4 added-16 removed
122 unmodified lines123 /// tip124 125 If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.126 127-Click checks specifically for a `tuple` when extracting the help text.127+In the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.128 129-So in the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.130-129 ///130 131 /// info132 21 unmodified lines154 ## Simplify with `yield`155 156 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.157 160-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:158+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** can iterate:159 160 {* docs_src/options_autocompletion/tutorial005_an_py39.py hl[12:15] *}161 162 That simplifies our code a bit and works the same.48 unmodified lines211 ### Getting completion for multiple values212 213 And the same way as before, we want to provide **completion** for those names. But we don't want to provide the **same names** for completion if they were already given in previous parameters.214 217-For that, we will access and use the "Context". When you create a **Typer** application it uses Click underneath. And every Click application has a special object called a <a href="https://click.palletsprojects.com/en/7.x/commands/#nested-handling-and-contexts" class="external-link" target="_blank">"Context"</a> that is normally hidden.215+For that, we will access and use the "Context". Every Typer application has a special object called a "Context" that is normally hidden.216 217 But you can access the context by declaring a function parameter of type `typer.Context`.218 219 And from that context you can get the current values for each parameter.85 unmodified lines305 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`.306 307 /// tip308 311-Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.309+Here we name the list of all the raw *CLI parameters* `args` because that's the usual convention.310 311 But it doesn't contain only *CLI arguments*, it has everything, including *CLI options* and values, as a raw `list` of `str`.312 313 ///67 unmodified lines381 * `typer.Context`: for the current context.382 * `list[str]`: for the raw *CLI parameters*.383 384 It doesn't matter how you name them, in which order, or which ones of the 3 options you declare. It will all "**just work**" ✨387-388-## Comparison to Click functionality389-390-Note that Click 7 had a similar [`autocompletion` function](https://click.palletsprojects.com/en/7.x/bashcomplete/), but it worked slightly differently.391-392-It required the callback function to take exactly the 3 arguments `ctx`, `args` and `incomplete` in that exact order, instead of matching them dynamically based on types, as Typer does.393-394-Since Click 8, this functionality has been replaced by [`shell_complete`](https://click.palletsprojects.com/en/8.1.x/api/#click.ParamType.shell_complete), which still depends on the exact order of arguments for the callback function.395-396-However, Typer continues to use the `autocompletion` functionality as described on this page.modified:docs/tutorial/printing.md+1 added-13 removed
186 unmodified lines187 You can probably skip the rest of this section. 🎉😎188 189 ///190 191-**Typer** also has a small utility `typer.echo()` to print information on the screen, it comes directly from Click. But normally you shouldn't need it.191+**Typer** also has a small utility `typer.echo()` to print information on the screen. But normally you shouldn't need it.192 193 For the simplest cases, you can use the standard Python `print()`.194 195 And for the cases where you want to display data more beautifully, or more advanced content, you should use **Rich** instead.7 unmodified lines203 If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.204 205 And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.206 207-/// info208-209-`typer.echo()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/7.x/quickstart/#echoing" class="external-link" target="_blank">Click's docs</a>.210-211-///212-207 ### Color208 209 /// note | Technical Details210 40 unmodified lines251 * `blink`: enable or disable blinking.252 * `reverse`: enable or disable inverse rendering (foreground becomes background and the other way round).253 * `reset`: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.254 261-/// info262-263-You can read more about it in <a href="https://click.palletsprojects.com/en/7.x/api/#click.style" class="external-link" target="_blank">Click's docs about `style()`</a>264-265-///266-255 ### `typer.secho()` - style and print256 257 /// tip258 14 unmodified linesmodified:docs/tutorial/progressbar.md+2 added-8 removed
73 unmodified lines74 If you can use Rich, use the information above, the Rich docs, and skip the rest of this page. 😎75 76 ///77 78-But if you can't use Rich and have it disabled, Typer (actually Click) comes with a simple utility to show progress bars.78+But if you can't use Rich and have it disabled, Typer comes with a simple utility to show progress bars.79 80-/// info81-82-`typer.progressbar()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/8.1.x/utils/#showing-progress-bars" class="external-link" target="_blank">Click's docs</a>.83-84-///85-80 ### Use `typer.progressbar`81 82 /// tip83 22 unmodified lines106 ```107 108 And the `with` statement using `typer.progressbar()` gives you an object that you can iterate over, just like if it was the same thing that you would iterate over normally.109 116-But by iterating over this object **Typer** (actually Click) will know to update the progress bar:110+But by iterating over this object **Typer** will know to update the progress bar:111 112 ```Python113 users = ["Camila", "Rick", "Morty"]114 118 unmodified linesmodified:docs/tutorial/terminating.md+1 added-1 removed
44 unmodified lines45 Even though you are raising an exception, it doesn't necessarily mean there's an error.46 47 This is done with an exception because it works as an "error" and stops all execution.48 49-But then **Typer** (actually Click) catches it and just terminates the program normally.49+But then **Typer** catches it and just terminates the program normally.50 51 ///52 53 ## Exit with an error67 unmodified linesdeleted:docs/tutorial/using-click.md-193 removed
1-# Using Click2-3-/// warning4-5-This is a more advanced topic, if you are starting with **Typer**, feel free to skip it.6-7-It will be mostly useful for people that already work with Click and have questions around it.8-9-///10-11-**Typer** is powered by <a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a>. It does all the work underneath.12-13-Here is some more information related to using both together.14-15-## A single app with both Click and **Typer**16-17-If you already have a Click application and want to migrate to **Typer**, or to add some Typer components, you can get a Click `Command` from your Typer application and then use Click directly.18-19-### How Click works20-21-Before knowing how to combine Click and **Typer**, let's first check a little about how Click works.22-23-#### Click `Command`24-25-Any Click application has an object of class `Command`. That's, more or less, the most basic Click object.26-27-A `Command` can have its own *CLI arguments* and *CLI options*, and it has a function that it calls.28-29-For example, in this Click app:30-31-{* docs_src/using_click/tutorial001_py39.py hl[7,14] *}32-33-The original `hello` variable is converted by Click from a function to a `Command` object. And the original `hello` function is used by that `Command` internally, but it is no longer named `hello` (as `hello` is now a Click `Command`).34-35-#### Click `Group`36-37-Then Click also has a `Group` class, it **inherits from `Command`**. So, a `Group` object is *also* a `Command`.38-39-A `Group` can also have its own *CLI arguments* and *CLI options*.40-41-A `Group` can have subcommands of class `Command` or sub groups of class `Group` as well.42-43-And a `Group` can also have a function that it calls, right before calling the function for any specific subcommand.44-45-For example:46-47-{* docs_src/using_click/tutorial002_py39.py hl[5,19,20] *}48-49-The `cli` variable is converted by Click from a function to a `Group` object. And the original `cli` function is used by that `Group` internally.50-51-/// tip52-53-The original `cli` function would be the equivalent of a [Typer Callback](./commands/callback.md){.internal-link target=_blank}.54-55-///56-57-Then the `cli` variable, that now is a `Group` object, is used to add sub-commands.58-59-### How **Typer** works60-61-Typer doesn't modify the functions. You create an explicit variable of class `typer.Typer` and use it to *register* those functions.62-63-And then, when you call the app, Typer goes and creates a Click `Command` (or `Group`), and then calls it.64-65-If your app only has one command, then when you call it, **Typer** creates a single Click `Command` object and calls it.66-67-But **Typer** creates a Click `Group` object if your app has any of:68-69-* More than one command.70-* A callback.71-* Sub-Typer apps (sub commands).72-73-/// tip74-75-If you want to learn more about this check the section [One or Multiple Commands](./commands/one-or-multiple.md){.internal-link target=_blank}.76-77-///78-79-### Combine Click and **Typer**80-81-**Typer** uses an internal function `typer.main.get_command()` to generate a Click `Command` (or `Group`) from a `typer.Typer` object.82-83-You can use it directly, and use the Click object with other Click applications.84-85-### Including a Click app in a **Typer** app86-87-For example, you could have a **Typer** app, generate a Click `Group` from it, and then include other Click apps in it:88-89-{* docs_src/using_click/tutorial003_py39.py hl[15,16,29,31,34] *}90-91-Notice that we add a callback that does nothing (only document the CLI program), to make sure **Typer** creates a Click `Group`. That way we can add sub-commands to that Click `Group`.92-93-Then we generate a Click object from our `typer.Typer` app (`typer_click_object`), and then we can include another Click object (`hello`) in this Click `Group`.94-95-And that way, our **Typer** app will have a subcommand `top` built with Typer, and a subcommand `hello` built with Click.96-97-Check it:98-99-<div class="termy">100-101-```console102-$ python main.py --help103-104-// Notice we have both subcommands, top and hello105-Usage: main.py [OPTIONS] COMMAND [ARGS]...106-107-Options:108- --install-completion Install completion for the current shell.109- --show-completion Show completion for the current shell, to copy it or customize the installation.110- --help Show this message and exit.111-112-Commands:113- hello114- top115-116-// Call the Typer part117-$ python main.py top118-119-The Typer app is at the top level120-121-// Call the Click part122-$ python main.py hello --name Camila123-124-Hello Camila!125-```126-127-</div>128-129-### Including a **Typer** app in a Click app130-131-The same way, you can do the contrary and include a **Typer** sub app in a bigger Click app:132-133-{* docs_src/using_click/tutorial004_py39.py hl[31,33,36] *}134-135-Notice that we don't have to add a callback or more commands, we can just create a **Typer** app that generates a single Click `Command`, as we don't need to include anything under the Typer app.136-137-Then we generate a Click object from our `typer.Typer` app (`typer_click_object`), and then we use **the Click `cli` to include** our Click object from our Typer app.138-139-In this case, the original Click app includes the **Typer** app.140-141-And then we call the *original Click* app, not the Typer app.142-143-Check it:144-145-<div class="termy">146-147-```console148-$ python main.py149-150-// We get our Typer app down there in the sub command151-Usage: main.py [OPTIONS] COMMAND [ARGS]...152-153-Options:154- --help Show this message and exit.155-156-Commands:157- dropdb158- initdb159- sub A single-command Typer sub app160-161-162-// Use the Click part163-$ python main.py initdb164-165-Initialized the database166-167-// And use the Typer part168-$ python main.py sub169-170-Typer is now below Click, the Click app is the top level171-```172-173-</div>174-175-## About Click decorators176-177-Typer apps don't work with Click decorators directly.178-179-This is because **Typer** doesn't modify functions to add metadata or to convert them to another object like Click does.180-181-So, things like `@click.pass_context` won't work.182-183-Most of the functionality provided by decorators in Click has an alternative way of doing it in **Typer**.184-185-For example, to access the context, you can just declare a function parameter of type `typer.Context`.186-187-/// tip188-189-You can read more about using the context in the docs: [Commands: Using the Context](commands/context.md){.internal-link target=_blank}190-191-///192-193-But if you need to use something based on Click decorators, you can always generate a Click object using the methods described above, and use it as you would normally use Click.modified:docs/features.md-8 removed
69 unmodified lines70 Then it extends those ideas with features and bug fixes. For example, **Typer** programs also support modern versions of PowerShell (e.g. in Windows 10) among all the other shells.71 72 ///73 74-## The power of Click75-76-<a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a> is one of the most popular tools for building CLIs in Python.77-78-**Typer** is based on it, so you get all its benefits.79-80-But you can write simpler code with the benefits of modern Python.81-74 ## Tested75 76 * 100% <abbr title="The amount of code that is automatically tested">test coverage</abbr>.77 * 100% <abbr title="Python type annotations, with this your editor and external tools can give you better support">type annotated</abbr> code base.1 unmodified linedeleted:docs_src/parameter_types/custom_types/tutorial002_an_py39.py-37 removed
1-from typing import Annotated2-3-import click4-import typer5-6-7-class CustomClass:8- def __init__(self, value: str):9- self.value = value10-11- def __repr__(self):12- return f"<CustomClass: value={self.value}>"13-14-15-class CustomClassParser(click.ParamType):16- name = "CustomClass"17-18- def convert(self, value, param, ctx):19- return CustomClass(value * 3)20-21-22-app = typer.Typer()23-24-25-@app.command()26-def main(27- custom_arg: Annotated[CustomClass, typer.Argument(click_type=CustomClassParser())],28- custom_opt: Annotated[29- CustomClass, typer.Option(click_type=CustomClassParser())30- ] = "Foo",31-):32- print(f"custom_arg is {custom_arg}")33- print(f"--custom-opt is {custom_opt}")34-35-36-if __name__ == "__main__":37- app()deleted:docs_src/parameter_types/custom_types/tutorial002_py39.py-33 removed
1-import click2-import typer3-4-5-class CustomClass:6- def __init__(self, value: str):7- self.value = value8-9- def __repr__(self):10- return f"<CustomClass: value={self.value}>"11-12-13-class CustomClassParser(click.ParamType):14- name = "CustomClass"15-16- def convert(self, value, param, ctx):17- return CustomClass(value * 3)18-19-20-app = typer.Typer()21-22-23-@app.command()24-def main(25- custom_arg: CustomClass = typer.Argument(click_type=CustomClassParser()),26- custom_opt: CustomClass = typer.Option("Foo", click_type=CustomClassParser()),27-):28- print(f"custom_arg is {custom_arg}")29- print(f"--custom-opt is {custom_opt}")30-31-32-if __name__ == "__main__":33- app()deleted:docs_src/using_click/__init__.py
deleted:docs_src/using_click/tutorial001_py39.py-14 removed
1-import click2-3-4-@click.command()5-@click.option("--count", default=1, help="Number of greetings.")6-@click.option("--name", prompt="Your name", help="The person to greet.")7-def hello(count, name):8- """Simple program that greets NAME for a total of COUNT times."""9- for x in range(count):10- click.echo(f"Hello {name}!")11-12-13-if __name__ == "__main__":14- hello()deleted:docs_src/using_click/tutorial002_py39.py-24 removed
1-import click2-3-4-@click.group()5-def cli():6- pass7-8-9-@click.command()10-def initdb():11- click.echo("Initialized the database")12-13-14-@click.command()15-def dropdb():16- click.echo("Dropped the database")17-18-19-cli.add_command(initdb)20-cli.add_command(dropdb)21-22-23-if __name__ == "__main__":24- cli()deleted:docs_src/using_click/tutorial003_py39.py-34 removed
1-import click2-import typer3-4-app = typer.Typer()5-6-7-@app.command()8-def top():9- """10- Top level command, form Typer11- """12- print("The Typer app is at the top level")13-14-15-@app.callback()16-def callback():17- """18- Typer app, including Click subapp19- """20-21-22-@click.command()23-@click.option("--name", prompt="Your name", help="The person to greet.")24-def hello(name):25- """Simple program that greets NAME for a total of COUNT times."""26- click.echo(f"Hello {name}!")27-28-29-typer_click_object = typer.main.get_command(app)30-31-typer_click_object.add_command(hello, "hello")32-33-if __name__ == "__main__":34- typer_click_object()deleted:docs_src/using_click/tutorial004_py39.py-36 removed
1-import click2-import typer3-4-5-@click.group()6-def cli():7- pass8-9-10-@cli.command()11-def initdb():12- click.echo("Initialized the database")13-14-15-@cli.command()16-def dropdb():17- click.echo("Dropped the database")18-19-20-app = typer.Typer()21-22-23-@app.command()24-def sub():25- """26- A single-command Typer sub app27- """28- print("Typer is now below Click, the Click app is the top level")29-30-31-typer_click_object = typer.main.get_command(app)32-33-cli.add_command(typer_click_object, "sub")34-35-if __name__ == "__main__":36- cli()deleted:tests/test_tutorial/test_parameter_types/test_custom_types/test_tutorial002.py-48 removed
1-import importlib2-import subprocess3-import sys4-from types import ModuleType5-6-import pytest7-from typer.testing import CliRunner8-9-runner = CliRunner()10-11-12-@pytest.fixture(13- name="mod",14- params=[15- pytest.param("tutorial002_py39"),16- pytest.param("tutorial002_an_py39"),17- ],18-)19-def get_mod(request: pytest.FixtureRequest) -> ModuleType:20- module_name = f"docs_src.parameter_types.custom_types.{request.param}"21- mod = importlib.import_module(module_name)22- return mod23-24-25-def test_help(mod: ModuleType):26- result = runner.invoke(mod.app, ["--help"])27- assert result.exit_code == 028-29-30-def test_parse_custom_type(mod: ModuleType):31- result = runner.invoke(mod.app, ["0", "--custom-opt", "1"])32- assert "custom_arg is <CustomClass: value=000>" in result.output33- assert "custom-opt is <CustomClass: value=111>" in result.output34-35-36-def test_parse_custom_type_with_default(mod: ModuleType):37- result = runner.invoke(mod.app, ["0"])38- assert "custom_arg is <CustomClass: value=000>" in result.output39- assert "custom-opt is <CustomClass: value=FooFooFoo>" in result.output40-41-42-def test_script(mod: ModuleType):43- result = subprocess.run(44- [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],45- capture_output=True,46- encoding="utf-8",47- )48- assert "Usage" in result.stdoutdeleted:tests/test_tutorial/test_using_click/__init__.py
deleted:tests/test_tutorial/test_using_click/test_tutorial001.py-47 removed
1-import subprocess2-import sys3-4-from click.testing import CliRunner5-6-from docs_src.using_click import tutorial001_py39 as mod7-8-runner = CliRunner()9-10-11-def test_help():12- result = runner.invoke(mod.hello, ["--help"])13- assert result.exit_code == 014- assert (15- "Simple program that greets NAME for a total of COUNT times." in result.output16- )17- assert "--name" in result.output18- assert "--count" in result.output19-20-21-def test_cli_prompt():22- result = runner.invoke(mod.hello, input="Camila\n")23- assert result.exit_code == 024- assert "Your name: Camila" in result.stdout25- assert "Hello Camila!" in result.stdout26-27-28-def test_cli_with_name():29- result = runner.invoke(mod.hello, ["--name", "Camila"])30- assert result.exit_code == 031- assert "Hello Camila!" in result.stdout32-33-34-def test_cli_with_name_and_count():35- result = runner.invoke(mod.hello, ["--name", "Camila", "--count", "3"])36- assert result.exit_code == 037- assert "Hello Camila!" in result.stdout38- assert result.stdout.count("Hello Camila!") == 339-40-41-def test_script():42- result = subprocess.run(43- [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],44- capture_output=True,45- encoding="utf-8",46- )47- assert "Usage" in result.stdoutdeleted:tests/test_tutorial/test_using_click/test_tutorial002.py-35 removed
1-import subprocess2-import sys3-4-from click.testing import CliRunner5-6-from docs_src.using_click import tutorial002_py39 as mod7-8-runner = CliRunner()9-10-11-def test_help():12- result = runner.invoke(mod.cli, ["--help"])13- assert result.exit_code == 014- assert "Commands" in result.output15- assert "initdb" in result.output16- assert "dropdb" in result.output17-18-19-def test_initdb():20- result = runner.invoke(mod.cli, ["initdb"])21- assert "Initialized the database" in result.stdout22-23-24-def test_dropdb():25- result = runner.invoke(mod.cli, ["dropdb"])26- assert "Dropped the database" in result.stdout27-28-29-def test_script():30- result = subprocess.run(31- [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],32- capture_output=True,33- encoding="utf-8",34- )35- assert "Usage" in result.stdoutdeleted:tests/test_tutorial/test_using_click/test_tutorial003.py-40 removed
1-import subprocess2-import sys3-4-from click.testing import CliRunner5-6-from docs_src.using_click import tutorial003_py39 as mod7-8-runner = CliRunner()9-10-11-def test_cli():12- result = runner.invoke(mod.typer_click_object, [])13- assert "Missing command" in result.output14-15-16-def test_help():17- result = runner.invoke(mod.typer_click_object, ["--help"])18- assert result.exit_code == 019- assert "Commands" in result.output20- assert "top" in result.output21- assert "hello" in result.output22-23-24-def test_typer():25- result = runner.invoke(mod.typer_click_object, ["top"])26- assert "The Typer app is at the top level" in result.stdout27-28-29-def test_click():30- result = runner.invoke(mod.typer_click_object, ["hello", "--name", "Camila"])31- assert "Hello Camila!" in result.stdout32-33-34-def test_script():35- result = subprocess.run(36- [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],37- capture_output=True,38- encoding="utf-8",39- )40- assert "Usage" in result.stdoutdeleted:tests/test_tutorial/test_using_click/test_tutorial004.py-39 removed
1-import subprocess2-import sys3-4-from click.testing import CliRunner5-6-from docs_src.using_click import tutorial004_py39 as mod7-8-runner = CliRunner()9-10-11-def test_cli():12- result = runner.invoke(mod.cli, [])13- assert "Usage" in result.output14- assert "dropdb" in result.output15- assert "sub" in result.output16-17-18-def test_typer():19- result = runner.invoke(mod.cli, ["sub"])20- assert "Typer is now below Click, the Click app is the top level" in result.stdout21-22-23-def test_click_initdb():24- result = runner.invoke(mod.cli, ["initdb"])25- assert "Initialized the database" in result.stdout26-27-28-def test_click_dropdb():29- result = runner.invoke(mod.cli, ["dropdb"])30- assert "Dropped the database" in result.stdout31-32-33-def test_script():34- result = subprocess.run(35- [sys.executable, "-m", "coverage", "run", mod.__file__, "--help"],36- capture_output=True,37- encoding="utf-8",38- )39- assert "Usage" in result.stdoutmodified:mkdocs.yml-1 removed
150 unmodified lines151 - tutorial/progressbar.md152 - tutorial/app-dir.md153 - tutorial/launch.md154 - tutorial/testing.md155- - tutorial/using-click.md155 - tutorial/package.md156 - tutorial/exceptions.md157 - tutorial/one-file-per-command.md158 - tutorial/typer-command.md96 unmodified linesmodified:pyproject.toml-2 removed
238 unmodified lines239 "docs_src/progressbar/tutorial005_py39.py" = ["B007"]240 "docs_src/progressbar/tutorial006_py39.py" = ["B007"]241 # Local variable `delete` is assigned to but never used242 "docs_src/prompt/tutorial003_py39.py" = ["F841"]243-# Loop control variable `x` not used within loop body244-"docs_src/using_click/tutorial001_py39.py" = ["B007"]243 # No need to worry about rich imports in docs244 "docs_src/*" = ["TID"]245 246 [tool.ruff.lint.isort]18 unmodified lines