index.md
This file
Path
docs/index.md
388 lines · 14.3 KiB · Markdown
Last changed by
➖ Vendor Click and streamline Typer's functionality and code base (#1774)Sofie Van Landeghembefore adoption1829d73
History of this fileTake it
The walk stopped after 200 commits: lines older than 3436fe6 point at it.
⬆️ Migrate to Zensical (#1470)Sebastián Ramírezbefore adoptionf655ef2
lines 1–2why, one step back1#2⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 3–16why, one step back3<style>4.md-content .md-typeset h1 { display: none; }5</style>67<p align="center">8 <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>9<!-- only-mkdocs -->10 <a href="https://typer.tiangolo.com"><img src="img/logo-margin/logo-margin-white-vector.svg#only-dark" alt="Typer"></a>11<!-- /only-mkdocs -->12</p>13<p align="center">14 <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>15</p>16<p align="center">📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 17why, one step back17<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster">⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 18–19why, one step back18 <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">19</a>📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 20why, one step back20<a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish">⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 21–22why, one step back21 <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">22</a>📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 23why, one step back23<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer">⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
line 24why, one step back24 <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 25why, one step back25<a href="https://pypi.org/project/typer">⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 26–31why, one step back26 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">27</a>28</p>2930---31📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 32why, one step back32**Documentation**: [https://typer.tiangolo.com](https://typer.tiangolo.com)⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
line 33why, one step back33📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 34why, one step back34**Source Code**: [https://github.com/fastapi/typer](https://github.com/fastapi/typer)⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 35–52why, one step back3536---3738Typer 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.3940It's also a command line tool to run scripts, automatically converting them to CLI applications.4142The key features are:4344* **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.45* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.46* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.47* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.48* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.49* **Run scripts**: Typer includes a `typer` command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.5051## FastAPI of CLIs52📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 53why, one step back53**Typer** is [FastAPI](https://fastapi.tiangolo.com)'s little sibling, it's the FastAPI of CLIs.⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 54–56why, one step back5455## Installation56📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 57why, one step back57Create and activate a [virtual environment](https://typer.tiangolo.com/virtual-environments/) and then install **Typer**:⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 58–362why, one step back5859<div class="termy">6061```console62$ pip install typer63---> 100%64Successfully installed typer rich shellingham65```6667</div>6869## Example7071### The absolute minimum7273* Create a file `main.py` with:7475```Python76def main(name: str):77 print(f"Hello {name}")78```7980This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.8182### Run it8384Run your application with the `typer` command:8586<div class="termy">8788```console89// Run your application90$ typer main.py run9192// You get a nice error, you are missing NAME93Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME94Try 'typer [PATH_OR_MODULE] run --help' for help.95╭─ Error ───────────────────────────────────────────╮96│ Missing argument 'NAME'. │97╰───────────────────────────────────────────────────╯9899100// You get a --help for free101$ typer main.py run --help102103Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME104105Run the provided Typer app.106107╭─ Arguments ───────────────────────────────────────╮108│ * name TEXT [default: None] [required] |109╰───────────────────────────────────────────────────╯110╭─ Options ─────────────────────────────────────────╮111│ --help Show this message and exit. │112╰───────────────────────────────────────────────────╯113114// Now pass the NAME argument115$ typer main.py run Camila116117Hello Camila118119// It works! 🎉120```121122</div>123124This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.125126**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.127128## Use Typer in your code129130Now let's start using Typer in your own code, update `main.py` with:131132```Python133import typer134135136def main(name: str):137 print(f"Hello {name}")138139140if __name__ == "__main__":141 typer.run(main)142```143144Now you could run it with Python directly:145146<div class="termy">147148```console149// Run your application150$ python main.py151152// You get a nice error, you are missing NAME153Usage: main.py [OPTIONS] NAME154Try 'main.py --help' for help.155╭─ Error ───────────────────────────────────────────╮156│ Missing argument 'NAME'. │157╰───────────────────────────────────────────────────╯158159160// You get a --help for free161$ python main.py --help162163Usage: main.py [OPTIONS] NAME164165╭─ Arguments ───────────────────────────────────────╮166│ * name TEXT [default: None] [required] |167╰───────────────────────────────────────────────────╯168╭─ Options ─────────────────────────────────────────╮169│ --help Show this message and exit. │170╰───────────────────────────────────────────────────╯171172// Now pass the NAME argument173$ python main.py Camila174175Hello Camila176177// It works! 🎉178```179180</div>181182**Note**: you can also call this same script with the `typer` command, but you don't need to.183184## Example upgrade185186This was the simplest example possible.187188Now let's see one a bit more complex.189190### An example with two subcommands191192Modify the file `main.py`.193194Create a `typer.Typer()` app, and create two subcommands with their parameters.195196```Python hl_lines="3 6 11 20"197import typer198199app = typer.Typer()200201202@app.command()203def hello(name: str):204 print(f"Hello {name}")205206207@app.command()208def goodbye(name: str, formal: bool = False):209 if formal:210 print(f"Goodbye Ms. {name}. Have a good day.")211 else:212 print(f"Bye {name}!")213214215if __name__ == "__main__":216 app()217```218219And that will:220221* Explicitly create a `typer.Typer` app.222 * The previous `typer.run` actually creates one implicitly for you.223* Add two subcommands with `@app.command()`.224* Execute the `app()` itself, as if it was a function (instead of `typer.run`).225226### Run the upgraded example227228Check the new help:229230<div class="termy">231232```console233$ python main.py --help234235 Usage: main.py [OPTIONS] COMMAND [ARGS]...236237╭─ Options ─────────────────────────────────────────╮238│ --install-completion Install completion │239│ for the current │240│ shell. │241│ --show-completion Show completion for │242│ the current shell, │243│ to copy it or │244│ customize the │245│ installation. │246│ --help Show this message │247│ and exit. │248╰───────────────────────────────────────────────────╯249╭─ Commands ────────────────────────────────────────╮250│ goodbye │251│ hello │252╰───────────────────────────────────────────────────╯253254// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion255256// You have 2 subcommands (the 2 functions): goodbye and hello257```258259</div>260261Now check the help for the `hello` command:262263<div class="termy">264265```console266$ python main.py hello --help267268 Usage: main.py hello [OPTIONS] NAME269270╭─ Arguments ───────────────────────────────────────╮271│ * name TEXT [default: None] [required] │272╰───────────────────────────────────────────────────╯273╭─ Options ─────────────────────────────────────────╮274│ --help Show this message and exit. │275╰───────────────────────────────────────────────────╯276```277278</div>279280And now check the help for the `goodbye` command:281282<div class="termy">283284```console285$ python main.py goodbye --help286287 Usage: main.py goodbye [OPTIONS] NAME288289╭─ Arguments ───────────────────────────────────────╮290│ * name TEXT [default: None] [required] │291╰───────────────────────────────────────────────────╯292╭─ Options ─────────────────────────────────────────╮293│ --formal --no-formal [default: no-formal] │294│ --help Show this message │295│ and exit. │296╰───────────────────────────────────────────────────╯297298// Automatic --formal and --no-formal for the bool option 🎉299```300301</div>302303Now you can try out the new command line application:304305<div class="termy">306307```console308// Use it with the hello command309310$ python main.py hello Camila311312Hello Camila313314// And with the goodbye command315316$ python main.py goodbye Camila317318Bye Camila!319320// And with --formal321322$ python main.py goodbye --formal Camila323324Goodbye Ms. Camila. Have a good day.325```326327</div>328329**Note**: If your app only has one command, by default the command name is **omitted** in usage: `python main.py Camila`. However, when there are multiple commands, you must **explicitly include the command name**: `python main.py hello Camila`. See [One or Multiple Commands](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/) for more details.330331### Recap332333In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.334335You do that with standard modern Python types.336337You don't have to learn a new syntax, the methods or classes of a specific library, etc.338339Just standard **Python**.340341For example, for an `int`:342343```Python344total: int345```346347or for a `bool` flag:348349```Python350force: bool351```352353And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.354355**You get**: great editor support, including **completion** and **type checks** everywhere.356357**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.358359For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.360361## Dependencies362➖ Vendor Click and streamline Typer's functionality and code base (#1774)Sofie Van Landeghembefore adoption1829d73
line 363why, one step back363**Typer** requires only a few dependencies (most are tiny):⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
line 364why, one step back364📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 365–366why, one step back365* [`rich`](https://rich.readthedocs.io/en/stable/index.html): to show nicely formatted errors automatically.366* [`shellingham`](https://github.com/sarugaku/shellingham): to automatically detect the current shell when installing completion.➖ Vendor Click and streamline Typer's functionality and code base (#1774)Sofie Van Landeghembefore adoption1829d73
lines 367–376why, one step back367* [`annotated-doc`](https://github.com/fastapi/annotated-doc): to generate documentation from Python type annotations.368* [`colorama`](https://github.com/tartley/colorama) (only on Windows): for producing colored terminal text on Windows.369370### Click code371372Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.373374Since version 0.26.0, Typer has vendored Click (included Click's source code internally, instead of installing it as a third party package) and has unified the code interactions between Typer and the embedded Click source code for easier maintainability in the future.375376Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 377–388why, one step back377378### `typer-slim`379380There used to be a slimmed-down version of Typer called `typer-slim`, which didn't include the dependencies `rich` and `shellingham`, nor the `typer` command.381382However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.383384If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.385386## License387388This project is licensed under the terms of the MIT license.