Skip to content
Myr

📝 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

37 files+26 added−790 removed

modified:docs/reference/context.md+6 added-5 removed
modified:docs/tutorial/arguments/envvar.md-8 removed
modified:docs/tutorial/arguments/help.md+3 added-29 removed
110 unmodified lines
111```112113</div>114115/// note | Technical Details116117In Click applications the default values are hidden by default. 🙈118119In **Typer** these default values are shown by default. 👀120121///122115## Custom default string116117You 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 lines
257But it won't show up in the main help text under the `Arguments` section.258259///260269### Help text for *CLI arguments* in Click261### Help text for *CLI arguments*262271Click 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. 🎨264273Not 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>:274275> 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.276277So, 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>.278279---280281Nevertheless, **Typer supports `help` for *CLI arguments***. ✨ 🤷‍♂282283**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. 🎨284265This is also to help you create CLI programs that are ✨ awesome ✨ *by default*. With very little code.266287If you want to keep Click's convention in a **Typer** app, you can do it with the `hidden` parameter as described above.288289/// note | Technical Details290291To support `help` in *CLI arguments* **Typer** does a lot of internal work in its own sub-classes of Click's internal classes.292293///267If 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 lines
158Creating user: Camila159```160161</div>162163## Click Group164165If 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>.166167For example:168169```Python170import click171172@click.group()173def cli():174 pass175```176177The original function `cli` would be the equivalent of a Typer callback.178179/// note | Technical Details180181When using Click, it converts that `cli` variable to a Click `Group` object. And then the original function no longer exists in that variable.182183**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.184185///
modified:docs/tutorial/commands/context.md+1 added-3 removed
1# Using the Context23When 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.3When you create a **Typer** application it always has a special, hidden object underneath called the "Context".45But you can access the context by declaring a function parameter of type `typer.Context`.67You might have read it in [CLI Option Callback and Context](../options/callback-and-context.md){.internal-link target=_blank}.
90 unmodified lines
98## Configuring the context99100You can pass configurations for the context when creating a command or callback.101102To 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>.103102For example, you could keep additional *CLI parameters* not declared in your CLI program with `ignore_unknown_options` and `allow_extra_args`.103104Then you can access those extra raw *CLI parameters* as a `list` of `str` in `ctx.args`:105
20 unmodified lines
modified:docs/tutorial/commands/index.md-20 removed
160 unmodified lines
161```162163</div>164165## Click Group166167If 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>.168169/// note | Technical Details170171A `typer.Typer` app is *not* a Click Group, but it provides the equivalent functionality. And it creates a Click Group when calling it.172173It 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.174175///176165## Decorator Technical Details166167When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.168169But Typer doesn't modify that function itself, the function is left as is.170171That 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.184185/// note | Click Technical Details186187This behavior is a design difference with Click.188189In Click, when you add a `@click.command()` decorator it actually modifies the function underneath and replaces it with an object.190191///
modified:docs/tutorial/multiple-values/options-with-multiple-values.md-8 removed
46 unmodified lines
47coins = user[1]48is_wizard = user[2]49```5051/// tip5253Notice that the default is a tuple with `(None, None, None)`.5455You 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>.5657///5851## Check it5253Now let's see how this works in the terminal:54
31 unmodified lines
modified:docs/tutorial/options/callback-and-context.md+2 added-8 removed
119 unmodified lines
120</div>121122### Fix completion - using the `Context`123124When you create a **Typer** application it uses Click underneath.124Every Typer application has a special object called a "Context" that is normally hidden.125126And 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.127126But you can access the context by declaring a function parameter of type `typer.Context`.127128The "context" has some additional data about the current execution of your program:129
26 unmodified lines
156</div>157158## Using the `CallbackParam` object159162The 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.160The 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.161162{* docs_src/options/callback/tutorial004_an_py310.py hl[8,11] *}163164It's probably not very common, but you could do it if you need it.
22 unmodified lines
187You don't have to worry about their names, their order, etc.188189As it's based on standard Python types, it "**just works**". ✨190193### Click's `Parameter`194195The `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.196191### Callback with type annotations192193You can get the `typer.Context` and the `typer.CallbackParam` simply by declaring a function parameter of each type.194
11 unmodified lines
modified:docs/tutorial/options/help.md-8 removed
125 unmodified lines
126```127128</div>129130/// note | Technical Details131132In Click applications the default values are hidden by default. 🙈133134In **Typer** these default values are shown by default. 👀135136///137130## Custom default string131132You 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 lines
modified:docs/tutorial/options/version.md+1 added-1 removed
92 unmodified lines
93### Fix with `is_eager`9495For those cases, we can mark a *CLI parameter* (a *CLI option* or *CLI argument*) with `is_eager=True`.9697That will tell **Typer** (actually Click) that it should process this *CLI parameter* before the others:97That will tell **Typer** that it should process this *CLI parameter* before the others:9899{* docs_src/options/version/tutorial003_an_py310.py hl[25:28] *}100101Check it:
11 unmodified lines
modified:docs/tutorial/parameter-types/custom-types.md-11 removed
2 unmodified lines
3You can easily use your own custom types in your **Typer** applications.45The 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.67There are two ways to achieve this:89* Adding a type `parser`10* Expanding Click's custom types117## Type Parser89`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>.1011{* docs_src/parameter_types/custom_types/tutorial001_an_py39.py hl[14:15,23:24] *}1213The 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.1920## Click Custom Type2122If 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.2324{* 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 lines
172 * 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.178179## Advanced `mode`180
50 unmodified lines
231This is a single line232```233234</div>235236## About the different types237238/// info239240These are technical details about why the different types/classes provided by **Typer**.241242But you don't need this information to be able to use them. You can skip it.243244///245246**Typer** provides you these different types (classes) because they inherit directly from the actual Python implementation that will be provided underneath for each case.247248This way your editor will give you the right type checks and completion for each type.249250Even 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.251252But 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 lines
5960## Watch next6162See more about specific types and validations in the next sections...636465/// info | Technical Details6667All the types you will see in the next sections are handled underneath by <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click's Parameter Types</a>.6869///
modified:docs/tutorial/parameter-types/path.md+1 added-7 removed
55 unmodified lines
56It will not expand a tilde-prefix (something with `~`, like `~/Documents/`), as this is supposed to be done by the shell only.5758///5960/// tip6162All these parameters come directly from <a href="https://click.palletsprojects.com/en/7.x/parameters/#parameter-types" class="external-link" target="_blank">Click</a>.6364///6560For example:6162{* docs_src/parameter_types/path/tutorial002_an_py39.py hl[14:19] *}63
38 unmodified lines
102103///104105* `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 lines
164Do you need sub-sub-sub-subcommands? Go ahead, create all the `typer.Typer()`s you need and put them together with `app.add_typer()`.165166In the next sections we'll update this with more features, but you already have the core idea.167168This 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.168This 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 lines
15## Exceptions with Rich1617**Typer** will automatically use Rich to automatically show you nicely printed errors.1819It 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.19It will **omit** all the parts of the traceback (the chain of things that called your function) that come from the internal parts in Typer.2021So, the error you see will be **much clearer** and simpler, to help you detect the problem in your code quickly:2223<div class="termy">
87 unmodified lines
111But you should only enable it if you're not dealing with delicate information.112113## Disable Short Output114115If you want to show the full exception, including the parts in Typer and Click, you can use the parameter `pretty_exceptions_short=False`:115If you want to show the full exception, including the internal parts in Typer, you can use the parameter `pretty_exceptions_short=False`:116117{* docs_src/exceptions/tutorial003_py39.py hl[3] *}118119Now when you run it, you will see the whole output:
150 unmodified lines
modified:docs/tutorial/options-autocompletion.md+4 added-16 removed
122 unmodified lines
123/// tip124125If you want to have help text for each item, make sure each item in the list is a `tuple`. Not a `list`.126127Click checks specifically for a `tuple` when extracting the help text.127In the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.128129So in the end, the return will be a `list` (or other iterable) of `tuples` of 2 `str`.130129///130131/// info132
21 unmodified lines
154## Simplify with `yield`155156Instead of creating and returning a list with values (`str` or `tuple`), we can use `yield` with each value that we want in the completion.157160That 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:158That 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:159160{* docs_src/options_autocompletion/tutorial005_an_py39.py hl[12:15] *}161162That simplifies our code a bit and works the same.
48 unmodified lines
211### Getting completion for multiple values212213And 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.214217For 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.215For that, we will access and use the "Context". Every Typer application has a special object called a "Context" that is normally hidden.216217But you can access the context by declaring a function parameter of type `typer.Context`.218219And from that context you can get the current values for each parameter.
85 unmodified lines
305We get all the *CLI parameters* as a raw `list` of `str` by declaring a parameter with type `list[str]`, here it's named `args`.306307/// tip308311Here we name the list of all the raw *CLI parameters* `args` because that's the convention with Click.309Here we name the list of all the raw *CLI parameters* `args` because that's the usual convention.310311But it doesn't contain only *CLI arguments*, it has everything, including *CLI options* and values, as a raw `list` of `str`.312313///
67 unmodified lines
381* `typer.Context`: for the current context.382* `list[str]`: for the raw *CLI parameters*.383384It doesn't matter how you name them, in which order, or which ones of the 3 options you declare. It will all "**just work**" ✨387388## Comparison to Click functionality389390Note that Click 7 had a similar [`autocompletion` function](https://click.palletsprojects.com/en/7.x/bashcomplete/), but it worked slightly differently.391392It 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.393394Since 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.395396However, Typer continues to use the `autocompletion` functionality as described on this page.
modified:docs/tutorial/printing.md+1 added-13 removed
186 unmodified lines
187You can probably skip the rest of this section. 🎉😎188189///190191**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.192193For the simplest cases, you can use the standard Python `print()`.194195And for the cases where you want to display data more beautifully, or more advanced content, you should use **Rich** instead.
7 unmodified lines
203If you have some `bytes` objects, you would probably want to decode them intentionally and directly before trying to print them.204205And if you want to print data with colors and other features, you are much better off with the more advanced tools in **Rich**.206207/// info208209`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>.210211///212207### Color208209/// note | Technical Details210
40 unmodified lines
251* `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.254261/// info262263You 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>264265///266255### `typer.secho()` - style and print256257/// tip258
14 unmodified lines
modified:docs/tutorial/progressbar.md+2 added-8 removed
73 unmodified lines
74If you can use Rich, use the information above, the Rich docs, and skip the rest of this page. 😎7576///7778But if you can't use Rich and have it disabled, Typer (actually Click) comes with a simple utility to show progress bars.78But if you can't use Rich and have it disabled, Typer comes with a simple utility to show progress bars.7980/// info8182`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>.8384///8580### Use `typer.progressbar`8182/// tip83
22 unmodified lines
106```107108And 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.109116But by iterating over this object **Typer** (actually Click) will know to update the progress bar:110But by iterating over this object **Typer** will know to update the progress bar:111112```Python113users = ["Camila", "Rick", "Morty"]114
118 unmodified lines
modified:docs/tutorial/terminating.md+1 added-1 removed
44 unmodified lines
45Even though you are raising an exception, it doesn't necessarily mean there's an error.4647This is done with an exception because it works as an "error" and stops all execution.4849But then **Typer** (actually Click) catches it and just terminates the program normally.49But then **Typer** catches it and just terminates the program normally.5051///5253## Exit with an error
67 unmodified lines
deleted:docs/tutorial/using-click.md-193 removed
1# Using Click23/// warning45This is a more advanced topic, if you are starting with **Typer**, feel free to skip it.67It will be mostly useful for people that already work with Click and have questions around it.89///1011**Typer** is powered by <a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a>. It does all the work underneath.1213Here is some more information related to using both together.1415## A single app with both Click and **Typer**1617If 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.1819### How Click works2021Before knowing how to combine Click and **Typer**, let's first check a little about how Click works.2223#### Click `Command`2425Any Click application has an object of class `Command`. That's, more or less, the most basic Click object.2627A `Command` can have its own *CLI arguments* and *CLI options*, and it has a function that it calls.2829For example, in this Click app:3031{* docs_src/using_click/tutorial001_py39.py hl[7,14] *}3233The 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`).3435#### Click `Group`3637Then Click also has a `Group` class, it **inherits from `Command`**. So, a `Group` object is *also* a `Command`.3839A `Group` can also have its own *CLI arguments* and *CLI options*.4041A `Group` can have subcommands of class `Command` or sub groups of class `Group` as well.4243And a `Group` can also have a function that it calls, right before calling the function for any specific subcommand.4445For example:4647{* docs_src/using_click/tutorial002_py39.py hl[5,19,20] *}4849The `cli` variable is converted by Click from a function to a `Group` object. And the original `cli` function is used by that `Group` internally.5051/// tip5253The original `cli` function would be the equivalent of a [Typer Callback](./commands/callback.md){.internal-link target=_blank}.5455///5657Then the `cli` variable, that now is a `Group` object, is used to add sub-commands.5859### How **Typer** works6061Typer doesn't modify the functions. You create an explicit variable of class `typer.Typer` and use it to *register* those functions.6263And then, when you call the app, Typer goes and creates a Click `Command` (or `Group`), and then calls it.6465If your app only has one command, then when you call it, **Typer** creates a single Click `Command` object and calls it.6667But **Typer** creates a Click `Group` object if your app has any of:6869* More than one command.70* A callback.71* Sub-Typer apps (sub commands).7273/// tip7475If you want to learn more about this check the section [One or Multiple Commands](./commands/one-or-multiple.md){.internal-link target=_blank}.7677///7879### Combine Click and **Typer**8081**Typer** uses an internal function `typer.main.get_command()` to generate a Click `Command` (or `Group`) from a `typer.Typer` object.8283You can use it directly, and use the Click object with other Click applications.8485### Including a Click app in a **Typer** app8687For example, you could have a **Typer** app, generate a Click `Group` from it, and then include other Click apps in it:8889{* docs_src/using_click/tutorial003_py39.py hl[15,16,29,31,34] *}9091Notice 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`.9293Then 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`.9495And that way, our **Typer** app will have a subcommand `top` built with Typer, and a subcommand `hello` built with Click.9697Check it:9899<div class="termy">100101```console102$ python main.py --help103104// Notice we have both subcommands, top and hello105Usage: main.py [OPTIONS] COMMAND [ARGS]...106107Options: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.111112Commands:113 hello114 top115116// Call the Typer part117$ python main.py top118119The Typer app is at the top level120121// Call the Click part122$ python main.py hello --name Camila123124Hello Camila!125```126127</div>128129### Including a **Typer** app in a Click app130131The same way, you can do the contrary and include a **Typer** sub app in a bigger Click app:132133{* docs_src/using_click/tutorial004_py39.py hl[31,33,36] *}134135Notice 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.136137Then 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.138139In this case, the original Click app includes the **Typer** app.140141And then we call the *original Click* app, not the Typer app.142143Check it:144145<div class="termy">146147```console148$ python main.py149150// We get our Typer app down there in the sub command151Usage: main.py [OPTIONS] COMMAND [ARGS]...152153Options:154 --help Show this message and exit.155156Commands:157 dropdb158 initdb159 sub A single-command Typer sub app160161162// Use the Click part163$ python main.py initdb164165Initialized the database166167// And use the Typer part168$ python main.py sub169170Typer is now below Click, the Click app is the top level171```172173</div>174175## About Click decorators176177Typer apps don't work with Click decorators directly.178179This is because **Typer** doesn't modify functions to add metadata or to convert them to another object like Click does.180181So, things like `@click.pass_context` won't work.182183Most of the functionality provided by decorators in Click has an alternative way of doing it in **Typer**.184185For example, to access the context, you can just declare a function parameter of type `typer.Context`.186187/// tip188189You can read more about using the context in the docs: [Commands: Using the Context](commands/context.md){.internal-link target=_blank}190191///192193But 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 lines
70Then 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.7172///7374## The power of Click7576<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.7778**Typer** is based on it, so you get all its benefits.7980But you can write simpler code with the benefits of modern Python.8174## Tested7576* 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 line
deleted:docs_src/parameter_types/custom_types/tutorial002_an_py39.py-37 removed
1from typing import Annotated23import click4import typer567class CustomClass:8 def __init__(self, value: str):9 self.value = value1011 def __repr__(self):12 return f"<CustomClass: value={self.value}>"131415class CustomClassParser(click.ParamType):16 name = "CustomClass"1718 def convert(self, value, param, ctx):19 return CustomClass(value * 3)202122app = typer.Typer()232425@app.command()26def 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}")343536if __name__ == "__main__":37 app()
deleted:docs_src/parameter_types/custom_types/tutorial002_py39.py-33 removed
1import click2import typer345class CustomClass:6 def __init__(self, value: str):7 self.value = value89 def __repr__(self):10 return f"<CustomClass: value={self.value}>"111213class CustomClassParser(click.ParamType):14 name = "CustomClass"1516 def convert(self, value, param, ctx):17 return CustomClass(value * 3)181920app = typer.Typer()212223@app.command()24def 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}")303132if __name__ == "__main__":33 app()
deleted:docs_src/using_click/__init__.py
deleted:docs_src/using_click/tutorial001_py39.py-14 removed
1import click234@click.command()5@click.option("--count", default=1, help="Number of greetings.")6@click.option("--name", prompt="Your name", help="The person to greet.")7def 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}!")111213if __name__ == "__main__":14 hello()
deleted:docs_src/using_click/tutorial002_py39.py-24 removed
1import click234@click.group()5def cli():6 pass789@click.command()10def initdb():11 click.echo("Initialized the database")121314@click.command()15def dropdb():16 click.echo("Dropped the database")171819cli.add_command(initdb)20cli.add_command(dropdb)212223if __name__ == "__main__":24 cli()
deleted:docs_src/using_click/tutorial003_py39.py-34 removed
1import click2import typer34app = typer.Typer()567@app.command()8def top():9 """10 Top level command, form Typer11 """12 print("The Typer app is at the top level")131415@app.callback()16def callback():17 """18 Typer app, including Click subapp19 """202122@click.command()23@click.option("--name", prompt="Your name", help="The person to greet.")24def hello(name):25 """Simple program that greets NAME for a total of COUNT times."""26 click.echo(f"Hello {name}!")272829typer_click_object = typer.main.get_command(app)3031typer_click_object.add_command(hello, "hello")3233if __name__ == "__main__":34 typer_click_object()
deleted:docs_src/using_click/tutorial004_py39.py-36 removed
1import click2import typer345@click.group()6def cli():7 pass8910@cli.command()11def initdb():12 click.echo("Initialized the database")131415@cli.command()16def dropdb():17 click.echo("Dropped the database")181920app = typer.Typer()212223@app.command()24def sub():25 """26 A single-command Typer sub app27 """28 print("Typer is now below Click, the Click app is the top level")293031typer_click_object = typer.main.get_command(app)3233cli.add_command(typer_click_object, "sub")3435if __name__ == "__main__":36 cli()
deleted:tests/test_tutorial/test_parameter_types/test_custom_types/test_tutorial002.py-48 removed
1import importlib2import subprocess3import sys4from types import ModuleType56import pytest7from typer.testing import CliRunner89runner = CliRunner()101112@pytest.fixture(13 name="mod",14 params=[15 pytest.param("tutorial002_py39"),16 pytest.param("tutorial002_an_py39"),17 ],18)19def 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 mod232425def test_help(mod: ModuleType):26 result = runner.invoke(mod.app, ["--help"])27 assert result.exit_code == 0282930def 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.output343536def 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.output404142def 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.stdout
deleted:tests/test_tutorial/test_using_click/__init__.py
deleted:tests/test_tutorial/test_using_click/test_tutorial001.py-47 removed
1import subprocess2import sys34from click.testing import CliRunner56from docs_src.using_click import tutorial001_py39 as mod78runner = CliRunner()91011def 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.output192021def 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.stdout262728def test_cli_with_name():29 result = runner.invoke(mod.hello, ["--name", "Camila"])30 assert result.exit_code == 031 assert "Hello Camila!" in result.stdout323334def 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!") == 3394041def 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.stdout
deleted:tests/test_tutorial/test_using_click/test_tutorial002.py-35 removed
1import subprocess2import sys34from click.testing import CliRunner56from docs_src.using_click import tutorial002_py39 as mod78runner = CliRunner()91011def 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.output171819def test_initdb():20 result = runner.invoke(mod.cli, ["initdb"])21 assert "Initialized the database" in result.stdout222324def test_dropdb():25 result = runner.invoke(mod.cli, ["dropdb"])26 assert "Dropped the database" in result.stdout272829def 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.stdout
deleted:tests/test_tutorial/test_using_click/test_tutorial003.py-40 removed
1import subprocess2import sys34from click.testing import CliRunner56from docs_src.using_click import tutorial003_py39 as mod78runner = CliRunner()91011def test_cli():12 result = runner.invoke(mod.typer_click_object, [])13 assert "Missing command" in result.output141516def 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.output222324def test_typer():25 result = runner.invoke(mod.typer_click_object, ["top"])26 assert "The Typer app is at the top level" in result.stdout272829def test_click():30 result = runner.invoke(mod.typer_click_object, ["hello", "--name", "Camila"])31 assert "Hello Camila!" in result.stdout323334def 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.stdout
deleted:tests/test_tutorial/test_using_click/test_tutorial004.py-39 removed
1import subprocess2import sys34from click.testing import CliRunner56from docs_src.using_click import tutorial004_py39 as mod78runner = CliRunner()91011def test_cli():12 result = runner.invoke(mod.cli, [])13 assert "Usage" in result.output14 assert "dropdb" in result.output15 assert "sub" in result.output161718def 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.stdout212223def test_click_initdb():24 result = runner.invoke(mod.cli, ["initdb"])25 assert "Initialized the database" in result.stdout262728def test_click_dropdb():29 result = runner.invoke(mod.cli, ["dropdb"])30 assert "Dropped the database" in result.stdout313233def 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.stdout
modified:mkdocs.yml-1 removed
150 unmodified lines
151 - 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.md
96 unmodified lines
modified:pyproject.toml-2 removed
238 unmodified lines
239"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"]245246[tool.ruff.lint.isort]
18 unmodified lines