✨ Add `typer-slim` package without extras, make `typer` include `typer-slim[default]` and integrate Typer CLI (`typer` command) into Typer (#780)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by GitHub · parent 62988df · Browse files · 75 files·+2241 added−601 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
75 files+2241 added−601 removed
- tests:+1054 added−53 removed
- other:+1187 added−548 removed
Provenance
- Commit
7d5d6bb- Tree
f7c03be- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
62988df
75 files changed+2241 added−601 removed
modified:.github/workflows/publish.yml+12 added-5 removed
6 unmodified lines7891011121314151617181920212223248 unmodified lines3334353637383940413132333435426 unmodified lines
jobs: publish: runs-on: ubuntu-latest strategy: matrix: package: - typer-slim - typer - typer-cli env: dir: ${{ matrix.package == 'typer-slim' && './' || matrix.package == 'typer' && 'typer_package' || matrix.package == 'typer-cli' && 'typer_cli_package' }} permissions: id-token: write steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }}8 unmodified lines # cache-dependency-path: pyproject.toml - name: Install build dependencies run: pip install build - name: Build distribution working-directory: ${{ env.dir }} run: python -m build - name: Publish uses: pypa/gh-action-pypi-publish@v1.8.11 with: password: ${{ secrets.PYPI_API_TOKEN }} - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" packages-dir: ${{ env.dir }}/dist/modified:.github/workflows/test-redistribute.yml+16 added-7 removed
10 unmodified lines111213141516171819202122232425268 unmodified lines35363738394041424344454647483849505152534254555657585947484950516010 unmodified lines
jobs: test-redistribute: runs-on: ubuntu-latest strategy: matrix: package: - typer-slim - typer - typer-cli env: dir: ${{ matrix.package == 'typer-slim' && './' || matrix.package == 'typer' && 'typer_package' || matrix.package == 'typer-cli' && 'typer_cli_package' }} steps: - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }}8 unmodified lines # cache-dependency-path: pyproject.toml - name: Install build dependencies run: pip install build - name: Build source distribution working-directory: ${{ env.dir }} run: python -m build --sdist - name: Decompress source distribution working-directory: ${{ env.dir }} run: | cd dist tar xvf typer*.tar.gz - name: Install test dependencies if: ${{ matrix.package == 'typer-slim' }} run: | cd dist/typer-*/ cd dist/typer*/ pip install -r requirements-tests.txt - name: Run source distribution tests if: ${{ matrix.package == 'typer-slim' }} run: | cd dist/typer-*/ cd dist/typer*/ bash scripts/test.sh - name: Build wheel distribution working-directory: ${{ env.dir }} run: | cd dist pip wheel --no-deps typer-*.tar.gz - name: Dump GitHub context env: GITHUB_CONTEXT: ${{ toJson(github) }} run: echo "$GITHUB_CONTEXT" pip wheel --no-deps typer*.tar.gzmodified:docs/tutorial/options/callback-and-context.md+2 added-2 removed
52 unmodified lines53 There's something to be aware of with callbacks and completion that requires some small special handling.54 55 But first let's just use completion in your shell (Bash, Zsh, Fish, or PowerShell).56 57-After installing completion (for your own Python package or for **Typer CLI**), when you use your CLI program and start adding a *CLI option* with `--` an then hit <kbd>TAB</kbd>, your shell will show you the available *CLI options* (the same for *CLI arguments*, etc).57+After installing completion (for your own Python package), when you use your CLI program and start adding a *CLI option* with `--` an then hit <kbd>TAB</kbd>, your shell will show you the available *CLI options* (the same for *CLI arguments*, etc).58 59-To check it quickly without creating a new Python package, install [Typer CLI](../../typer-cli.md){.internal-link target=_blank} and use it with the previous script:59+To check it quickly with the previous script use the `typer` command:60 61 <div class="termy">62 63 ```console198 unmodified linesmodified:docs/tutorial/first-steps.md+5 added-5 removed
450 unmodified lines451 And we'll use ***CLI option*** to refer to those *CLI parameters* that depend on a name that starts with `--` (like `--lastname`). That are **optional** by default.452 453 We will use ***CLI parameter*** to refer to both, *CLI arguments* and *CLI options*.454 455-## **Typer CLI**455+## The `typer` Command456 457-Now that you know the basics of **Typer**, you might want to install and use [Typer CLI](../typer-cli.md){.internal-link target=_blank}.457+When you install `typer`, by default it adds a `typer` command to your shell.458 459-**Typer CLI** is a tool to run your **Typer** scripts giving you ✨ auto completion ✨ in your terminal.459+This `typer` command allows you to run your scripts with ✨ auto completion ✨ in your terminal.460 461 As an alternative to running with Python:462 463 <div class="termy">5 unmodified lines469 ```470 471 </div>472 473-You can run with **Typer CLI**:473+You can run with the `typer` command:474 475 <div class="termy">476 477 ```console8 unmodified lines486 487 So you can use it to have auto completion for your own scripts as you continue with the tutorial.488 489 !!! tip490- Your CLI application built with **Typer** won't need [Typer CLI](../typer-cli.md){.internal-link target=_blank} to have auto completion once you create a Python package.490+ Your CLI application built with **Typer** won't need the `typer` command to have auto completion once you create a Python package.491 492 But for short scripts and for learning, before creating a Python package, it might be useful.modified:docs/tutorial/index.md+17 added-6 removed
59 unmodified lines60616263646465666766676871697073717273747578767778798081828384858687888959 unmodified lines---
## Install **Typer**
The first step is to install **Typer**.The first step is to install **Typer**:
For the tutorial, you might want to install it with all the optional dependencies and features:
<div class="termy">
```console$ pip install "typer[all]"$ pip install typer---> 100%Successfully installed typer click shellingham richSuccessfully installed typer click shellingham rich typer-cli```
</div>
...that also includes `rich` and `shellingham`.By default, `typer` comes with `rich`, `shellingham`, and `typer-cli`.
!!! note If you are an advanced user and want to opt out of these default extra dependencies, you can instead install `typer-slim`.
```bash pip install typer ```
...is the equivalent of:
```bash pip install "typer-slim[standard]" ```modified:docs/tutorial/options-autocompletion.md+4 added-4 removed
1-As you have seen, apps built with **Typer** have completion in your shell that works when you create a Python package or using **Typer CLI**.1+As you have seen, apps built with **Typer** have completion in your shell that works when you create a Python package or using the `typer` command.2 3 It normally completes *CLI options*, *CLI arguments*, and subcommands (that you will learn about later).4 5 But you can also provide auto completion for the **values** of *CLI options* and *CLI arguments*. We will learn about that here.1 unmodified line7 ## Review completion8 9 Before checking how to provide custom completions, let's check again how it works.10 11-After installing completion (for your own Python package or for **Typer CLI**), when you use your CLI program and start adding a *CLI option* with `--` an then hit <kbd>TAB</kbd>, your shell will show you the available *CLI options* (the same for *CLI arguments*, etc).11+After installing completion for your own Python package (or using the `typer` command), when you use your CLI program and start adding a *CLI option* with `--` an then hit <kbd>TAB</kbd>, your shell will show you the available *CLI options* (the same for *CLI arguments*, etc).12 13-To check it quickly without creating a new Python package, install [Typer CLI](../typer-cli.md){.internal-link target=_blank}.13+To check it quickly without creating a new Python package, use the `typer` command.14 15 Then let's create small example program:16 17 === "Python 3.7+"10 unmodified lines28 ```Python29 {!> ../docs_src/options_autocompletion/tutorial001.py!}30 ```31 32-And let's try it with **Typer CLI** to get completion:32+And let's try it with the `typer` command to get completion:33 34 <div class="termy">35 36 ```console429 unmodified linesmodified:docs/tutorial/package.md+6 added-5 removed
1 When you create a CLI program with **Typer** you probably want to create your own Python package.2 3 That's what allows your users to install it and have it as an independent program that they can use in their terminal.4 5-And that's also required for shell auto completion to work (unless you use your program through [Typer CLI](../typer-cli.md){.internal-link target=_blank}).5+And that's also required for shell auto completion to work (unless you use your program through `typer` command).6 7 Nowadays, there are several ways and tools to create Python packages (what you install with `pip install something`).8 9 You might even have your favorite already.690 unmodified lines700 ```701 702 </div>703 704-## Generate docs with **Typer CLI** (optional)704+## Generate docs705 706-You can install and use [Typer CLI](../typer-cli.md){.internal-link target=_blank} to generate docs for your package.706+You can use the `typer` command to generate docs for your package that you can put in your `README.md`:707 708-After installing it, you can use it to generate a new `README.md`:709-708 <div class="termy">709 710 ```console711 $ typer rick_portal_gun.main utils docs --output README.md --name rick-portal-gun6 unmodified lines718 You just have to pass it the module to import (`rick_portal_gun.main`) and it will detect the `typer.Typer` app automatically.719 720 By specifying the `--name` of the program it will be able to use it while generating the docs.721 722+!!! tip723+ If you installed `typer-slim` and don't have the `typer` command, you can use `python -m typer` instead.724+725 ### Publish a new version with the docs726 727 Now you can publish a new version with the updated docs.728 73 unmodified linesmodified:docs/tutorial/printing.md+1 added-21 removed
16 unmodified lines17 </div>18 19 ## Use Rich20 21-You can also display beautiful and more complex information using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>.21+You can also display beautiful and more complex information using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>. It comes by default when you install `typer`.22 23-### Install Rich24-25-First, you need to install it:26-27-<div class="termy">28-29-```console30-// Rich comes with typer[all]31-$ pip install "typer[all]"32----> 100%33-Successfully installed typer rich34-35-// Alternatively, you can install Rich independently36-$ pip install rich37----> 100%38-Successfully installed rich39-```40-41-</div>42-23 ### Use Rich `print`24 25 For the simplest cases, you can just import `print` from `rich` and use it instead of the standard `print`:26 243 unmodified linesadded:docs/tutorial/typer-command.md+377 added
1+# `typer` command2+3+The `typer` command provides ✨ completion ✨ in the Terminal for your own small scripts. Even if they don't use Typer internally. Of course, it works better if you use **Typer** in your script.4+5+It's probably most useful if you have a small custom Python script using **Typer** (maybe as part of some project), for some small tasks, and it's not complex/important enough to create a whole installable Python package for it (something to be installed with `pip`).6+7+In that case, you can run your program with the `typer` command in your Terminal, and it will provide completion for your script.8+9+The `typer` command also has functionality to generate Markdown documentation for your own **Typer** programs 📝.10+11+## Install12+13+When you install **Typer** with:14+15+```bash16+pip install typer17+```18+19+...it includes the `typer` command.20+21+If you don't want to have the `typer` command, you can install instead:22+23+```bash24+pip install typer-slim25+```26+27+You can still use it by calling the Typer library as a module with:28+29+```bash30+python -m typer31+```32+33+## Install completion34+35+You can then install completion for the `typer` command with:36+37+<div class="termy">38+39+```console40+$ typer --install-completion41+42+bash completion installed in /home/user/.bashrc.43+Completion will take effect once you restart the terminal.44+```45+46+</div>47+48+### Sample script49+50+Let's say you have a script that uses **Typer** in `my_custom_script.py`:51+52+```Python53+from typing import Optional54+55+import typer56+57+app = typer.Typer()58+59+60+@app.command()61+def hello(name: Optional[str] = None):62+ if name:63+ typer.echo(f"Hello {name}")64+ else:65+ typer.echo("Hello World!")66+67+68+@app.command()69+def bye(name: Optional[str] = None):70+ if name:71+ typer.echo(f"Bye {name}")72+ else:73+ typer.echo("Goodbye!")74+75+76+if __name__ == "__main__":77+ app()78+```79+80+For it to work, you would also install **Typer**:81+82+<div class="termy">83+84+```console85+$ python -m pip install typer86+---> 100%87+Successfully installed typer88+```89+90+</div>91+92+### Run with Python93+94+Then you could run your script with normal Python:95+96+<div class="termy">97+98+```console99+$ python my_custom_script.py hello100+101+Hello World!102+103+$ python my_custom_script.py hello --name Camila104+105+Hello Camila!106+107+$ python my_custom_script.py bye --name Camila108+109+Bye Camila110+```111+112+</div>113+114+There's nothing wrong with using Python directly to run it. And, in fact, if some other code or program uses your script, that would probably be the best way to do it.115+116+⛔️ But in your terminal, you won't get completion when hitting <kbd>TAB</kbd> for any of the subcommands or options, like `hello`, `bye`, and `--name`.117+118+### Run with the `typer` command.119+120+You can also run the same script with the `typer` command:121+122+<div class="termy">123+124+```console125+$ typer my_custom_script.py run hello126+127+Hello World!128+129+$ typer my_custom_script.py run hello --name Camila130+131+Hello Camila!132+133+$ typer my_custom_script.py run bye --name Camila134+135+Bye Camila136+```137+138+</div>139+140+* Instead of using `python` directly you use the `typer` command.141+* After the name of the file, add the subcommand `run`.142+143+✔️ If you installed completion for the `typer` command as described above, when you hit <kbd>TAB</kbd> you will have ✨ completion for everything ✨, including all the subcommands and options of your script, like `hello`, `bye`, and `--name` 🚀.144+145+## If main146+147+Because the `typer` command won't use the block with:148+149+```Python150+if __name__ == "__main__":151+ app()152+```153+154+...you can also remove it if you are calling that script only with the `typer` command.155+156+## Run other files157+158+The `typer` command can run any script with **Typer**, but the script doesn't even have to use **Typer** at all.159+160+You could even run a file with a function that could be used with `typer.run()`, even if the script doesn't use `typer.run()` or anything else.161+162+For example, a file `main.py` like this will still work:163+164+```Python165+def main(name: str = "World"):166+ """167+ Say hi to someone, by default to the World.168+ """169+ print(f"Hello {name}")170+```171+172+Then you can call it with:173+174+<div class="termy">175+176+```console177+$ typer main.py run --help178+Usage: typer run [OPTIONS]179+180+ Say hi to someone, by default to the World.181+182+Options:183+ --name TEXT184+ --help Show this message and exit.185+186+$ typer main.py run --name Camila187+188+Hello Camila189+```190+191+</div>192+193+And it will also have completion for things like the `--name` *CLI Option*.194+195+## Run a package or module196+197+Instead of a file path you can pass a module (possibly in a package) to import.198+199+For example:200+201+<div class="termy">202+203+```console204+$ typer my_package.main run --help205+Usage: typer run [OPTIONS]206+207+Options:208+ --name TEXT209+ --help Show this message and exit.210+211+$ typer my_package.main run --name Camila212+213+Hello Camila214+```215+216+</div>217+218+## Options219+220+You can specify one of the following **CLI options**:221+222+* `--app`: the name of the variable with a `Typer()` object to run as the main app.223+* `--func`: the name of the variable with a function that would be used with `typer.run()`.224+225+### Defaults226+227+When your run a script with the `typer` command it will use the app from the following priority:228+229+* An app object from the `--app` *CLI Option*.230+* A function to convert to a **Typer** app from `--func` *CLI Option* (like when using `typer.run()`).231+* A **Typer** app in a variable with a name of `app`, `cli`, or `main`.232+* The first **Typer** app available in the file, with any name.233+* A function in a variable with a name of `main`, `cli`, or `app`.234+* The first function in the file, with any name.235+236+## Generate docs237+238+You can also use the `typer` command to generate Markdown documentation for your **Typer** application.239+240+### Sample script with docs241+242+For example, you could have a script like:243+244+```Python245+{!../docs_src/commands/help/tutorial001.py!}246+```247+248+### Generate docs with the `typer` command249+250+Then you could generate docs for it with the `typer` command.251+252+You can use the subcommand `utils`.253+254+And then the subcommand `docs`.255+256+<div class="termy">257+258+```console259+$ typer some_script.py utils docs260+```261+262+</div>263+264+!!! tip265+ If you installed only `typer-slim` and you don't have the `typer` command, you can still generate docs with:266+267+ ```console268+ $ python -m typer some_script.py utils docs269+ ```270+271+**Options**:272+273+* `--name TEXT`: The name of the CLI program to use in docs.274+* `--output FILE`: An output file to write docs to, like README.md.275+276+For example:277+278+<div class="termy">279+280+```console281+$ typer my_package.main utils docs --name awesome-cli --output README.md282+283+Docs saved to: README.md284+```285+286+</div>287+288+### Sample docs output289+290+For example, for the previous script, the generated docs would look like:291+292+---293+294+## `awesome-cli`295+296+Awesome CLI user manager.297+298+**Usage**:299+300+```console301+$ awesome-cli [OPTIONS] COMMAND [ARGS]...302+```303+304+**Options**:305+306+* `--install-completion`: Install completion for the current shell.307+* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.308+* `--help`: Show this message and exit.309+310+**Commands**:311+312+* `create`: Create a new user with USERNAME.313+* `delete`: Delete a user with USERNAME.314+* `delete-all`: Delete ALL users in the database.315+* `init`: Initialize the users database.316+317+## `awesome-cli create`318+319+Create a new user with USERNAME.320+321+**Usage**:322+323+```console324+$ awesome-cli create [OPTIONS] USERNAME325+```326+327+**Options**:328+329+* `--help`: Show this message and exit.330+331+## `awesome-cli delete`332+333+Delete a user with USERNAME.334+335+If --force is not used, will ask for confirmation.336+337+**Usage**:338+339+```console340+$ awesome-cli delete [OPTIONS] USERNAME341+```342+343+**Options**:344+345+* `--force / --no-force`: Force deletion without confirmation. [required]346+* `--help`: Show this message and exit.347+348+## `awesome-cli delete-all`349+350+Delete ALL users in the database.351+352+If --force is not used, will ask for confirmation.353+354+**Usage**:355+356+```console357+$ awesome-cli delete-all [OPTIONS]358+```359+360+**Options**:361+362+* `--force / --no-force`: Force deletion without confirmation. [required]363+* `--help`: Show this message and exit.364+365+## `awesome-cli init`366+367+Initialize the users database.368+369+**Usage**:370+371+```console372+$ awesome-cli init [OPTIONS]373+```374+375+**Options**:376+377+* `--help`: Show this message and exit.modified:docs/features.md+4 added-4 removed
47 unmodified lines48 * Automatic command and subcommand structure handling (you will see more about subcommands in the Tutorial - User Guide).49 * Automatic completion for the CLI app in all operating systems, in all the shells (Bash, Zsh, Fish, PowerShell), so that the final user of your app can just hit <kbd>TAB</kbd> and get the available options or subcommands. *50 51 !!! note "* Auto completion"52- Auto completion works when you create a package (installable with `pip`). Or when using [Typer CLI](typer-cli.md){.internal-link target=_blank}.52+ Auto completion works when you create a package (installable with `pip`). Or when using the `typer` command.53 54- If you also add `shellingham` as a dependency, **Typer** will use it to auto-detect the current shell when installing completion.54+ **Typer** uses `shellingham` to auto-detect the current shell when installing completion. If you don't want to include `shellingham`, install `typer-slim`.55 56 **Typer** will automatically create 2 *CLI options*:57 58 * `--install-completion`: Install completion for the current shell.59 * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.60 61- If you didn't add `shellingham` those *CLI options* take a value with the name of the shell to install completion for, e.g.:61+ If you didn't add `shellingham` (if you installed `pip install typer-slim`) those *CLI options* take a value with the name of the shell to install completion for, e.g.:62 63 * `--install-completion bash`.64 * `--show-completion powershell`.65 7 unmodified lines73 ## The power of Click74 75 <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.76 77-**Typer** is based on it, so you get all its benefits, plug-ins, robustness, etc.77+**Typer** is based on it, so you get all its benefits.78 79 But you can write simpler code with the benefits of modern Python.80 81 ## Tested4 unmodified linesmodified:docs/index.md+93 added-24 removed
26 unmodified lines27 ---28 29 Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.30 31+It's also a command line tool to run scripts, automatically converting them to CLI applications.32+33 The key features are:34 35 * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.36 * **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.37 * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.38 * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.39 * **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.40+* **Run scripts**: Typer includes a `typer` command that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.41 42 ## FastAPI of CLIs43 41-<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>44+**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.45 43-**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.44-45-And it's intended to be the FastAPI of CLIs.46-47-## Requirements48-49-**Typer** stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.50-46 ## Installation47 48 <div class="termy">49 50 ```console56-$ pip install "typer[all]"51+$ pip install typer52 ---> 100%58-Successfully installed typer53+Successfully installed typer rich shellingham54 ```55 56 </div>57 63-**Note**: that will include <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>. Rich is the recommended library to *display* information on the terminal, it is optional, but when installed, it's deeply integrated into **Typer** to display beautiful output.64-58 ## Example59 60 ### The absolute minimum61 62 * Create a file `main.py` with:63 64 ```Python65+def main(name: str):66+ print(f"Hello {name}")67+```68+69+This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.70+71+### Run it72+73+Run your application with the `typer` command:74+75+<div class="termy">76+77+```console78+// Run your application79+$ typer main.py run80+81+// You get a nice error, you are missing NAME82+Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME83+Try 'typer [PATH_OR_MODULE] run --help' for help.84+╭─ Error ───────────────────────────────────────────╮85+│ Missing argument 'NAME'. │86+╰───────────────────────────────────────────────────╯87+88+89+// You get a --help for free90+$ typer main.py run --help91+92+Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME93+94+Run the provided Typer app.95+96+╭─ Arguments ───────────────────────────────────────╮97+│ * name TEXT [default: None] [required] |98+╰───────────────────────────────────────────────────╯99+╭─ Options ─────────────────────────────────────────╮100+│ --help Show this message and exit. │101+╰───────────────────────────────────────────────────╯102+103+// Now pass the NAME argument104+$ typer main.py run Camila105+106+Hello Camila107+108+// It works! 🎉109+```110+111+</div>112+113+This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.114+115+**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.116+117+## Use Typer in your code118+119+Now let's start using Typer in your own code, update `main.py` with:120+121+```Python122 import typer123 124 125 def main(name: str):3 unmodified lines129 if __name__ == "__main__":130 typer.run(main)131 ```132 83-### Run it133+Now you could run it with Python directly:134 85-Run your application:86-135 <div class="termy">136 137 ```console138 // Run your application28 unmodified lines167 ```168 169 </div>170 123-**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.171+**Note**: you can also call this same script with the `typer` command, but you don't need to.172 173 ## Example upgrade174 175 This was the simplest example possible.164 unmodified lines340 And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.341 342 **You get**: great editor support, including **completion** and **type checks** everywhere.343 296-**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.344+**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command.345 346 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.347 300-## Optional Dependencies348+## Dependencies349 302-Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.350+**Typer** stands on the shoulders of a giant. Its only internal required dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.351 304-But you can also install extras:352+By default it also comes with extra standard dependencies:353 306-* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: and Typer will show nicely formatted errors automatically.307-* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.354+* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.355+* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.356 * With `shellingham` you can just use `--install-completion`.357 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.358+* `typer-cli`: adds the `typer` command to your shell:359+ * Quickly run scripts (that don't have to use Typer) with shell completion.360+ * Generate docs for your Typer applications.361 311-You can install `typer` with `rich` and `shellingham` with `pip install typer[all]`.362+### `typer-slim`363 364+If you don't want the extra dependencies, install `typer-slim` instead.365+366+When you install with:367+368+```bash369+pip install typer370+```371+372+...it's the equivalent of:373+374+```bash375+pip install "typer-slim[standard]"376+```377+378+The `standard` extra dependencies are `rich`, `shellingham`, `typer-cli`.379+380+**Note**: even if you don't install `typer-cli` you can still use it's functionality by calling `typer` as a module, e.g. `python -m typer`.381+382 ## License383 384 This project is licensed under the terms of the MIT license.deleted:docs/typer-cli.md-433 removed
1-# Typer CLI2-3-<p align="center">4- <em>Run <strong>Typer</strong> scripts with completion, without having to create a package, using <strong>Typer CLI</strong>.</em>5-</p>6-<p align="center">7-<a href="https://travis-ci.com/tiangolo/typer-cli" target="_blank">8- <img src="https://travis-ci.com/tiangolo/typer-cli.svg?branch=master" alt="Build Status">9-</a>10-<a href="https://codecov.io/gh/tiangolo/typer-cli" target="_blank">11- <img src="https://img.shields.io/codecov/c/github/tiangolo/typer-cli" alt="Coverage">12-</a>13-<a href="https://pypi.org/project/typer-cli" target="_blank">14- <img src="https://badge.fury.io/py/typer-cli.svg" alt="Package version">15-</a>16-</p>17-18-There is an optional utility tool called **Typer CLI**, additional to **Typer** itself.19-20-It's main feature is to provide ✨ completion ✨ in the Terminal for your own small programs built with **Typer**.21-22-...without you having to create a complete installable Python package.23-24-It's probably most useful if you have a small custom Python script using **Typer** (maybe as part of some project), for some small tasks, and it's not complex/important enough to create a whole installable Python package for it (something to be installed with `pip`).25-26-In that case, you can install **Typer CLI**, and run your program with the `typer` command in your Terminal, and it will provide completion for your script.27-28-You can also use **Typer CLI** to generate Markdown documentation for your own **Typer** programs 📝.29-30----31-32-**Documentation**: <a href="https://typer.tiangolo.com/typer-cli/" target="_blank">https://typer.tiangolo.com/typer-cli/</a>33-34-**Source Code for Typer CLI**: <a href="https://github.com/tiangolo/typer-cli" target="_blank">https://github.com/tiangolo/typer-cli</a>35-36----37-38-## **Typer** or **Typer CLI**39-40-**Typer** is a library for building CLIs (Command Line Interface applications).41-42-You use **Typer** in your Python scripts. Like in:43-44-```Python45-import typer46-47-48-def main():49- typer.echo("Hello World")50-51-52-if __name__ == "__main__":53- typer.run(main)54-```55-56-**Typer CLI** is a command line application to run simple programs created with **Typer**, with completion in your terminal 🚀.57-58-You use **Typer CLI** in your terminal, to run your scripts (as an alternative to calling `python` directly). Like in:59-60-<div class="termy">61-62-```console63-$ typer my_script.py run64-65-Hello World66-```67-68-</div>69-70-But you never import anything from **Typer CLI** in your own scripts.71-72-## Usage73-74-### Install75-76-Install **Typer CLI**:77-78-<div class="termy">79-80-```console81-$ python -m pip install typer-cli82----> 100%83-Successfully installed typer-cli84-```85-86-</div>87-88-That creates a `typer` command you can call in your terminal, much like `python`, `git`, or `echo`.89-90-You can then install completion for it:91-92-<div class="termy">93-94-```console95-$ typer --install-completion96-97-zsh completion installed in /home/user/.bashrc.98-Completion will take effect once you restart the terminal.99-```100-101-</div>102-103-### Sample script104-105-Let's say you have a script that uses **Typer** in `my_custom_script.py`:106-107-```Python108-from typing import Optional109-110-import typer111-112-app = typer.Typer()113-114-115-@app.command()116-def hello(name: Optional[str] = None):117- if name:118- typer.echo(f"Hello {name}")119- else:120- typer.echo("Hello World!")121-122-123-@app.command()124-def bye(name: Optional[str] = None):125- if name:126- typer.echo(f"Bye {name}")127- else:128- typer.echo("Goodbye!")129-130-131-if __name__ == "__main__":132- app()133-```134-135-For it to work, you would also install **Typer**:136-137-<div class="termy">138-139-```console140-$ python -m pip install typer141----> 100%142-Successfully installed typer143-```144-145-</div>146-147-### Run with Python148-149-Then you could run your script with normal Python:150-151-<div class="termy">152-153-```console154-$ python my_custom_script.py hello155-156-Hello World!157-158-$ python my_custom_script.py hello --name Camila159-160-Hello Camila!161-162-$ python my_custom_script.py bye --name Camila163-164-Bye Camila165-```166-167-</div>168-169-There's nothing wrong with using Python directly to run it. And, in fact, if some other code or program uses your script, that would probably be the best way to do it.170-171-⛔️ But in your terminal, you won't get completion when hitting <kbd>TAB</kbd> for any of the subcommands or options, like `hello`, `bye`, and `--name`.172-173-### Run with **Typer CLI**174-175-Here's where **Typer CLI** is useful.176-177-You can also run the same script with the `typer` command you get after installing `typer-cli`:178-179-<div class="termy">180-181-```console182-$ typer my_custom_script.py run hello183-184-Hello World!185-186-$ typer my_custom_script.py run hello --name Camila187-188-Hello Camila!189-190-$ typer my_custom_script.py run bye --name Camila191-192-Bye Camila193-```194-195-</div>196-197-* Instead of using `python` directly you use the `typer` command.198-* After the name of the file, add the subcommand `run`.199-200-✔️ If you installed completion for **Typer CLI** (for the `typer` command) as described above, when you hit <kbd>TAB</kbd> you will have ✨ completion for everything ✨, including all the subcommands and options of your script, like `hello`, `bye`, and `--name` 🚀.201-202-## If main203-204-Because **Typer CLI** won't use the block with:205-206-```Python207-if __name__ == "__main__":208- app()209-```210-211-...you can also remove it if you are calling that script only with **Typer CLI** (using the `typer` command).212-213-## Run other files214-215-**Typer CLI** can run any script with **Typer**, but the script doesn't even have to use **Typer** at all.216-217-**Typer CLI** could even run a file with a function that could be used with `typer.run()`, even if the script doesn't use `typer.run()` or anything else.218-219-For example, a file `main.py` like this will still work:220-221-```Python222-def main(name: str = "World"):223- """224- Say hi to someone, by default to the World.225- """226- print(f"Hello {name}")227-```228-229-Then you can call it with:230-231-<div class="termy">232-233-```console234-$ typer main.py run --help235-Usage: typer run [OPTIONS]236-237- Say hi to someone, by default to the World.238-239-Options:240- --name TEXT241- --help Show this message and exit.242-243-$ typer main.py run --name Camila244-245-Hello Camila246-```247-248-</div>249-250-And it will also have completion for things like the `--name` *CLI Option*.251-252-## Run a package or module253-254-Instead of a file path you can pass a module (possibly in a package) to import.255-256-For example:257-258-<div class="termy">259-260-```console261-$ typer my_package.main run --help262-Usage: typer run [OPTIONS]263-264-Options:265- --name TEXT266- --help Show this message and exit.267-268-$ typer my_package.main run --name Camila269-270-Hello Camila271-```272-273-</div>274-275-## Options276-277-You can specify one of the following **CLI options**:278-279-* `--app`: the name of the variable with a `Typer()` object to run as the main app.280-* `--func`: the name of the variable with a function that would be used with `typer.run()`.281-282-### Defaults283-284-When your run a script with the **Typer CLI** (the `typer` command) it will use the app from the following priority:285-286-* An app object from the `--app` *CLI Option*.287-* A function to convert to a **Typer** app from `--func` *CLI Option* (like when using `typer.run()`).288-* A **Typer** app in a variable with a name of `app`, `cli`, or `main`.289-* The first **Typer** app available in the file, with any name.290-* A function in a variable with a name of `main`, `cli`, or `app`.291-* The first function in the file, with any name.292-293-## Generate docs294-295-**Typer CLI** can also generate Markdown documentation for your **Typer** application.296-297-### Sample script with docs298-299-For example, you could have a script like:300-301-```Python302-{!../docs_src/commands/help/tutorial001.py!}303-```304-305-### Generate docs with Typer CLI306-307-Then you could generate docs for it with **Typer CLI**.308-309-You can use the subcommand `utils`.310-311-And then the subcommand `docs`.312-313-<div class="termy">314-315-```console316-$ typer some_script.py utils docs317-```318-319-</div>320-321-**Options**:322-323-* `--name TEXT`: The name of the CLI program to use in docs.324-* `--output FILE`: An output file to write docs to, like README.md.325-326-For example:327-328-<div class="termy">329-330-```console331-$ typer my_package.main utils docs --name awesome-cli --output README.md332-333-Docs saved to: README.md334-```335-336-</div>337-338-### Sample docs output339-340-For example, for the previous script, the generated docs would look like:341-342----343-344-## `awesome-cli`345-346-Awesome CLI user manager.347-348-**Usage**:349-350-```console351-$ awesome-cli [OPTIONS] COMMAND [ARGS]...352-```353-354-**Options**:355-356-* `--install-completion`: Install completion for the current shell.357-* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.358-* `--help`: Show this message and exit.359-360-**Commands**:361-362-* `create`: Create a new user with USERNAME.363-* `delete`: Delete a user with USERNAME.364-* `delete-all`: Delete ALL users in the database.365-* `init`: Initialize the users database.366-367-## `awesome-cli create`368-369-Create a new user with USERNAME.370-371-**Usage**:372-373-```console374-$ awesome-cli create [OPTIONS] USERNAME375-```376-377-**Options**:378-379-* `--help`: Show this message and exit.380-381-## `awesome-cli delete`382-383-Delete a user with USERNAME.384-385-If --force is not used, will ask for confirmation.386-387-**Usage**:388-389-```console390-$ awesome-cli delete [OPTIONS] USERNAME391-```392-393-**Options**:394-395-* `--force / --no-force`: Force deletion without confirmation. [required]396-* `--help`: Show this message and exit.397-398-## `awesome-cli delete-all`399-400-Delete ALL users in the database.401-402-If --force is not used, will ask for confirmation.403-404-**Usage**:405-406-```console407-$ awesome-cli delete-all [OPTIONS]408-```409-410-**Options**:411-412-* `--force / --no-force`: Force deletion without confirmation. [required]413-* `--help`: Show this message and exit.414-415-## `awesome-cli init`416-417-Initialize the users database.418-419-**Usage**:420-421-```console422-$ awesome-cli init [OPTIONS]423-```424-425-**Options**:426-427-* `--help`: Show this message and exit.428-429----430-431-## License432-433-**Typer CLI**, the same as **Typer**, is licensed under the terms of the MIT license.added:tests/assets/cli/__init__.py
added:tests/assets/cli/app_other_name.py+8 added
1+import typer2+3+application = typer.Typer()4+5+6+@application.command()7+def callback(name: str = "World"):8+ typer.echo(f"Hello {name}")added:tests/assets/cli/empty_script.py
added:tests/assets/cli/func_other_name.py+2 added
1+def some_function(name: str = "World"):2+ print(f"Hello {name}")added:tests/assets/cli/multi_app_cli.py+22 added
1+import typer2+3+sub_app = typer.Typer()4+5+6+@sub_app.command()7+def hello():8+ typer.echo("sub hello")9+10+11+@sub_app.command()12+def bye():13+ typer.echo("sub bye")14+15+16+cli = typer.Typer()17+cli.add_typer(sub_app, name="sub")18+19+20+@cli.command()21+def top():22+ typer.echo("top")added:tests/assets/cli/multi_app.py+40 added
1+import typer2+3+sub_app = typer.Typer()4+5+variable = "Some text"6+7+8+@sub_app.command()9+def hello(name: str = "World", age: int = typer.Option(0, help="The age of the user")):10+ """11+ Say Hello12+ """13+ typer.echo(f"Hello {name}")14+15+16+@sub_app.command()17+def hi(user: str = typer.Argument("World", help="The name of the user to greet")):18+ """19+ Say Hi20+ """21+22+23+@sub_app.command()24+def bye():25+ """26+ Say bye27+ """28+ typer.echo("sub bye")29+30+31+app = typer.Typer(help="Demo App", epilog="The end")32+app.add_typer(sub_app, name="sub")33+34+35+@app.command()36+def top():37+ """38+ Top command39+ """40+ typer.echo("top")added:tests/assets/cli/multi_func.py+12 added
1+message = "Stuff"2+3+4+def say_stuff():5+ print(message)6+7+8+def main(name: str = "World"):9+ """10+ Say hi to someone, by default to the World.11+ """12+ print(f"Hello {name}")added:tests/assets/cli/multiapp-docs.md+102 added
1+# `multiapp`2+3+Demo App4+5+**Usage**:6+7+```console8+$ multiapp [OPTIONS] COMMAND [ARGS]...9+```10+11+**Options**:12+13+* `--install-completion`: Install completion for the current shell.14+* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.15+* `--help`: Show this message and exit.16+17+The end18+19+**Commands**:20+21+* `sub`22+* `top`: Top command23+24+## `multiapp sub`25+26+**Usage**:27+28+```console29+$ multiapp sub [OPTIONS] COMMAND [ARGS]...30+```31+32+**Options**:33+34+* `--help`: Show this message and exit.35+36+**Commands**:37+38+* `bye`: Say bye39+* `hello`: Say Hello40+* `hi`: Say Hi41+42+### `multiapp sub bye`43+44+Say bye45+46+**Usage**:47+48+```console49+$ multiapp sub bye [OPTIONS]50+```51+52+**Options**:53+54+* `--help`: Show this message and exit.55+56+### `multiapp sub hello`57+58+Say Hello59+60+**Usage**:61+62+```console63+$ multiapp sub hello [OPTIONS]64+```65+66+**Options**:67+68+* `--name TEXT`: [default: World]69+* `--age INTEGER`: The age of the user [default: 0]70+* `--help`: Show this message and exit.71+72+### `multiapp sub hi`73+74+Say Hi75+76+**Usage**:77+78+```console79+$ multiapp sub hi [OPTIONS] [USER]80+```81+82+**Arguments**:83+84+* `[USER]`: The name of the user to greet [default: World]85+86+**Options**:87+88+* `--help`: Show this message and exit.89+90+## `multiapp top`91+92+Top command93+94+**Usage**:95+96+```console97+$ multiapp top [OPTIONS]98+```99+100+**Options**:101+102+* `--help`: Show this message and exit.added:tests/assets/cli/not_python.txt+1 added
1+This is not Pythonadded:tests/assets/cli/sample.py+25 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def hello(name: str = "World", formal: bool = False):8+ """9+ Say hi10+ """11+ if formal:12+ typer.echo(f"Good morning Ms. {name}")13+ else:14+ typer.echo(f"Hello {name}!")15+16+17+@app.command()18+def bye(friend: bool = False):19+ """20+ Say bye21+ """22+ if friend:23+ typer.echo("Goodbye my friend")24+ else:25+ typer.echo("Goodbye")added:tests/test_cli/__init__.py
added:tests/test_cli/test_app_other_name.py+41 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/app_other_name.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "--name" in result.stdout22+23+24+def test_script():25+ result = subprocess.run(26+ [27+ sys.executable,28+ "-m",29+ "coverage",30+ "run",31+ "-m",32+ "typer",33+ "tests/assets/cli/app_other_name.py",34+ "run",35+ "--name",36+ "Camila",37+ ],38+ capture_output=True,39+ encoding="utf-8",40+ )41+ assert "Hello Camila" in result.stdoutadded:tests/test_cli/test_completion_run.py+19 added
1+import os2+import subprocess3+import sys4+5+6+def test_script_completion_run():7+ result = subprocess.run(8+ [sys.executable, "-m", "coverage", "run", "-m", "typer"],9+ capture_output=True,10+ encoding="utf-8",11+ env={12+ **os.environ,13+ "___MAIN__.PY_COMPLETE": "complete_bash",14+ "_PYTHON _M TYPER_COMPLETE": "complete_bash",15+ "COMP_WORDS": "typer tests/assets/cli/sample.py",16+ "COMP_CWORD": "2",17+ },18+ )19+ assert "run" in result.stdoutadded:tests/test_cli/test_doc.py+112 added
1+import subprocess2+import sys3+from pathlib import Path4+5+6+def test_doc():7+ result = subprocess.run(8+ [9+ sys.executable,10+ "-m",11+ "coverage",12+ "run",13+ "-m",14+ "typer",15+ "tests.assets.cli.multi_app",16+ "utils",17+ "docs",18+ "--name",19+ "multiapp",20+ ],21+ capture_output=True,22+ encoding="utf-8",23+ )24+ docs_path: Path = Path(__file__).parent.parent / "assets/cli/multiapp-docs.md"25+ docs = docs_path.read_text()26+ assert docs in result.stdout27+ assert "**Arguments**" in result.stdout28+29+30+def test_doc_output(tmp_path: Path):31+ out_file: Path = tmp_path / "out.md"32+ result = subprocess.run(33+ [34+ sys.executable,35+ "-m",36+ "coverage",37+ "run",38+ "-m",39+ "typer",40+ "tests.assets.cli.multi_app",41+ "utils",42+ "docs",43+ "--name",44+ "multiapp",45+ "--output",46+ str(out_file),47+ ],48+ capture_output=True,49+ encoding="utf-8",50+ )51+ docs_path: Path = Path(__file__).parent.parent / "assets/cli/multiapp-docs.md"52+ docs = docs_path.read_text()53+ written_docs = out_file.read_text()54+ assert docs in written_docs55+ assert "Docs saved to:" in result.stdout56+57+58+def test_doc_not_existing():59+ result = subprocess.run(60+ [61+ sys.executable,62+ "-m",63+ "coverage",64+ "run",65+ "-m",66+ "typer",67+ "no_typer",68+ "utils",69+ "docs",70+ ],71+ capture_output=True,72+ encoding="utf-8",73+ )74+ assert "Could not import as Python module:" in result.stderr75+76+77+def test_doc_no_typer():78+ result = subprocess.run(79+ [80+ sys.executable,81+ "-m",82+ "coverage",83+ "run",84+ "-m",85+ "typer",86+ "tests/assets/cli/empty_script.py",87+ "utils",88+ "docs",89+ ],90+ capture_output=True,91+ encoding="utf-8",92+ )93+ assert "No Typer app found" in result.stderr94+95+96+def test_doc_file_not_existing():97+ result = subprocess.run(98+ [99+ sys.executable,100+ "-m",101+ "coverage",102+ "run",103+ "-m",104+ "typer",105+ "assets/cli/not_existing.py",106+ "utils",107+ "docs",108+ ],109+ capture_output=True,110+ encoding="utf-8",111+ )112+ assert "Not a valid file or Python module:" in result.stderradded:tests/test_cli/test_empty_script.py+20 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/empty_script.py",15+ "--help",16+ ],17+ capture_output=True,18+ encoding="utf-8",19+ )20+ assert "run" not in result.stdoutadded:tests/test_cli/test_func_other_name.py+22 added
1+import subprocess2+import sys3+4+5+def test_script():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/func_other_name.py",15+ "run",16+ "--name",17+ "Camila",18+ ],19+ capture_output=True,20+ encoding="utf-8",21+ )22+ assert "Hello Camila" in result.stdoutadded:tests/test_cli/test_help.py+38 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/sample.py",15+ "--help",16+ ],17+ capture_output=True,18+ encoding="utf-8",19+ )20+ assert "run" in result.stdout21+22+23+def test_not_python():24+ result = subprocess.run(25+ [26+ sys.executable,27+ "-m",28+ "coverage",29+ "run",30+ "-m",31+ "typer",32+ "tests/assets/cli/not_python.txt",33+ "run",34+ ],35+ capture_output=True,36+ encoding="utf-8",37+ )38+ assert "Could not import as Python file" in result.stderradded:tests/test_cli/test_multi_app_cli.py+102 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/multi_app_cli.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "sub" in result.stdout22+ assert "top" in result.stdout23+24+25+def test_script_sub():26+ result = subprocess.run(27+ [28+ sys.executable,29+ "-m",30+ "coverage",31+ "run",32+ "-m",33+ "typer",34+ "tests/assets/cli/multi_app_cli.py",35+ "run",36+ "sub",37+ "--help",38+ ],39+ capture_output=True,40+ encoding="utf-8",41+ )42+ assert "bye" in result.stdout43+ assert "hello" in result.stdout44+45+46+def test_script_top():47+ result = subprocess.run(48+ [49+ sys.executable,50+ "-m",51+ "coverage",52+ "run",53+ "-m",54+ "typer",55+ "tests/assets/cli/multi_app_cli.py",56+ "run",57+ "top",58+ ],59+ capture_output=True,60+ encoding="utf-8",61+ )62+ assert "top" in result.stdout63+64+65+def test_script_sub_hello():66+ result = subprocess.run(67+ [68+ sys.executable,69+ "-m",70+ "coverage",71+ "run",72+ "-m",73+ "typer",74+ "tests/assets/cli/multi_app_cli.py",75+ "run",76+ "sub",77+ "hello",78+ ],79+ capture_output=True,80+ encoding="utf-8",81+ )82+ assert "sub hello" in result.stdout83+84+85+def test_script_sub_bye():86+ result = subprocess.run(87+ [88+ sys.executable,89+ "-m",90+ "coverage",91+ "run",92+ "-m",93+ "typer",94+ "tests/assets/cli/multi_app_cli.py",95+ "run",96+ "sub",97+ "bye",98+ ],99+ capture_output=True,100+ encoding="utf-8",101+ )102+ assert "sub bye" in result.stdoutadded:tests/test_cli/test_multi_app_sub.py+46 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "--app",15+ "sub_app",16+ "tests/assets/cli/multi_app.py",17+ "run",18+ "--help",19+ ],20+ capture_output=True,21+ encoding="utf-8",22+ )23+ assert "bye" in result.stdout24+ assert "hello" in result.stdout25+ assert "top" not in result.stdout26+27+28+def test_script():29+ result = subprocess.run(30+ [31+ sys.executable,32+ "-m",33+ "coverage",34+ "run",35+ "-m",36+ "typer",37+ "--app",38+ "sub_app",39+ "tests/assets/cli/multi_app.py",40+ "run",41+ "hello",42+ ],43+ capture_output=True,44+ encoding="utf-8",45+ )46+ assert "Hello World" in result.stdoutadded:tests/test_cli/test_multi_app.py+123 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/multi_app.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "sub" in result.stdout22+ assert "top" in result.stdout23+24+25+def test_script_app_non_existent():26+ result = subprocess.run(27+ [28+ sys.executable,29+ "-m",30+ "coverage",31+ "run",32+ "-m",33+ "typer",34+ "--app",35+ "non_existent",36+ "tests/assets/cli/multi_app.py",37+ "run",38+ "--help",39+ ],40+ capture_output=True,41+ encoding="utf-8",42+ )43+ assert "Not a Typer object:" in result.stderr44+45+46+def test_script_sub():47+ result = subprocess.run(48+ [49+ sys.executable,50+ "-m",51+ "coverage",52+ "run",53+ "-m",54+ "typer",55+ "tests/assets/cli/multi_app.py",56+ "run",57+ "sub",58+ "--help",59+ ],60+ capture_output=True,61+ encoding="utf-8",62+ )63+ assert "bye" in result.stdout64+ assert "hello" in result.stdout65+66+67+def test_script_top():68+ result = subprocess.run(69+ [70+ sys.executable,71+ "-m",72+ "coverage",73+ "run",74+ "-m",75+ "typer",76+ "tests/assets/cli/multi_app.py",77+ "run",78+ "top",79+ ],80+ capture_output=True,81+ encoding="utf-8",82+ )83+ assert "top" in result.stdout84+85+86+def test_script_sub_hello():87+ result = subprocess.run(88+ [89+ sys.executable,90+ "-m",91+ "coverage",92+ "run",93+ "-m",94+ "typer",95+ "tests/assets/cli/multi_app.py",96+ "run",97+ "sub",98+ "hello",99+ ],100+ capture_output=True,101+ encoding="utf-8",102+ )103+ assert "Hello World" in result.stdout104+105+106+def test_script_sub_bye():107+ result = subprocess.run(108+ [109+ sys.executable,110+ "-m",111+ "coverage",112+ "run",113+ "-m",114+ "typer",115+ "tests/assets/cli/multi_app.py",116+ "run",117+ "sub",118+ "bye",119+ ],120+ capture_output=True,121+ encoding="utf-8",122+ )123+ assert "sub bye" in result.stdoutadded:tests/test_cli/test_multi_func.py+106 added
1+import subprocess2+import sys3+4+5+def test_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/multi_func.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "Say hi to someone, by default to the World." in result.stdout22+23+24+def test_script():25+ result = subprocess.run(26+ [27+ sys.executable,28+ "-m",29+ "coverage",30+ "run",31+ "-m",32+ "typer",33+ "tests/assets/cli/multi_func.py",34+ "run",35+ "--name",36+ "Camila",37+ ],38+ capture_output=True,39+ encoding="utf-8",40+ )41+ assert "Hello Camila" in result.stdout42+43+44+def test_script_func_non_existent():45+ result = subprocess.run(46+ [47+ sys.executable,48+ "-m",49+ "coverage",50+ "run",51+ "-m",52+ "typer",53+ "--func",54+ "non_existent",55+ "tests/assets/cli/multi_func.py",56+ "run",57+ "--name",58+ "Camila",59+ ],60+ capture_output=True,61+ encoding="utf-8",62+ )63+ assert "Not a function:" in result.stderr64+65+66+def test_script_func_not_function():67+ result = subprocess.run(68+ [69+ sys.executable,70+ "-m",71+ "coverage",72+ "run",73+ "-m",74+ "typer",75+ "--func",76+ "message",77+ "tests/assets/cli/multi_func.py",78+ "run",79+ "--name",80+ "Camila",81+ ],82+ capture_output=True,83+ encoding="utf-8",84+ )85+ assert "Not a function:" in result.stderr86+87+88+def test_script_func():89+ result = subprocess.run(90+ [91+ sys.executable,92+ "-m",93+ "coverage",94+ "run",95+ "-m",96+ "typer",97+ "--func",98+ "say_stuff",99+ "tests/assets/cli/multi_func.py",100+ "run",101+ ],102+ capture_output=True,103+ encoding="utf-8",104+ )105+ assert "Hello" not in result.stdout106+ assert "Stuff" in result.stdoutadded:tests/test_cli/test_not_python.py+20 added
1+import subprocess2+import sys3+4+5+def test_not_python():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/not_python.txt",15+ "run",16+ ],17+ capture_output=True,18+ encoding="utf-8",19+ )20+ assert "Could not import as Python file" in result.stderradded:tests/test_cli/test_sub_completion.py+19 added
1+import os2+import subprocess3+import sys4+5+6+def test_script_completion_run():7+ result = subprocess.run(8+ [sys.executable, "-m", "coverage", "run", "-m", "typer"],9+ capture_output=True,10+ encoding="utf-8",11+ env={12+ **os.environ,13+ "___MAIN__.PY_COMPLETE": "complete_bash",14+ "_PYTHON _M TYPER_COMPLETE": "complete_bash",15+ "COMP_WORDS": "typer tests/assets/cli/sample.py run hello --",16+ "COMP_CWORD": "4",17+ },18+ )19+ assert "--name" in result.stdoutadded:tests/test_cli/test_sub_help.py+24 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/sample.py",15+ "run",16+ "--help",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "bye" in result.stdout22+ assert "Say bye" in result.stdout23+ assert "hello" in result.stdout24+ assert "Say hi" in result.stdoutadded:tests/test_cli/test_sub.py+139 added
1+import subprocess2+import sys3+4+5+def test_script_hello():6+ result = subprocess.run(7+ [8+ sys.executable,9+ "-m",10+ "coverage",11+ "run",12+ "-m",13+ "typer",14+ "tests/assets/cli/sample.py",15+ "run",16+ "hello",17+ ],18+ capture_output=True,19+ encoding="utf-8",20+ )21+ assert "Hello World!" in result.stdout22+23+24+def test_script_hello_name():25+ result = subprocess.run(26+ [27+ sys.executable,28+ "-m",29+ "coverage",30+ "run",31+ "-m",32+ "typer",33+ "tests/assets/cli/sample.py",34+ "run",35+ "hello",36+ "--name",37+ "Camila",38+ ],39+ capture_output=True,40+ encoding="utf-8",41+ )42+ assert "Hello Camila!" in result.stdout43+44+45+def test_script_hello_name_formal():46+ result = subprocess.run(47+ [48+ sys.executable,49+ "-m",50+ "coverage",51+ "run",52+ "-m",53+ "typer",54+ "tests/assets/cli/sample.py",55+ "run",56+ "hello",57+ "--name",58+ "Camila",59+ "--formal",60+ ],61+ capture_output=True,62+ encoding="utf-8",63+ )64+ assert "Good morning Ms. Camila" in result.stdout65+66+67+def test_script_bye():68+ result = subprocess.run(69+ [70+ sys.executable,71+ "-m",72+ "coverage",73+ "run",74+ "-m",75+ "typer",76+ "tests/assets/cli/sample.py",77+ "run",78+ "bye",79+ ],80+ capture_output=True,81+ encoding="utf-8",82+ )83+ assert "Goodbye" in result.stdout84+85+86+def test_script_bye_friend():87+ result = subprocess.run(88+ [89+ sys.executable,90+ "-m",91+ "coverage",92+ "run",93+ "-m",94+ "typer",95+ "tests/assets/cli/sample.py",96+ "run",97+ "bye",98+ "--friend",99+ ],100+ capture_output=True,101+ encoding="utf-8",102+ )103+ assert "Goodbye my friend" in result.stdout104+105+106+def test_script_help():107+ result = subprocess.run(108+ [109+ sys.executable,110+ "-m",111+ "coverage",112+ "run",113+ "-m",114+ "typer",115+ "tests/assets/cli/sample.py",116+ "--help",117+ ],118+ capture_output=True,119+ encoding="utf-8",120+ )121+ assert "run" in result.stdout122+123+124+def test_not_python():125+ result = subprocess.run(126+ [127+ sys.executable,128+ "-m",129+ "coverage",130+ "run",131+ "-m",132+ "typer",133+ "tests/assets/cli/not_python.txt",134+ "run",135+ ],136+ capture_output=True,137+ encoding="utf-8",138+ )139+ assert "Could not import as Python file" in result.stderradded:tests/test_cli/test_version.py+11 added
1+import subprocess2+import sys3+4+5+def test_script_help():6+ result = subprocess.run(7+ [sys.executable, "-m", "coverage", "run", "-m", "typer", "--version"],8+ capture_output=True,9+ encoding="utf-8",10+ )11+ assert "Typer version:" in result.stdoutmodified:tests/test_compat/test_option_get_help.py-1 removed
46 unmodified lines47 env={48 **os.environ,49 "_COMPAT_CLICK7_8.PY_COMPLETE": "complete_zsh",50 "_TYPER_COMPLETE_ARGS": "compat_click7_8.py --nickname ",51- "_TYPER_COMPLETE_TESTING": "True",51 },52 )53 assert "Jonny" in result.stdoutmodified:tests/test_completion/test_completion_complete_no_help.py-4 removed
12 unmodified lines13 env={14 **os.environ,15 "_TUTORIAL002.PY_COMPLETE": "complete_zsh",16 "_TYPER_COMPLETE_ARGS": "tutorial002.py ",17- "_TYPER_COMPLETE_TESTING": "True",17 },18 )19 assert "create" in result.stdout20 assert "delete" in result.stdout8 unmodified lines29 **os.environ,30 "_TUTORIAL002.PY_COMPLETE": "complete_fish",31 "_TYPER_COMPLETE_ARGS": "tutorial002.py ",32 "_TYPER_COMPLETE_FISH_ACTION": "get-args",34- "_TYPER_COMPLETE_TESTING": "True",33 },34 )35 assert "create\ndelete" in result.stdout36 6 unmodified lines43 env={44 **os.environ,45 "_TUTORIAL002.PY_COMPLETE": "complete_powershell",46 "_TYPER_COMPLETE_ARGS": "tutorial002.py ",49- "_TYPER_COMPLETE_TESTING": "True",47 },48 )49 assert ("create::: \ndelete::: ") in result.stdout50 6 unmodified lines57 env={58 **os.environ,59 "_TUTORIAL002.PY_COMPLETE": "complete_pwsh",60 "_TYPER_COMPLETE_ARGS": "tutorial002.py ",64- "_TYPER_COMPLETE_TESTING": "True",61 },62 )63 assert ("create::: \ndelete::: ") in result.stdoutmodified:tests/test_completion/test_completion_complete.py-10 removed
13 unmodified lines14 **os.environ,15 "_TUTORIAL001.PY_COMPLETE": "complete_bash",16 "COMP_WORDS": "tutorial001.py del",17 "COMP_CWORD": "1",18- "_TYPER_COMPLETE_TESTING": "True",18 },19 )20 assert "delete\ndelete-all" in result.stdout21 7 unmodified lines29 **os.environ,30 "_TUTORIAL001.PY_COMPLETE": "complete_bash",31 "COMP_WORDS": "tutorial001.py del",32 "COMP_CWORD": "42",34- "_TYPER_COMPLETE_TESTING": "True",33 },34 )35 assert "create\ndelete\ndelete-all\ninit" in result.stdout36 6 unmodified lines43 env={44 **os.environ,45 "_TUTORIAL001.PY_COMPLETE": "complete_zsh",46 "_TYPER_COMPLETE_ARGS": "tutorial001.py del",49- "_TYPER_COMPLETE_TESTING": "True",47 },48 )49 assert (50 """_arguments '*: :(("delete":"Delete a user with USERNAME."\n"""9 unmodified lines60 env={61 **os.environ,62 "_TUTORIAL001.PY_COMPLETE": "complete_zsh",63 "_TYPER_COMPLETE_ARGS": "tutorial001.py delete ",67- "_TYPER_COMPLETE_TESTING": "True",64 },65 )66 assert ("_files") in result.stdout67 7 unmodified lines75 **os.environ,76 "_TUTORIAL001.PY_COMPLETE": "complete_fish",77 "_TYPER_COMPLETE_ARGS": "tutorial001.py del",78 "_TYPER_COMPLETE_FISH_ACTION": "get-args",83- "_TYPER_COMPLETE_TESTING": "True",79 },80 )81 assert (82 "delete\tDelete a user with USERNAME.\ndelete-all\tDelete ALL users in the database."10 unmodified lines93 **os.environ,94 "_TUTORIAL001.PY_COMPLETE": "complete_fish",95 "_TYPER_COMPLETE_ARGS": "tutorial001.py del",96 "_TYPER_COMPLETE_FISH_ACTION": "is-args",102- "_TYPER_COMPLETE_TESTING": "True",97 },98 )99 assert result.returncode == 0100 7 unmodified lines108 **os.environ,109 "_TUTORIAL001.PY_COMPLETE": "complete_fish",110 "_TYPER_COMPLETE_ARGS": "tutorial001.py delete ",111 "_TYPER_COMPLETE_FISH_ACTION": "is-args",118- "_TYPER_COMPLETE_TESTING": "True",112 },113 )114 assert result.returncode != 0115 6 unmodified lines122 env={123 **os.environ,124 "_TUTORIAL001.PY_COMPLETE": "complete_powershell",125 "_TYPER_COMPLETE_ARGS": "tutorial001.py del",133- "_TYPER_COMPLETE_TESTING": "True",126 },127 )128 assert (129 "delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."8 unmodified lines138 env={139 **os.environ,140 "_TUTORIAL001.PY_COMPLETE": "complete_pwsh",141 "_TYPER_COMPLETE_ARGS": "tutorial001.py del",150- "_TYPER_COMPLETE_TESTING": "True",142 },143 )144 assert (145 "delete:::Delete a user with USERNAME.\ndelete-all:::Delete ALL users in the database."8 unmodified lines154 env={155 **os.environ,156 "_TUTORIAL001.PY_COMPLETE": "complete_noshell",157 "_TYPER_COMPLETE_ARGS": "tutorial001.py del",167- "_TYPER_COMPLETE_TESTING": "True",158 },159 )160 assert ("") in result.stdoutmodified:tests/test_completion/test_completion_install.py-4 removed
20 unmodified lines21 capture_output=True,22 encoding="utf-8",23 env={24 **os.environ,25- "_TYPER_COMPLETE_TESTING": "True",25 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",26 },27 )28 assert "Option '--install-completion' requires an argument" in result.stderr17 unmodified lines46 capture_output=True,47 encoding="utf-8",48 env={49 **os.environ,51- "_TYPER_COMPLETE_TESTING": "True",50 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",51 },52 )53 new_text = bash_completion_path.read_text()33 unmodified lines87 capture_output=True,88 encoding="utf-8",89 env={90 **os.environ,93- "_TYPER_COMPLETE_TESTING": "True",91 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",92 },93 )94 new_text = completion_path.read_text()27 unmodified lines122 capture_output=True,123 encoding="utf-8",124 env={125 **os.environ,129- "_TYPER_COMPLETE_TESTING": "True",126 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",127 },128 )129 new_text = completion_path.read_text()41 unmodified linesmodified:tests/test_completion/test_completion_show.py-6 removed
19 unmodified lines20 capture_output=True,21 encoding="utf-8",22 env={23 **os.environ,24- "_TYPER_COMPLETE_TESTING": "True",24 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",25 },26 )27 assert "Option '--show-completion' requires an argument" in result.stderr13 unmodified lines41 capture_output=True,42 encoding="utf-8",43 env={44 **os.environ,46- "_TYPER_COMPLETE_TESTING": "True",45 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",46 },47 )48 assert (16 unmodified lines65 capture_output=True,66 encoding="utf-8",67 env={68 **os.environ,71- "_TYPER_COMPLETE_TESTING": "True",69 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",70 },71 )72 assert "compdef _tutorial001py_completion tutorial001.py" in result.stdout13 unmodified lines86 capture_output=True,87 encoding="utf-8",88 env={89 **os.environ,93- "_TYPER_COMPLETE_TESTING": "True",90 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",91 },92 )93 assert "complete --command tutorial001.py --no-files" in result.stdout13 unmodified lines107 capture_output=True,108 encoding="utf-8",109 env={110 **os.environ,115- "_TYPER_COMPLETE_TESTING": "True",111 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",112 },113 )114 assert (16 unmodified lines131 capture_output=True,132 encoding="utf-8",133 env={134 **os.environ,140- "_TYPER_COMPLETE_TESTING": "True",135 "_TYPER_COMPLETE_TEST_DISABLE_SHELL_DETECTION": "True",136 },137 )138 assert (11 unmodified linesmodified:tests/test_completion/test_completion.py-8 removed
49 unmodified lines50 encoding="utf-8",51 env={52 **os.environ,53 "_TUTORIAL001.PY_COMPLETE": "sourcebash",54- "_TYPER_COMPLETE_TESTING": "True",54 },55 )56 assert result.returncode != 057 assert "Invalid completion instruction." in result.stderr6 unmodified lines64 encoding="utf-8",65 env={66 **os.environ,67 "_TUTORIAL001.PY_COMPLETE": "source_bash",69- "_TYPER_COMPLETE_TESTING": "True",68 },69 )70 assert (71 "complete -o default -F _tutorial001py_completion tutorial001.py"8 unmodified lines80 encoding="utf-8",81 env={82 **os.environ,83 "_TUTORIAL001.PY_COMPLETE": "source_xxx",86- "_TYPER_COMPLETE_TESTING": "True",84 },85 )86 assert "Shell xxx not supported." in result.stderr87 5 unmodified lines93 encoding="utf-8",94 env={95 **os.environ,96 "_TUTORIAL001.PY_COMPLETE": "explode_bash",100- "_TYPER_COMPLETE_TESTING": "True",97 },98 )99 assert 'Completion instruction "explode" not supported.' in result.stderr100 5 unmodified lines106 encoding="utf-8",107 env={108 **os.environ,109 "_TUTORIAL001.PY_COMPLETE": "source_zsh",114- "_TYPER_COMPLETE_TESTING": "True",110 },111 )112 assert "compdef _tutorial001py_completion tutorial001.py" in result.stdout113 5 unmodified lines119 encoding="utf-8",120 env={121 **os.environ,122 "_TUTORIAL001.PY_COMPLETE": "source_fish",128- "_TYPER_COMPLETE_TESTING": "True",123 },124 )125 assert "complete --command tutorial001.py --no-files" in result.stdout126 5 unmodified lines132 encoding="utf-8",133 env={134 **os.environ,135 "_TUTORIAL001.PY_COMPLETE": "source_powershell",142- "_TYPER_COMPLETE_TESTING": "True",136 },137 )138 assert (139 "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"8 unmodified lines148 encoding="utf-8",149 env={150 **os.environ,151 "_TUTORIAL001.PY_COMPLETE": "source_pwsh",159- "_TYPER_COMPLETE_TESTING": "True",152 },153 )154 assert (155 "Register-ArgumentCompleter -Native -CommandName tutorial001.py -ScriptBlock $scriptblock"2 unmodified linesmodified:tests/test_tutorial/test_options/test_callback/test_tutorial003_an.py-1 removed
43 unmodified lines44 **os.environ,45 "_TUTORIAL003_AN.PY_COMPLETE": "complete_bash",46 "COMP_WORDS": "tutorial003_an.py --",47 "COMP_CWORD": "1",48- "_TYPER_COMPLETE_TESTING": "True",48 },49 )50 assert "--name" in result.stdoutmodified:tests/test_tutorial/test_options/test_callback/test_tutorial003.py-1 removed
43 unmodified lines44 **os.environ,45 "_TUTORIAL003.PY_COMPLETE": "complete_bash",46 "COMP_WORDS": "tutorial003.py --",47 "COMP_CWORD": "1",48- "_TYPER_COMPLETE_TESTING": "True",48 },49 )50 assert "--name" in result.stdoutmodified:tests/test_tutorial/test_options/test_callback/test_tutorial004_an.py-1 removed
43 unmodified lines44 **os.environ,45 "_TUTORIAL004_AN.PY_COMPLETE": "complete_bash",46 "COMP_WORDS": "tutorial004_an.py --",47 "COMP_CWORD": "1",48- "_TYPER_COMPLETE_TESTING": "True",48 },49 )50 assert "--name" in result.stdoutmodified:tests/test_tutorial/test_options/test_callback/test_tutorial004.py-1 removed
43 unmodified lines44 **os.environ,45 "_TUTORIAL004.PY_COMPLETE": "complete_bash",46 "COMP_WORDS": "tutorial004.py --",47 "COMP_CWORD": "1",48- "_TYPER_COMPLETE_TESTING": "True",48 },49 )50 assert "--name" in result.stdoutmodified:tests/test_tutorial/test_options/test_version/test_tutorial003_an.py-1 removed
48 unmodified lines49 **os.environ,50 "_TUTORIAL003_AN.PY_COMPLETE": "complete_bash",51 "COMP_WORDS": "tutorial003_an.py --name Rick --v",52 "COMP_CWORD": "3",53- "_TYPER_COMPLETE_TESTING": "True",53 },54 )55 assert "--version" in result.stdoutmodified:tests/test_tutorial/test_options/test_version/test_tutorial003.py-1 removed
48 unmodified lines49 **os.environ,50 "_TUTORIAL003.PY_COMPLETE": "complete_bash",51 "COMP_WORDS": "tutorial003.py --name Rick --v",52 "COMP_CWORD": "3",53- "_TYPER_COMPLETE_TESTING": "True",53 },54 )55 assert "--version" in result.stdoutmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial002_an.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL002_AN.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial002_an.py --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert "Camila" in result.stdout24 assert "Carlos" in result.stdout16 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial002.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL002.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial002.py --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert "Camila" in result.stdout24 assert "Carlos" in result.stdout16 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial003_an.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL003_AN.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial003_an.py --name Seb",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert "Camila" not in result.stdout24 assert "Carlos" not in result.stdout16 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial003.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL003.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial003.py --name Seb",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert "Camila" not in result.stdout24 assert "Carlos" not in result.stdout16 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial004_an.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL004_AN.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial004_an_aux.py --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout16 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial004.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL004.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial004_aux.py --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout16 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial007_an.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL007_AN.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial007_an.py --name Sebastian --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout17 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial007.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL007.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial007.py --name Sebastian --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout17 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial008_an.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL008_AN.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial008_an.py --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout18 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial008.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL008.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial008.py --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout18 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial009_an.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL009_AN.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial009_an.py --name Sebastian --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout18 unmodified linesmodified:tests/test_tutorial/test_options_autocompletion/test_tutorial009.py-1 removed
16 unmodified lines17 env={18 **os.environ,19 "_TUTORIAL009.PY_COMPLETE": "complete_zsh",20 "_TYPER_COMPLETE_ARGS": "tutorial009.py --name Sebastian --name ",21- "_TYPER_COMPLETE_TESTING": "True",21 },22 )23 assert '"Camila":"The reader of books."' in result.stdout24 assert '"Carlos":"The writer of scripts."' in result.stdout18 unmodified linesmodified:tests/test_others.py-2 removed
149 unmodified lines150 env={151 **os.environ,152 "_COMPLETION_NO_TYPES.PY_COMPLETE": "complete_zsh",153 "_TYPER_COMPLETE_ARGS": "completion_no_types.py --name Sebastian --name Ca",154- "_TYPER_COMPLETE_TESTING": "True",154 },155 )156 assert "info name is: completion_no_types.py" in result.stderr157 assert "args is: []" in result.stderr18 unmodified lines176 env={177 **os.environ,178 "_COMPLETION_NO_TYPES_ORDER.PY_COMPLETE": "complete_zsh",179 "_TYPER_COMPLETE_ARGS": "completion_no_types_order.py --name Sebastian --name Ca",181- "_TYPER_COMPLETE_TESTING": "True",180 },181 )182 assert "info name is: completion_no_types_order.py" in result.stderr183 assert "args is: []" in result.stderr75 unmodified linesmodified:typer/__init__.py+1 added-1 removed
1 """Typer, build great CLIs. Easy to code. Based on Python type hints."""2 3-__version__ = "0.11.1"3+__version__ = "0.12.dev2"4 5 from shutil import get_terminal_size as get_terminal_size6 7 from click.exceptions import Abort as Abort32 unmodified linesadded:typer/__main__.py+3 added
1+from .cli import main2+3+main()added:typer/cli.py+292 added
1+import importlib.util2+import re3+import sys4+from pathlib import Path5+from typing import Any, List, Optional6+7+import click8+import typer9+import typer.core10+from click import Command, Group, Option11+12+from . import __version__13+14+default_app_names = ("app", "cli", "main")15+default_func_names = ("main", "cli", "app")16+17+app = typer.Typer()18+utils_app = typer.Typer(help="Extra utility commands for Typer apps.")19+app.add_typer(utils_app, name="utils")20+21+22+class State:23+ def __init__(self) -> None:24+ self.app: Optional[str] = None25+ self.func: Optional[str] = None26+ self.file: Optional[Path] = None27+ self.module: Optional[str] = None28+29+30+state = State()31+32+33+def maybe_update_state(ctx: click.Context) -> None:34+ path_or_module = ctx.params.get("path_or_module")35+ if path_or_module:36+ file_path = Path(path_or_module)37+ if file_path.exists() and file_path.is_file():38+ state.file = file_path39+ else:40+ if not re.fullmatch(r"[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*", path_or_module):41+ typer.echo(42+ f"Not a valid file or Python module: {path_or_module}", err=True43+ )44+ sys.exit(1)45+ state.module = path_or_module46+ app_name = ctx.params.get("app")47+ if app_name:48+ state.app = app_name49+ func_name = ctx.params.get("func")50+ if func_name:51+ state.func = func_name52+53+54+class TyperCLIGroup(typer.core.TyperGroup):55+ def list_commands(self, ctx: click.Context) -> List[str]:56+ self.maybe_add_run(ctx)57+ return super().list_commands(ctx)58+59+ def get_command(self, ctx: click.Context, name: str) -> Optional[Command]:60+ self.maybe_add_run(ctx)61+ return super().get_command(ctx, name)62+63+ def invoke(self, ctx: click.Context) -> Any:64+ self.maybe_add_run(ctx)65+ return super().invoke(ctx)66+67+ def maybe_add_run(self, ctx: click.Context) -> None:68+ maybe_update_state(ctx)69+ maybe_add_run_to_cli(self)70+71+72+def get_typer_from_module(module: Any) -> Optional[typer.Typer]:73+ # Try to get defined app74+ if state.app:75+ obj = getattr(module, state.app, None)76+ if not isinstance(obj, typer.Typer):77+ typer.echo(f"Not a Typer object: --app {state.app}", err=True)78+ sys.exit(1)79+ return obj80+ # Try to get defined function81+ if state.func:82+ func_obj = getattr(module, state.func, None)83+ if not callable(func_obj):84+ typer.echo(f"Not a function: --func {state.func}", err=True)85+ sys.exit(1)86+ sub_app = typer.Typer()87+ sub_app.command()(func_obj)88+ return sub_app89+ # Iterate and get a default object to use as CLI90+ local_names = dir(module)91+ local_names_set = set(local_names)92+ # Try to get a default Typer app93+ for name in default_app_names:94+ if name in local_names_set:95+ obj = getattr(module, name, None)96+ if isinstance(obj, typer.Typer):97+ return obj98+ # Try to get any Typer app99+ for name in local_names_set - set(default_app_names):100+ obj = getattr(module, name)101+ if isinstance(obj, typer.Typer):102+ return obj103+ # Try to get a default function104+ for func_name in default_func_names:105+ func_obj = getattr(module, func_name, None)106+ if callable(func_obj):107+ sub_app = typer.Typer()108+ sub_app.command()(func_obj)109+ return sub_app110+ # Try to get any func app111+ for func_name in local_names_set - set(default_func_names):112+ func_obj = getattr(module, func_name)113+ if callable(func_obj):114+ sub_app = typer.Typer()115+ sub_app.command()(func_obj)116+ return sub_app117+ return None118+119+120+def get_typer_from_state() -> Optional[typer.Typer]:121+ spec = None122+ if state.file:123+ module_name = state.file.name124+ spec = importlib.util.spec_from_file_location(module_name, str(state.file))125+ elif state.module:126+ spec = importlib.util.find_spec(state.module)127+ if spec is None:128+ if state.file:129+ typer.echo(f"Could not import as Python file: {state.file}", err=True)130+ else:131+ typer.echo(f"Could not import as Python module: {state.module}", err=True)132+ sys.exit(1)133+ module = importlib.util.module_from_spec(spec)134+ spec.loader.exec_module(module) # type: ignore135+ obj = get_typer_from_module(module)136+ return obj137+138+139+def maybe_add_run_to_cli(cli: click.Group) -> None:140+ if "run" not in cli.commands:141+ if state.file or state.module:142+ obj = get_typer_from_state()143+ if obj:144+ obj._add_completion = False145+ click_obj = typer.main.get_command(obj)146+ click_obj.name = "run"147+ if not click_obj.help:148+ click_obj.help = "Run the provided Typer app."149+ cli.add_command(click_obj)150+151+152+def print_version(ctx: click.Context, param: Option, value: bool) -> None:153+ if not value or ctx.resilient_parsing:154+ return155+ typer.echo(f"Typer version: {__version__}")156+ raise typer.Exit()157+158+159+@app.callback(cls=TyperCLIGroup, no_args_is_help=True)160+def callback(161+ ctx: typer.Context,162+ *,163+ path_or_module: str = typer.Argument(None),164+ app: str = typer.Option(None, help="The typer app object/variable to use."),165+ func: str = typer.Option(None, help="The function to convert to Typer."),166+ version: bool = typer.Option(167+ False,168+ "--version",169+ help="Print version and exit.",170+ callback=print_version,171+ ),172+) -> None:173+ """174+ Run Typer scripts with completion, without having to create a package.175+176+ You probably want to install completion for the typer command:177+178+ $ typer --install-completion179+180+ https://typer.tiangolo.com/181+ """182+ maybe_update_state(ctx)183+184+185+def get_docs_for_click(186+ *,187+ obj: Command,188+ ctx: typer.Context,189+ indent: int = 0,190+ name: str = "",191+ call_prefix: str = "",192+) -> str:193+ docs = "#" * (1 + indent)194+ command_name = name or obj.name195+ if call_prefix:196+ command_name = f"{call_prefix} {command_name}"197+ title = f"`{command_name}`" if command_name else "CLI"198+ docs += f" {title}\n\n"199+ if obj.help:200+ docs += f"{obj.help}\n\n"201+ usage_pieces = obj.collect_usage_pieces(ctx)202+ if usage_pieces:203+ docs += "**Usage**:\n\n"204+ docs += "```console\n"205+ docs += "$ "206+ if command_name:207+ docs += f"{command_name} "208+ docs += f"{' '.join(usage_pieces)}\n"209+ docs += "```\n\n"210+ args = []211+ opts = []212+ for param in obj.get_params(ctx):213+ rv = param.get_help_record(ctx)214+ if rv is not None:215+ if param.param_type_name == "argument":216+ args.append(rv)217+ elif param.param_type_name == "option":218+ opts.append(rv)219+ if args:220+ docs += "**Arguments**:\n\n"221+ for arg_name, arg_help in args:222+ docs += f"* `{arg_name}`"223+ if arg_help:224+ docs += f": {arg_help}"225+ docs += "\n"226+ docs += "\n"227+ if opts:228+ docs += "**Options**:\n\n"229+ for opt_name, opt_help in opts:230+ docs += f"* `{opt_name}`"231+ if opt_help:232+ docs += f": {opt_help}"233+ docs += "\n"234+ docs += "\n"235+ if obj.epilog:236+ docs += f"{obj.epilog}\n\n"237+ if isinstance(obj, Group):238+ group = obj239+ commands = group.list_commands(ctx)240+ if commands:241+ docs += "**Commands**:\n\n"242+ for command in commands:243+ command_obj = group.get_command(ctx, command)244+ assert command_obj245+ docs += f"* `{command_obj.name}`"246+ command_help = command_obj.get_short_help_str()247+ if command_help:248+ docs += f": {command_help}"249+ docs += "\n"250+ docs += "\n"251+ for command in commands:252+ command_obj = group.get_command(ctx, command)253+ assert command_obj254+ use_prefix = ""255+ if command_name:256+ use_prefix += f"{command_name}"257+ docs += get_docs_for_click(258+ obj=command_obj, ctx=ctx, indent=indent + 1, call_prefix=use_prefix259+ )260+ return docs261+262+263+@utils_app.command()264+def docs(265+ ctx: typer.Context,266+ name: str = typer.Option("", help="The name of the CLI program to use in docs."),267+ output: Path = typer.Option(268+ None,269+ help="An output file to write docs to, like README.md.",270+ file_okay=True,271+ dir_okay=False,272+ ),273+) -> None:274+ """275+ Generate Markdown docs for a Typer app.276+ """277+ typer_obj = get_typer_from_state()278+ if not typer_obj:279+ typer.echo("No Typer app found", err=True)280+ raise typer.Abort()281+ click_obj = typer.main.get_command(typer_obj)282+ docs = get_docs_for_click(obj=click_obj, ctx=ctx, name=name)283+ clean_docs = f"{docs.strip()}\n"284+ if output:285+ output.write_text(clean_docs)286+ typer.echo(f"Docs saved to: {output}")287+ else:288+ typer.echo(clean_docs)289+290+291+def main() -> Any:292+ return app()added:typer_cli_package/pdm_build.py+40 added
1+from pathlib import Path2+from typing import List3+4+from pdm.backend.hooks import Context5+6+packages_to_sync = ["typer-slim"]7+8+license_name = "LICENSE"9+license_path = Path("..") / license_name10+11+12+def pdm_build_hook_enabled(context: Context):13+ return context.target == "sdist"14+15+16+def pdm_build_initialize(context: Context):17+ metadata = context.config.metadata18+ # Get main version19+ version = metadata["version"]20+ # Update version in dependencies to sync them21+ dependencies: List[str] = metadata["dependencies"]22+ new_dependencies = []23+ for dep in dependencies:24+ if any(dep.startswith(name) for name in packages_to_sync):25+ new_dep = f"{dep}=={version}"26+ new_dependencies.append(new_dep)27+ else:28+ new_dependencies.append(dep)29+ if new_dependencies != dependencies:30+ metadata["dependencies"] = new_dependencies31+ # LICENSE32+ license_content = license_path.read_text()33+ context.ensure_build_dir()34+ # # Workaround, copy LICENSE to package_dir during build35+ Path(license_name).write_text(license_content)36+37+38+def pdm_build_finalize(context: Context, artifact: Path):39+ # Workaround, remove LICENSE from package_dir after build40+ Path(license_name).unlink()added:typer_cli_package/pyproject.toml+55 added
1+[build-system]2+requires = ["pdm-backend"]3+build-backend = "pdm.backend"4+5+[project]6+name = "typer-cli"7+dynamic = ["version"]8+description = "Typer, build great CLIs. Easy to code. Based on Python type hints."9+authors = [10+ {name = "Sebastián Ramírez", email = "tiangolo@gmail.com"},11+]12+readme = "README.md"13+requires-python = ">=3.7"14+classifiers = [15+ "Intended Audience :: Information Technology",16+ "Intended Audience :: System Administrators",17+ "Operating System :: OS Independent",18+ "Programming Language :: Python :: 3",19+ "Programming Language :: Python",20+ "Topic :: Software Development :: Libraries :: Application Frameworks",21+ "Topic :: Software Development :: Libraries :: Python Modules",22+ "Topic :: Software Development :: Libraries",23+ "Topic :: Software Development",24+ "Typing :: Typed",25+ "Development Status :: 4 - Beta",26+ "Intended Audience :: Developers",27+ "Programming Language :: Python :: 3 :: Only",28+ "Programming Language :: Python :: 3.7",29+ "Programming Language :: Python :: 3.8",30+ "Programming Language :: Python :: 3.9",31+ "Programming Language :: Python :: 3.10",32+ "Programming Language :: Python :: 3.11",33+ "License :: OSI Approved :: MIT License",34+]35+dependencies = [36+ "typer-slim[standard]",37+]38+39+[project.urls]40+Documentation = "https://typer.tiangolo.com/"41+homepage = "https://github.com/tiangolo/typer"42+43+[project.optional-dependencies]44+# For backwards compatibility45+all = []46+47+[project.scripts]48+typer = "typer.cli:main"49+50+[tool.pdm]51+version = { source = "file", path = "../typer/__init__.py" }52+distribution = true53+54+[tool.pdm.build]55+excludes = ["*"]added:typer_cli_package/README.md+49 added
1+<p align="center">2+ <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" alt="Typer"></a>3+</p>4+<p align="center">5+ <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>6+</p>7+<p align="center">8+<a href="https://github.com/tiangolo/typer/actions?query=workflow%3ATest" target="_blank">9+ <img src="https://github.com/tiangolo/typer/workflows/Test/badge.svg" alt="Test">10+</a>11+<a href="https://github.com/tiangolo/typer/actions?query=workflow%3APublish" target="_blank">12+ <img src="https://github.com/tiangolo/typer/workflows/Publish/badge.svg" alt="Publish">13+</a>14+<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/typer" target="_blank">15+ <img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/typer.svg" alt="Coverage">16+<a href="https://pypi.org/project/typer" target="_blank">17+ <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">18+</a>19+</p>20+21+---22+23+**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com/tutorial/typer-command/</a>24+25+**Source Code**: <a href="https://github.com/tiangolo/typer" target="_blank">https://github.com/tiangolo/typer</a>26+27+---28+29+Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.30+31+## Typer CLI32+33+This package, `typer-cli`, only provides a command `typer` in the shell with the same functionality of `python -m typer`.34+35+The only reason why this is a separate package is to allow developers to opt out of the `typer` command by installing `typer-slim`, that doesn't include `typer-cli`.36+37+You probably **should not** install this package.38+39+Install instead:40+41+```bash42+pip install typer43+```44+45+That includes this package, `typer-cli`, with the `typer` command.46+47+## License48+49+This project is licensed under the terms of the MIT license.added:typer_package/pdm_build.py+49 added
1+from pathlib import Path2+from typing import List3+4+from pdm.backend.hooks import Context5+6+packages_to_sync = ["typer-slim", "typer-cli"]7+8+readme_name = "README.md"9+license_name = "LICENSE"10+readme_path = Path("..") / readme_name11+license_path = Path("..") / license_name12+13+14+def pdm_build_hook_enabled(context: Context):15+ return context.target == "sdist"16+17+18+def pdm_build_initialize(context: Context):19+ metadata = context.config.metadata20+ # Get main version21+ version = metadata["version"]22+ # Update version in dependencies to sync them23+ dependencies: List[str] = metadata["dependencies"]24+ new_dependencies = []25+ for dep in dependencies:26+ if any(dep.startswith(name) for name in packages_to_sync):27+ new_dep = f"{dep}=={version}"28+ new_dependencies.append(new_dep)29+ else:30+ new_dependencies.append(dep)31+ if new_dependencies != dependencies:32+ metadata["dependencies"] = new_dependencies33+ # README.md and LICENSE34+ readme_content = readme_path.read_text()35+ license_content = license_path.read_text()36+ metadata["readme"] = readme_name37+ context.ensure_build_dir()38+ # Copy README.md and LICENSE to build directory39+ # (context.build_dir / readme_name).write_text(readme_content)40+ # (context.build_dir / license_name).write_text(license_content)41+ # # Workaround, copy README.md and LICENSE to package_dir during build42+ Path(readme_name).write_text(readme_content)43+ Path(license_name).write_text(license_content)44+45+46+def pdm_build_finalize(context: Context, artifact: Path):47+ # Workaround, remove README.md and LICENSE from package_dir after build48+ Path(readme_name).unlink()49+ Path(license_name).unlink()added:typer_package/pyproject.toml+52 added
1+[build-system]2+requires = ["pdm-backend"]3+build-backend = "pdm.backend"4+5+[project]6+name = "typer"7+dynamic = ["version"]8+description = "Typer, build great CLIs. Easy to code. Based on Python type hints."9+authors = [10+ {name = "Sebastián Ramírez", email = "tiangolo@gmail.com"},11+]12+requires-python = ">=3.7"13+classifiers = [14+ "Intended Audience :: Information Technology",15+ "Intended Audience :: System Administrators",16+ "Operating System :: OS Independent",17+ "Programming Language :: Python :: 3",18+ "Programming Language :: Python",19+ "Topic :: Software Development :: Libraries :: Application Frameworks",20+ "Topic :: Software Development :: Libraries :: Python Modules",21+ "Topic :: Software Development :: Libraries",22+ "Topic :: Software Development",23+ "Typing :: Typed",24+ "Development Status :: 4 - Beta",25+ "Intended Audience :: Developers",26+ "Programming Language :: Python :: 3 :: Only",27+ "Programming Language :: Python :: 3.7",28+ "Programming Language :: Python :: 3.8",29+ "Programming Language :: Python :: 3.9",30+ "Programming Language :: Python :: 3.10",31+ "Programming Language :: Python :: 3.11",32+ "License :: OSI Approved :: MIT License",33+]34+dependencies = [35+ "typer-slim[standard]",36+ "typer-cli",37+]38+39+[project.urls]40+Documentation = "https://typer.tiangolo.com/"41+homepage = "https://github.com/tiangolo/typer"42+43+[project.optional-dependencies]44+# For backwards compatibility45+all = []46+47+[tool.pdm]48+version = { source = "file", path = "../typer/__init__.py" }49+distribution = true50+51+[tool.pdm.build]52+excludes = ["*"]modified:mkdocs.insiders.yml+1 added-2 removed
1 INHERIT: mkdocs.yml2-plugins:3- - search2+# plugins:3 # TODO: Re-enable once this is fixed: https://github.com/squidfunk/mkdocs-material/issues/69834 # - socialmodified:mkdocs.yml+6 added-1 removed
14 unmodified lines15 16 repo_name: tiangolo/typer17 repo_url: https://github.com/tiangolo/typer18 edit_uri: ""19+plugins:20+ search: null21+ redirects:22+ redirect_maps:23+ typer-cli.md: tutorial/typer-command.md24 25 nav:26 - Typer: index.md27 - Features: features.md57 unmodified lines85 - Testing: tutorial/testing.md86 - Using Click: tutorial/using-click.md87 - Building a Package: tutorial/package.md88 - tutorial/exceptions.md84- - Typer CLI - completion for small scripts: typer-cli.md89+ - tutorial/typer-command.md90 - Alternatives, Inspiration and Comparisons: alternatives.md91 - Help Typer - Get Help: help-typer.md92 - Development - Contributing: contributing.md93 - Release Notes: release-notes.md48 unmodified linesmodified:pyproject.toml+9 added-4 removed
1 unmodified line2 requires = ["pdm-backend"]3 build-backend = "pdm.backend"4 5 [project]6+# pip install typer-slim: is only the Typer library, without extras7+# pip install typer: is typer-slim[standard], with extras and typer-cli6-name = "typer"8+name = "typer-slim"9 dynamic = ["version"]10 description = "Typer, build great CLIs. Easy to code. Based on Python type hints."11 authors = [12 {name = "Sebastián Ramírez", email = "tiangolo@gmail.com"},31 unmodified lines44 homepage = "https://github.com/tiangolo/typer"45 46 [project.optional-dependencies]47 all = [46- "colorama >=0.4.3,<0.5.0",47- "shellingham >=1.3.0,<2.0.0",48- "rich >=10.11.0,<14.0.0",48+ "shellingham >=1.3.0",49+ "rich >=10.11.0",50 ]51+standard = [52+ "shellingham >=1.3.0",53+ "rich >=10.11.0",54+]55 56 [tool.pdm]57 version = { source = "file", path = "typer/__init__.py" }58 distribution = true116 unmodified linesmodified:README.md+93 added-24 removed
26 unmodified lines27 ---28 29 Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.30 31+It's also a command line tool to run scripts, automatically converting them to CLI applications.32+33 The key features are:34 35 * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.36 * **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.37 * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.38 * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.39 * **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.40+* **Run scripts**: Typer includes a `typer` command that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.41 42 ## FastAPI of CLIs43 41-<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>44+**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.45 43-**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling.44-45-And it's intended to be the FastAPI of CLIs.46-47-## Requirements48-49-**Typer** stands on the shoulders of a giant. Its only internal dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.50-46 ## Installation47 48 <div class="termy">49 50 ```console56-$ pip install "typer[all]"51+$ pip install typer52 ---> 100%58-Successfully installed typer53+Successfully installed typer rich shellingham54 ```55 56 </div>57 63-**Note**: that will include <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a>. Rich is the recommended library to *display* information on the terminal, it is optional, but when installed, it's deeply integrated into **Typer** to display beautiful output.64-58 ## Example59 60 ### The absolute minimum61 62 * Create a file `main.py` with:63 64 ```Python65+def main(name: str):66+ print(f"Hello {name}")67+```68+69+This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.70+71+### Run it72+73+Run your application with the `typer` command:74+75+<div class="termy">76+77+```console78+// Run your application79+$ typer main.py run80+81+// You get a nice error, you are missing NAME82+Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME83+Try 'typer [PATH_OR_MODULE] run --help' for help.84+╭─ Error ───────────────────────────────────────────╮85+│ Missing argument 'NAME'. │86+╰───────────────────────────────────────────────────╯87+88+89+// You get a --help for free90+$ typer main.py run --help91+92+Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME93+94+Run the provided Typer app.95+96+╭─ Arguments ───────────────────────────────────────╮97+│ * name TEXT [default: None] [required] |98+╰───────────────────────────────────────────────────╯99+╭─ Options ─────────────────────────────────────────╮100+│ --help Show this message and exit. │101+╰───────────────────────────────────────────────────╯102+103+// Now pass the NAME argument104+$ typer main.py run Camila105+106+Hello Camila107+108+// It works! 🎉109+```110+111+</div>112+113+This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.114+115+**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.116+117+## Use Typer in your code118+119+Now let's start using Typer in your own code, update `main.py` with:120+121+```Python122 import typer123 124 125 def main(name: str):3 unmodified lines129 if __name__ == "__main__":130 typer.run(main)131 ```132 83-### Run it133+Now you could run it with Python directly:134 85-Run your application:86-135 <div class="termy">136 137 ```console138 // Run your application28 unmodified lines167 ```168 169 </div>170 123-**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.171+**Note**: you can also call this same script with the `typer` command, but you don't need to.172 173 ## Example upgrade174 175 This was the simplest example possible.164 unmodified lines340 And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.341 342 **You get**: great editor support, including **completion** and **type checks** everywhere.343 296-**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.344+**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command.345 346 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.347 300-## Optional Dependencies348+## Dependencies349 302-Typer uses <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a> internally. That's the only dependency.350+**Typer** stands on the shoulders of a giant. Its only internal required dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.351 304-But you can also install extras:352+By default it also comes with extra standard dependencies:353 306-* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: and Typer will show nicely formatted errors automatically.307-* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: and Typer will automatically detect the current shell when installing completion.354+* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.355+* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.356 * With `shellingham` you can just use `--install-completion`.357 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.358+* `typer-cli`: adds the `typer` command to your shell:359+ * Quickly run scripts (that don't have to use Typer) with shell completion.360+ * Generate docs for your Typer applications.361 311-You can install `typer` with `rich` and `shellingham` with `pip install typer[all]`.362+### `typer-slim`363 364+If you don't want the extra dependencies, install `typer-slim` instead.365+366+When you install with:367+368+```bash369+pip install typer370+```371+372+...it's the equivalent of:373+374+```bash375+pip install "typer-slim[standard]"376+```377+378+The `standard` extra dependencies are `rich`, `shellingham`, `typer-cli`.379+380+**Note**: even if you don't install `typer-cli` you can still use it's functionality by calling `typer` as a module, e.g. `python -m typer`.381+382 ## License383 384 This project is licensed under the terms of the MIT license.