index.md
This file
Path
docs/index.md
385 lines · 14.2 KiB · Markdown
Last changed by
📝 Update docs badges: remove Publish badge, it doesn't give extra information (#1850)Sebastián Ramírezbefore adoption554b409
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://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer">⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
line 21why, one step back21 <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 22why, one step back22<a href="https://pypi.org/project/typer">⬆ Bump ty from 0.0.23 to 0.0.24 (#1646)dependabot[bot]before adoption3436fe6
lines 23–28why, one step back23 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">24</a>25</p>2627---28📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 29why, one step back29**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 30why, one step back30📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 31why, one step back31**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 32–49why, one step back3233---3435Typer 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.3637It's also a command line tool to run scripts, automatically converting them to CLI applications.3839The key features are:4041* **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.42* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.43* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.44* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.45* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.46* **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.4748## FastAPI of CLIs49📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 50why, one step back50**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 51–53why, one step back5152## Installation53📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 54why, one step back54Create 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 55–359why, one step back5556<div class="termy">5758```console59$ pip install typer60---> 100%61Successfully installed typer rich shellingham62```6364</div>6566## Example6768### The absolute minimum6970* Create a file `main.py` with:7172```Python73def main(name: str):74 print(f"Hello {name}")75```7677This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.7879### Run it8081Run your application with the `typer` command:8283<div class="termy">8485```console86// Run your application87$ typer main.py run8889// You get a nice error, you are missing NAME90Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME91Try 'typer [PATH_OR_MODULE] run --help' for help.92╭─ Error ───────────────────────────────────────────╮93│ Missing argument 'NAME'. │94╰───────────────────────────────────────────────────╯959697// You get a --help for free98$ typer main.py run --help99100Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME101102Run the provided Typer app.103104╭─ Arguments ───────────────────────────────────────╮105│ * name TEXT [default: None] [required] |106╰───────────────────────────────────────────────────╯107╭─ Options ─────────────────────────────────────────╮108│ --help Show this message and exit. │109╰───────────────────────────────────────────────────╯110111// Now pass the NAME argument112$ typer main.py run Camila113114Hello Camila115116// It works! 🎉117```118119</div>120121This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.122123**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.124125## Use Typer in your code126127Now let's start using Typer in your own code, update `main.py` with:128129```Python130import typer131132133def main(name: str):134 print(f"Hello {name}")135136137if __name__ == "__main__":138 typer.run(main)139```140141Now you could run it with Python directly:142143<div class="termy">144145```console146// Run your application147$ python main.py148149// You get a nice error, you are missing NAME150Usage: main.py [OPTIONS] NAME151Try 'main.py --help' for help.152╭─ Error ───────────────────────────────────────────╮153│ Missing argument 'NAME'. │154╰───────────────────────────────────────────────────╯155156157// You get a --help for free158$ python main.py --help159160Usage: main.py [OPTIONS] NAME161162╭─ Arguments ───────────────────────────────────────╮163│ * name TEXT [default: None] [required] |164╰───────────────────────────────────────────────────╯165╭─ Options ─────────────────────────────────────────╮166│ --help Show this message and exit. │167╰───────────────────────────────────────────────────╯168169// Now pass the NAME argument170$ python main.py Camila171172Hello Camila173174// It works! 🎉175```176177</div>178179**Note**: you can also call this same script with the `typer` command, but you don't need to.180181## Example upgrade182183This was the simplest example possible.184185Now let's see one a bit more complex.186187### An example with two subcommands188189Modify the file `main.py`.190191Create a `typer.Typer()` app, and create two subcommands with their parameters.192193```Python hl_lines="3 6 11 20"194import typer195196app = typer.Typer()197198199@app.command()200def hello(name: str):201 print(f"Hello {name}")202203204@app.command()205def goodbye(name: str, formal: bool = False):206 if formal:207 print(f"Goodbye Ms. {name}. Have a good day.")208 else:209 print(f"Bye {name}!")210211212if __name__ == "__main__":213 app()214```215216And that will:217218* Explicitly create a `typer.Typer` app.219 * The previous `typer.run` actually creates one implicitly for you.220* Add two subcommands with `@app.command()`.221* Execute the `app()` itself, as if it was a function (instead of `typer.run`).222223### Run the upgraded example224225Check the new help:226227<div class="termy">228229```console230$ python main.py --help231232 Usage: main.py [OPTIONS] COMMAND [ARGS]...233234╭─ Options ─────────────────────────────────────────╮235│ --install-completion Install completion │236│ for the current │237│ shell. │238│ --show-completion Show completion for │239│ the current shell, │240│ to copy it or │241│ customize the │242│ installation. │243│ --help Show this message │244│ and exit. │245╰───────────────────────────────────────────────────╯246╭─ Commands ────────────────────────────────────────╮247│ goodbye │248│ hello │249╰───────────────────────────────────────────────────╯250251// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion252253// You have 2 subcommands (the 2 functions): goodbye and hello254```255256</div>257258Now check the help for the `hello` command:259260<div class="termy">261262```console263$ python main.py hello --help264265 Usage: main.py hello [OPTIONS] NAME266267╭─ Arguments ───────────────────────────────────────╮268│ * name TEXT [default: None] [required] │269╰───────────────────────────────────────────────────╯270╭─ Options ─────────────────────────────────────────╮271│ --help Show this message and exit. │272╰───────────────────────────────────────────────────╯273```274275</div>276277And now check the help for the `goodbye` command:278279<div class="termy">280281```console282$ python main.py goodbye --help283284 Usage: main.py goodbye [OPTIONS] NAME285286╭─ Arguments ───────────────────────────────────────╮287│ * name TEXT [default: None] [required] │288╰───────────────────────────────────────────────────╯289╭─ Options ─────────────────────────────────────────╮290│ --formal --no-formal [default: no-formal] │291│ --help Show this message │292│ and exit. │293╰───────────────────────────────────────────────────╯294295// Automatic --formal and --no-formal for the bool option 🎉296```297298</div>299300Now you can try out the new command line application:301302<div class="termy">303304```console305// Use it with the hello command306307$ python main.py hello Camila308309Hello Camila310311// And with the goodbye command312313$ python main.py goodbye Camila314315Bye Camila!316317// And with --formal318319$ python main.py goodbye --formal Camila320321Goodbye Ms. Camila. Have a good day.322```323324</div>325326**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.327328### Recap329330In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.331332You do that with standard modern Python types.333334You don't have to learn a new syntax, the methods or classes of a specific library, etc.335336Just standard **Python**.337338For example, for an `int`:339340```Python341total: int342```343344or for a `bool` flag:345346```Python347force: bool348```349350And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.351352**You get**: great editor support, including **completion** and **type checks** everywhere.353354**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.355356For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.357358## Dependencies359➖ Vendor Click and streamline Typer's functionality and code base (#1774)Sofie Van Landeghembefore adoption1829d73
line 360why, one step back360**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 361why, one step back361📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 362–363why, one step back362* [`rich`](https://rich.readthedocs.io/en/stable/index.html): to show nicely formatted errors automatically.363* [`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 364–373why, one step back364* [`annotated-doc`](https://github.com/fastapi/annotated-doc): to generate documentation from Python type annotations.365* [`colorama`](https://github.com/tartley/colorama) (only on Windows): for producing colored terminal text on Windows.366367### Click code368369Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.370371Since 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.372373Note 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 374–385why, one step back374375### `typer-slim`376377There 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.378379However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.380381If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.382383## License384385This project is licensed under the terms of the MIT license.