README.md
This file
Path
README.md
380 lines · 14.4 KiB · Markdown
Last changed by
📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
History of this fileTake it
The walk stopped after 200 commits: lines older than 3780a29 point at it.
📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 1–45why, one step back1<p align="center">2 <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>34</p>5<p align="center">6 <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>7</p>8<p align="center">9<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster">10 <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">11</a>12<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer">13 <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">14<a href="https://pypi.org/project/typer">15 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">16</a>17</p>1819---2021**Documentation**: [https://typer.tiangolo.com](https://typer.tiangolo.com)2223**Source Code**: [https://github.com/fastapi/typer](https://github.com/fastapi/typer)2425---2627Typer 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.2829It's also a command line tool to run scripts, automatically converting them to CLI applications.3031The key features are:3233* **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.34* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.35* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.38* **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.3940## FastAPI of CLIs4142**Typer** is [FastAPI](https://fastapi.tiangolo.com)'s little sibling, it's the FastAPI of CLIs.4344## Installation45📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 46why, one step back46First, [install `uv`](https://docs.astral.sh/uv/getting-started/installation/), and then add **Typer** to your project:📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 47–50why, one step back4748<div class="termy">4950```console📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 51why, one step back51$ uv add typer📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 52–56why, one step back52---> 100%53```5455</div>56📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
lines 57–60why, one step back57This installs both the Typer library and the `typer` command in the project's virtual environment. To use `typer` directly with shell completion, [activate the project environment and install completion](tutorial/install.md#activate-the-virtual-environment).5859If you prefer to use `pip`, install `typer` inside a virtual environment. See the [installation guide](tutorial/install.md) for the alternative steps.60📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 61–83why, one step back61## Example6263### The absolute minimum6465* Create a file `main.py` with:6667```Python68def main(name: str):69 print(f"Hello {name}")70```7172This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.7374### Run it7576Run your application with the `typer` command:7778<div class="termy">7980```console81// Run your application82$ typer main.py run83💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
lines 84–85why, one step back84// You get a nice error, you are missing 'name'85Usage: typer [PATH_OR_MODULE] run [OPTIONS] {name}📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 86–87why, one step back86Try 'typer [PATH_OR_MODULE] run --help' for help.87╭─ Error ───────────────────────────────────────────╮💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 88why, one step back88│ Missing argument 'name'. │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 89–94why, one step back89╰───────────────────────────────────────────────────╯909192// You get a --help for free93$ typer main.py run --help94💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 95why, one step back95Usage: typer [PATH_OR_MODULE] run [OPTIONS] {name}📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 96–99why, one step back9697Run the provided Typer app.9899╭─ Arguments ───────────────────────────────────────╮💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 100why, one step back100│ * name <str> [required] │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 101–105why, one step back101╰───────────────────────────────────────────────────╯102╭─ Options ─────────────────────────────────────────╮103│ --help Show this message and exit. │104╰───────────────────────────────────────────────────╯105💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 106why, one step back106// Now pass the 'name' argument📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 107–141why, one step back107$ typer main.py run Camila108109Hello Camila110111// It works! 🎉112```113114</div>115116This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.117118**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.119120## Use Typer in your code121122Now let's start using Typer in your own code, update `main.py` with:123124```Python125import typer126127128def main(name: str):129 print(f"Hello {name}")130131132if __name__ == "__main__":133 typer.run(main)134```135136Now you could run it with Python directly:137138<div class="termy">139140```console141// Run your application📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 142why, one step back142$ uv run python main.py📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 143why, one step back143💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
lines 144–145why, one step back144// You get a nice error, you are missing 'name'145Usage: main.py [OPTIONS] {name}📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 146–147why, one step back146Try 'main.py --help' for help.147╭─ Error ───────────────────────────────────────────╮💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 148why, one step back148│ Missing argument 'name'. │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 149–152why, one step back149╰───────────────────────────────────────────────────╯150151152// You get a --help for free📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 153why, one step back153$ uv run python main.py --help📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 154why, one step back154💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 155why, one step back155Usage: main.py [OPTIONS] {name}📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 156–157why, one step back156157╭─ Arguments ───────────────────────────────────────╮💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 158why, one step back158│ * name <str> [required] │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 159–163why, one step back159╰───────────────────────────────────────────────────╯160╭─ Options ─────────────────────────────────────────╮161│ --help Show this message and exit. │162╰───────────────────────────────────────────────────╯163💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 164why, one step back164// Now pass the 'name' argument📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 165why, one step back165$ uv run python main.py Camila📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 166–224why, one step back166167Hello Camila168169// It works! 🎉170```171172</div>173174**Note**: you can also call this same script with the `typer` command, but you don't need to.175176## Example upgrade177178This was the simplest example possible.179180Now let's see one a bit more complex.181182### An example with two subcommands183184Modify the file `main.py`.185186Create a `typer.Typer()` app, and create two subcommands with their parameters.187188```Python hl_lines="3 6 11 20"189import typer190191app = typer.Typer()192193194@app.command()195def hello(name: str):196 print(f"Hello {name}")197198199@app.command()200def goodbye(name: str, formal: bool = False):201 if formal:202 print(f"Goodbye Ms. {name}. Have a good day.")203 else:204 print(f"Bye {name}!")205206207if __name__ == "__main__":208 app()209```210211And that will:212213* Explicitly create a `typer.Typer` app.214 * The previous `typer.run` actually creates one implicitly for you.215* Add two subcommands with `@app.command()`.216* Execute the `app()` itself, as if it was a function (instead of `typer.run`).217218### Run the upgraded example219220Check the new help:221222<div class="termy">223224```console📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 225why, one step back225$ uv run python main.py --help📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 226–242why, one step back226227 Usage: main.py [OPTIONS] COMMAND [ARGS]...228229╭─ Options ─────────────────────────────────────────╮230│ --install-completion Install completion │231│ for the current │232│ shell. │233│ --show-completion Show completion for │234│ the current shell, │235│ to copy it or │236│ customize the │237│ installation. │238│ --help Show this message │239│ and exit. │240╰───────────────────────────────────────────────────╯241╭─ Commands ────────────────────────────────────────╮242│ hello │💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 243why, one step back243│ goodbye │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 244–247why, one step back244╰───────────────────────────────────────────────────╯245246// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion247💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 248why, one step back248// You have 2 subcommands (the 2 functions): hello and goodbye📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 249–257why, one step back249```250251</div>252253Now check the help for the `hello` command:254255<div class="termy">256257```console📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 258why, one step back258$ uv run python main.py hello --help📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 259why, one step back259💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 260why, one step back260 Usage: main.py hello [OPTIONS] {name}📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 261–262why, one step back261262╭─ Arguments ───────────────────────────────────────╮💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 263why, one step back263│ * name <str> [required] │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 264–276why, one step back264╰───────────────────────────────────────────────────╯265╭─ Options ─────────────────────────────────────────╮266│ --help Show this message and exit. │267╰───────────────────────────────────────────────────╯268```269270</div>271272And now check the help for the `goodbye` command:273274<div class="termy">275276```console📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 277why, one step back277$ uv run python main.py goodbye --help📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 278why, one step back278💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 279why, one step back279 Usage: main.py goodbye [OPTIONS] {name}📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 280–281why, one step back280281╭─ Arguments ───────────────────────────────────────╮💥 Update metavar printing (#1863)Sofie Van Landeghembefore adoption42196d4
line 282why, one step back282│ * name <str> [required] │📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 283–301why, one step back283╰───────────────────────────────────────────────────╯284╭─ Options ─────────────────────────────────────────╮285│ --formal --no-formal [default: no-formal] │286│ --help Show this message │287│ and exit. │288╰───────────────────────────────────────────────────╯289290// Automatic --formal and --no-formal for the bool option 🎉291```292293</div>294295Now you can try out the new command line application:296297<div class="termy">298299```console300// Use it with the hello command301📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 302why, one step back302$ uv run python main.py hello Camila📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 303–307why, one step back303304Hello Camila305306// And with the goodbye command307📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 308why, one step back308$ uv run python main.py goodbye Camila📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 309–313why, one step back309310Bye Camila!311312// And with --formal313📝 Recommend uv projects by default in docs (#1903)Sebastián Ramírezbefore adoptione60a33e
line 314why, one step back314$ uv run python main.py goodbye --formal Camila📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 315–354why, one step back315316Goodbye Ms. Camila. Have a good day.317```318319</div>320321**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.322323### Recap324325In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.326327You do that with standard modern Python types.328329You don't have to learn a new syntax, the methods or classes of a specific library, etc.330331Just standard **Python**.332333For example, for an `int`:334335```Python336total: int337```338339or for a `bool` flag:340341```Python342force: bool343```344345And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.346347**You get**: great editor support, including **completion** and **type checks** everywhere.348349**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.350351For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.352353## Dependencies354➖ Vendor Click and streamline Typer's functionality and code base (#1774)Sofie Van Landeghembefore adoption1829d73
line 355why, one step back355**Typer** requires only a few dependencies (most are tiny):📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 356–358why, one step back356357* [`rich`](https://rich.readthedocs.io/en/stable/index.html): to show nicely formatted errors automatically.358* [`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 359–368why, one step back359* [`annotated-doc`](https://github.com/fastapi/annotated-doc): to generate documentation from Python type annotations.360* [`colorama`](https://github.com/tartley/colorama) (only on Windows): for producing colored terminal text on Windows.361362### Click code363364Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.365366Since 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.367368Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 369–380why, one step back369370### `typer-slim`371372There 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.373374However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.375376If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.377378## License379380This project is licensed under the terms of the MIT license.