README.md
This file
Path
README.md
380 lines · 14.1 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 0de0e8b point at it.
📝 Update release notesgithub-actions[bot]before adoption0de0e8b
lines 1–8why, 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">📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 9why, one step back9<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 back10 <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 back12<a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish">📝 Update release notesgithub-actions[bot]before adoption0de0e8b
lines 13–14why, one step back13 <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">14</a>📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 15why, one step back15<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer">📝 Update release notesgithub-actions[bot]before adoption0de0e8b
line 16why, one step back16 <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 17why, one step back17<a href="https://pypi.org/project/typer">📝 Update release notesgithub-actions[bot]before adoption0de0e8b
lines 18–23why, one step back18 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">19</a>20</p>2122---23📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 24why, one step back24**Documentation**: [https://typer.tiangolo.com](https://typer.tiangolo.com)📝 Update release notesgithub-actions[bot]before adoption0de0e8b
line 25why, one step back25📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 26why, one step back26**Source Code**: [https://github.com/fastapi/typer](https://github.com/fastapi/typer)📝 Update release notesgithub-actions[bot]before adoption0de0e8b
lines 27–44why, one step back2728---2930Typer 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.3132It's also a command line tool to run scripts, automatically converting them to CLI applications.3334The key features are:3536* **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.37* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.38* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.39* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.40* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.41* **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.4243## FastAPI of CLIs44📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 45why, one step back45**Typer** is [FastAPI](https://fastapi.tiangolo.com)'s little sibling, it's the FastAPI of CLIs.📝 Update release notesgithub-actions[bot]before adoption0de0e8b
lines 46–48why, one step back4647## Installation48📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
line 49why, one step back49Create and activate a [virtual environment](https://typer.tiangolo.com/virtual-environments/) and then install **Typer**:📝 Update release notesgithub-actions[bot]before adoption0de0e8b
lines 50–354why, one step back5051<div class="termy">5253```console54$ pip install typer55---> 100%56Successfully installed typer rich shellingham57```5859</div>6061## 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 run8384// You get a nice error, you are missing NAME85Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME86Try 'typer [PATH_OR_MODULE] run --help' for help.87╭─ Error ───────────────────────────────────────────╮88│ Missing argument 'NAME'. │89╰───────────────────────────────────────────────────╯909192// You get a --help for free93$ typer main.py run --help9495Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME9697Run the provided Typer app.9899╭─ Arguments ───────────────────────────────────────╮100│ * name TEXT [default: None] [required] |101╰───────────────────────────────────────────────────╯102╭─ Options ─────────────────────────────────────────╮103│ --help Show this message and exit. │104╰───────────────────────────────────────────────────╯105106// Now pass the NAME argument107$ 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 application142$ python main.py143144// You get a nice error, you are missing NAME145Usage: main.py [OPTIONS] NAME146Try 'main.py --help' for help.147╭─ Error ───────────────────────────────────────────╮148│ Missing argument 'NAME'. │149╰───────────────────────────────────────────────────╯150151152// You get a --help for free153$ python main.py --help154155Usage: main.py [OPTIONS] NAME156157╭─ Arguments ───────────────────────────────────────╮158│ * name TEXT [default: None] [required] |159╰───────────────────────────────────────────────────╯160╭─ Options ─────────────────────────────────────────╮161│ --help Show this message and exit. │162╰───────────────────────────────────────────────────╯163164// Now pass the NAME argument165$ python main.py Camila166167Hello 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```console225$ python main.py --help226227 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│ goodbye │243│ hello │244╰───────────────────────────────────────────────────╯245246// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion247248// You have 2 subcommands (the 2 functions): goodbye and hello249```250251</div>252253Now check the help for the `hello` command:254255<div class="termy">256257```console258$ python main.py hello --help259260 Usage: main.py hello [OPTIONS] NAME261262╭─ Arguments ───────────────────────────────────────╮263│ * name TEXT [default: None] [required] │264╰───────────────────────────────────────────────────╯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```console277$ python main.py goodbye --help278279 Usage: main.py goodbye [OPTIONS] NAME280281╭─ Arguments ───────────────────────────────────────╮282│ * name TEXT [default: None] [required] │283╰───────────────────────────────────────────────────╯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 command301302$ python main.py hello Camila303304Hello Camila305306// And with the goodbye command307308$ python main.py goodbye Camila309310Bye Camila!311312// And with --formal313314$ python main.py goodbye --formal Camila315316Goodbye 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 release notesgithub-actions[bot]before adoption0de0e8b
line 356why, one step back356📝 Update link syntax to minimal Markdown (#1623)Sebastián Ramírezbefore adoption3780a29
lines 357–358why, one step back357* [`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 release notesgithub-actions[bot]before adoption0de0e8b
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.