Skip to content
Myr

README.md

This file

Path

README.md

377 lines · 13.9 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 file

Take it

The walk stopped after 200 commits: lines older than 0de0e8b point at it.

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 1–8why, one step back
1<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">

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

line 9why, one step back
9<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster">

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 10–11why, one step back
10 <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">
11</a>

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

line 12why, one step back
12<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer">

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

line 13why, one step back
13 <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 14why, one step back
14<a href="https://pypi.org/project/typer">

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 15–20why, one step back
15 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">
16</a>17</p>1819---20

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

line 21why, one step back
21**Documentation**: [https://typer.tiangolo.com](https://typer.tiangolo.com)

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

line 22why, one step back
22

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

line 23why, one step back
23**Source Code**: [https://github.com/fastapi/typer](https://github.com/fastapi/typer)

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 24–41why, one step back
24
25---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 CLIs41

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

line 42why, one step back
42**Typer** is [FastAPI](https://fastapi.tiangolo.com)'s little sibling, it's the FastAPI of CLIs.

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 43–45why, one step back
43
44## Installation45

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

line 46why, one step back
46Create and activate a [virtual environment](https://typer.tiangolo.com/virtual-environments/) and then install **Typer**:

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 47–351why, one step back
47
48<div class="termy">4950```console51$ pip install typer52---> 100%53Successfully installed typer rich shellingham54```5556</div>5758## Example5960### The absolute minimum6162* Create a file `main.py` with:6364```Python65def main(name: str):66 print(f"Hello {name}")67```6869This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.7071### Run it7273Run your application with the `typer` command:7475<div class="termy">7677```console78// Run your application79$ typer main.py run8081// You get a nice error, you are missing NAME82Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME83Try 'typer [PATH_OR_MODULE] run --help' for help.84╭─ Error ───────────────────────────────────────────╮85│ Missing argument 'NAME'. │86╰───────────────────────────────────────────────────╯878889// You get a --help for free90$ typer main.py run --help9192Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME9394Run the provided Typer app.9596╭─ Arguments ───────────────────────────────────────╮97│ * name TEXT [default: None] [required] |98╰───────────────────────────────────────────────────╯99╭─ Options ─────────────────────────────────────────╮100│ --help Show this message and exit. │101╰───────────────────────────────────────────────────╯102103// Now pass the NAME argument104$ typer main.py run Camila105106Hello Camila107108// It works! 🎉109```110111</div>112113This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.114115**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.116117## Use Typer in your code118119Now let's start using Typer in your own code, update `main.py` with:120121```Python122import typer123124125def main(name: str):126 print(f"Hello {name}")127128129if __name__ == "__main__":130 typer.run(main)131```132133Now you could run it with Python directly:134135<div class="termy">136137```console138// Run your application139$ python main.py140141// You get a nice error, you are missing NAME142Usage: main.py [OPTIONS] NAME143Try 'main.py --help' for help.144╭─ Error ───────────────────────────────────────────╮145│ Missing argument 'NAME'. │146╰───────────────────────────────────────────────────╯147148149// You get a --help for free150$ python main.py --help151152Usage: main.py [OPTIONS] NAME153154╭─ Arguments ───────────────────────────────────────╮155│ * name TEXT [default: None] [required] |156╰───────────────────────────────────────────────────╯157╭─ Options ─────────────────────────────────────────╮158│ --help Show this message and exit. │159╰───────────────────────────────────────────────────╯160161// Now pass the NAME argument162$ python main.py Camila163164Hello Camila165166// It works! 🎉167```168169</div>170171**Note**: you can also call this same script with the `typer` command, but you don't need to.172173## Example upgrade174175This was the simplest example possible.176177Now let's see one a bit more complex.178179### An example with two subcommands180181Modify the file `main.py`.182183Create a `typer.Typer()` app, and create two subcommands with their parameters.184185```Python hl_lines="3 6 11 20"186import typer187188app = typer.Typer()189190191@app.command()192def hello(name: str):193 print(f"Hello {name}")194195196@app.command()197def goodbye(name: str, formal: bool = False):198 if formal:199 print(f"Goodbye Ms. {name}. Have a good day.")200 else:201 print(f"Bye {name}!")202203204if __name__ == "__main__":205 app()206```207208And that will:209210* Explicitly create a `typer.Typer` app.211 * The previous `typer.run` actually creates one implicitly for you.212* Add two subcommands with `@app.command()`.213* Execute the `app()` itself, as if it was a function (instead of `typer.run`).214215### Run the upgraded example216217Check the new help:218219<div class="termy">220221```console222$ python main.py --help223224 Usage: main.py [OPTIONS] COMMAND [ARGS]...225226╭─ Options ─────────────────────────────────────────╮227│ --install-completion Install completion │228│ for the current │229│ shell. │230│ --show-completion Show completion for │231│ the current shell, │232│ to copy it or │233│ customize the │234│ installation. │235│ --help Show this message │236│ and exit. │237╰───────────────────────────────────────────────────╯238╭─ Commands ────────────────────────────────────────╮239│ goodbye │240│ hello │241╰───────────────────────────────────────────────────╯242243// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion244245// You have 2 subcommands (the 2 functions): goodbye and hello246```247248</div>249250Now check the help for the `hello` command:251252<div class="termy">253254```console255$ python main.py hello --help256257 Usage: main.py hello [OPTIONS] NAME258259╭─ Arguments ───────────────────────────────────────╮260│ * name TEXT [default: None] [required] │261╰───────────────────────────────────────────────────╯262╭─ Options ─────────────────────────────────────────╮263│ --help Show this message and exit. │264╰───────────────────────────────────────────────────╯265```266267</div>268269And now check the help for the `goodbye` command:270271<div class="termy">272273```console274$ python main.py goodbye --help275276 Usage: main.py goodbye [OPTIONS] NAME277278╭─ Arguments ───────────────────────────────────────╮279│ * name TEXT [default: None] [required] │280╰───────────────────────────────────────────────────╯281╭─ Options ─────────────────────────────────────────╮282│ --formal --no-formal [default: no-formal] │283│ --help Show this message │284│ and exit. │285╰───────────────────────────────────────────────────╯286287// Automatic --formal and --no-formal for the bool option 🎉288```289290</div>291292Now you can try out the new command line application:293294<div class="termy">295296```console297// Use it with the hello command298299$ python main.py hello Camila300301Hello Camila302303// And with the goodbye command304305$ python main.py goodbye Camila306307Bye Camila!308309// And with --formal310311$ python main.py goodbye --formal Camila312313Goodbye Ms. Camila. Have a good day.314```315316</div>317318**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.319320### Recap321322In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.323324You do that with standard modern Python types.325326You don't have to learn a new syntax, the methods or classes of a specific library, etc.327328Just standard **Python**.329330For example, for an `int`:331332```Python333total: int334```335336or for a `bool` flag:337338```Python339force: bool340```341342And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.343344**You get**: great editor support, including **completion** and **type checks** everywhere.345346**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.347348For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.349350## Dependencies351

➖ Vendor Click and streamline Typer's functionality and code base (#1774)Sofie Van Landeghembefore adoption1829d73

line 352why, one step back
352**Typer** requires only a few dependencies (most are tiny):

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

line 353why, one step back
353

📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29

lines 354–355why, one step back
354* [`rich`](https://rich.readthedocs.io/en/stable/index.html): to show nicely formatted errors automatically.
355* [`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 356–365why, one step back
356* [`annotated-doc`](https://github.com/fastapi/annotated-doc): to generate documentation from Python type annotations.
357* [`colorama`](https://github.com/tartley/colorama) (only on Windows): for producing colored terminal text on Windows.358359### Click code360361Typer used to depend on [Click](https://click.palletsprojects.com/) as well, a popular tool for building CLIs in Python.362363Since 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.364365Note that some Click functionality will not be available anymore in the future, as we continue to improve and extend Typer's codebase.

📝 Update release notesgithub-actions[bot]before adoption0de0e8b

lines 366–377why, one step back
366
367### `typer-slim`368369There 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.370371However, since version 0.22.0, we have stopped supporting this, and `typer-slim` now simply installs (all of) Typer.372373If you want to disable Rich globally, you can set an environmental variable `TYPER_USE_RICH` to `False` or `0`.374375## License376377This project is licensed under the terms of the MIT license.