Skip to content
Myr

index.md

This file

Path

docs/index.md

392 lines · 14.2 KiB · Markdown

Last changed by

📝 Clarify single-command vs multi-command behaviour in README (#1268)Morgen Pronkbefore adoptione4c28a4

History of this file

Take it

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

📝 Update release notesgithub-actionsbefore adoptioncdeb036

lines 1–326why, one step back
1<style>
2.md-content .md-typeset h1 { display: none; }3</style>45<p align="center">6 <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>7<!-- only-mkdocs -->8 <a href="https://typer.tiangolo.com"><img src="img/logo-margin/logo-margin-white-vector.svg#only-dark" alt="Typer"></a>9<!-- /only-mkdocs -->10</p>11<p align="center">12 <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>13</p>14<p align="center">15<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest" target="_blank">16 <img src="https://github.com/fastapi/typer/workflows/Test/badge.svg" alt="Test">17</a>18<a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank">19 <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">20</a>21<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank">22 <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">23<a href="https://pypi.org/project/typer" target="_blank">24 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">25</a>26</p>2728---2930**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>3132**Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>3334---3536Typer 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.3738It's also a command line tool to run scripts, automatically converting them to CLI applications.3940The key features are:4142* **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.43* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.44* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.45* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.46* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.47* **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.4849## FastAPI of CLIs5051**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.5253## Installation5455Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:5657<div class="termy">5859```console60$ pip install typer61---> 100%62Successfully installed typer rich shellingham63```6465</div>6667## Example6869### The absolute minimum7071* Create a file `main.py` with:7273```Python74def main(name: str):75 print(f"Hello {name}")76```7778This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.7980### Run it8182Run your application with the `typer` command:8384<div class="termy">8586```console87// Run your application88$ typer main.py run8990// You get a nice error, you are missing NAME91Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME92Try 'typer [PATH_OR_MODULE] run --help' for help.93╭─ Error ───────────────────────────────────────────╮94│ Missing argument 'NAME'. │95╰───────────────────────────────────────────────────╯969798// You get a --help for free99$ typer main.py run --help100101Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME102103Run the provided Typer app.104105╭─ Arguments ───────────────────────────────────────╮106│ * name TEXT [default: None] [required] |107╰───────────────────────────────────────────────────╯108╭─ Options ─────────────────────────────────────────╮109│ --help Show this message and exit. │110╰───────────────────────────────────────────────────╯111112// Now pass the NAME argument113$ typer main.py run Camila114115Hello Camila116117// It works! 🎉118```119120</div>121122This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.123124**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.125126## Use Typer in your code127128Now let's start using Typer in your own code, update `main.py` with:129130```Python131import typer132133134def main(name: str):135 print(f"Hello {name}")136137138if __name__ == "__main__":139 typer.run(main)140```141142Now you could run it with Python directly:143144<div class="termy">145146```console147// Run your application148$ python main.py149150// You get a nice error, you are missing NAME151Usage: main.py [OPTIONS] NAME152Try 'main.py --help' for help.153╭─ Error ───────────────────────────────────────────╮154│ Missing argument 'NAME'. │155╰───────────────────────────────────────────────────╯156157158// You get a --help for free159$ python main.py --help160161Usage: main.py [OPTIONS] NAME162163╭─ Arguments ───────────────────────────────────────╮164│ * name TEXT [default: None] [required] |165╰───────────────────────────────────────────────────╯166╭─ Options ─────────────────────────────────────────╮167│ --help Show this message and exit. │168╰───────────────────────────────────────────────────╯169170// Now pass the NAME argument171$ python main.py Camila172173Hello Camila174175// It works! 🎉176```177178</div>179180**Note**: you can also call this same script with the `typer` command, but you don't need to.181182## Example upgrade183184This was the simplest example possible.185186Now let's see one a bit more complex.187188### An example with two subcommands189190Modify the file `main.py`.191192Create a `typer.Typer()` app, and create two subcommands with their parameters.193194```Python hl_lines="3 6 11 20"195import typer196197app = typer.Typer()198199200@app.command()201def hello(name: str):202 print(f"Hello {name}")203204205@app.command()206def goodbye(name: str, formal: bool = False):207 if formal:208 print(f"Goodbye Ms. {name}. Have a good day.")209 else:210 print(f"Bye {name}!")211212213if __name__ == "__main__":214 app()215```216217And that will:218219* Explicitly create a `typer.Typer` app.220 * The previous `typer.run` actually creates one implicitly for you.221* Add two subcommands with `@app.command()`.222* Execute the `app()` itself, as if it was a function (instead of `typer.run`).223224### Run the upgraded example225226Check the new help:227228<div class="termy">229230```console231$ python main.py --help232233 Usage: main.py [OPTIONS] COMMAND [ARGS]...234235╭─ Options ─────────────────────────────────────────╮236│ --install-completion Install completion │237│ for the current │238│ shell. │239│ --show-completion Show completion for │240│ the current shell, │241│ to copy it or │242│ customize the │243│ installation. │244│ --help Show this message │245│ and exit. │246╰───────────────────────────────────────────────────╯247╭─ Commands ────────────────────────────────────────╮248│ goodbye │249│ hello │250╰───────────────────────────────────────────────────╯251252// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion253254// You have 2 subcommands (the 2 functions): goodbye and hello255```256257</div>258259Now check the help for the `hello` command:260261<div class="termy">262263```console264$ python main.py hello --help265266 Usage: main.py hello [OPTIONS] NAME267268╭─ Arguments ───────────────────────────────────────╮269│ * name TEXT [default: None] [required] │270╰───────────────────────────────────────────────────╯271╭─ Options ─────────────────────────────────────────╮272│ --help Show this message and exit. │273╰───────────────────────────────────────────────────╯274```275276</div>277278And now check the help for the `goodbye` command:279280<div class="termy">281282```console283$ python main.py goodbye --help284285 Usage: main.py goodbye [OPTIONS] NAME286287╭─ Arguments ───────────────────────────────────────╮288│ * name TEXT [default: None] [required] │289╰───────────────────────────────────────────────────╯290╭─ Options ─────────────────────────────────────────╮291│ --formal --no-formal [default: no-formal] │292│ --help Show this message │293│ and exit. │294╰───────────────────────────────────────────────────╯295296// Automatic --formal and --no-formal for the bool option 🎉297```298299</div>300301Now you can try out the new command line application:302303<div class="termy">304305```console306// Use it with the hello command307308$ python main.py hello Camila309310Hello Camila311312// And with the goodbye command313314$ python main.py goodbye Camila315316Bye Camila!317318// And with --formal319320$ python main.py goodbye --formal Camila321322Goodbye Ms. Camila. Have a good day.323```324325</div>326

📝 Clarify single-command vs multi-command behaviour in README (#1268)Morgen Pronkbefore adoptione4c28a4

lines 327–328why, one step back
327**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.
328

📝 Update release notesgithub-actionsbefore adoptioncdeb036

lines 329–392why, one step back
329### Recap
330331In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.332333You do that with standard modern Python types.334335You don't have to learn a new syntax, the methods or classes of a specific library, etc.336337Just standard **Python**.338339For example, for an `int`:340341```Python342total: int343```344345or for a `bool` flag:346347```Python348force: bool349```350351And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.352353**You get**: great editor support, including **completion** and **type checks** everywhere.354355**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.356357For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.358359## Dependencies360361**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>.362363By default it also comes with extra standard dependencies:364365* <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.366* <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.367 * With `shellingham` you can just use `--install-completion`.368 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.369370### `typer-slim`371372If you don't want the extra standard optional dependencies, install `typer-slim` instead.373374When you install with:375376```bash377pip install typer378```379380...it includes the same code and dependencies as:381382```bash383pip install "typer-slim[standard]"384```385386The `standard` extra dependencies are `rich` and `shellingham`.387388**Note**: The `typer` command is only included in the `typer` package.389390## License391392This project is licensed under the terms of the MIT license.