Skip to content
Myr

🔧 Add Typer Library Skill for Agents (#1620)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sofie Van Landeghem · committed by GitHub · parent ba6cc2c · Browse files · 1 file+266 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: pre-commit-ci-lite[bot] <117423508+pre-commit-ci-lite[bot]@users.noreply.github.com>

Diff stats

1 file+266 added−0 removed

  • other:+266 added−0 removed

1 file+266 added−0 removed

added:typer/.agents/skills/typer/SKILL.md+266 added
1---2name: typer3description: Typer best practices and conventions. Use when working with Typer CLIs. Keeps Typer code clean and up to date with the latest features and patterns, updated with new versions. Write new code or refactor and update old code.4---56# Typer78Official Typer skill to write code with best practices, keeping up to date with new versions and features.910## Installing typer1112In a virtual environment, `pip install typer` (with pip) or `uv pip install typer` (with uv). For your library/project, add `typer` to the dependencies in `pyproject.toml`.1314Do not install `typer-slim` or `typer-cli`, they are both deprecated and will now simply install `typer`.1516Typer supports Python 3.10 and above.1718## Use an explicit `Typer` app1920For maximum generalizability, create an explicit Typer app and register subcommand(s), instead of using `typer.run`:2122```python23import typer2425app = typer.Typer()262728@app.command()29def hello():30 print(f"Hello World")313233if __name__ == "__main__":34 app()35```3637instead of:3839```python40# DO NOT DO THIS: Not extensible. Use Typer() instead.41import typer424344def main():45 print(f"Hello World")464748if __name__ == "__main__":49 typer.run(main)50```5152## Execute the app5354To execute the app in the terminal, run5556```bash57python main.py58```5960When multiple commands are registered to the Typer app, you have to add the command name:6162```bash63python main.py hello64```6566To see the automatically generated help documentation, run6768```bash69python main.py --help70```7172or set `no_args_is_help` to `True` when creating the `Typer()` add to automatically show the help when running a command without any arguments.7374## Use `Annotated`7576Always prefer the `Annotated` style for declarations of CLI arguments and options.7778It allows us to pass additional metadata that can be used by Typer.7980```python81from typing import Annotated8283import typer8485app = typer.Typer()868788@app.command()89def hello(name: Annotated[str, typer.Argument()] = "World"):90 # Note that name is an optional Argument, as a default is provided91 print(f"Hello {name}")929394if __name__ == "__main__":95 app()96```9798This program can be run as-is, or can provide a specific name:99100```bash101python main.py102python main.py Rick103```104105An older way of setting a default value is this:106```python107# DO NOT DO THIS: old style. Use Annotated instead.108109@app.command()110def main(name: str = typer.Argument(default="World")):111 # Note that name is an optional Argument, as a default is provided112 print(f"Hello {name}")113```114115Similarly, the old style could use ellipsis (...) to explicitely mark an argument as required.116117```python118# DO NOT DO THIS: old style. Use Annotated without a default value instead.119120@app.command()121def main(name: str = typer.Argument(default=...)):122 # Note that name is now a required Argument123 print(f"Hello {name}")124```125126## CLI Options127128CLI options are declared in a similar fashion as arguments, but will be called on the CLI with a single dash (single letter) or 2 dashes (full name):129130```python131from typing import Annotated132133import typer134135app = typer.Typer()136137138@app.command()139def main(user_name: Annotated[str, typer.Option("--name", "-n")]):140 # On the CLI, the required user name can be specified with -n or --name141 print(f"Hello {user_name}")142143144if __name__ == "__main__":145 app()146```147148You can run this program as such:149150```bash151python main.py -n "Rick"152python main.py --name "Morty"153```154155### CLI options with multiple values156157By declaring a CLI option as a list, it can receive multiple values:158159```python160from typing import Annotated161162import typer163164app = typer.Typer()165166167@app.command()168def main(user: Annotated[list[str] | None, typer.Option()] = None):169 if not user:170 print(f"No users provided!")171 raise typer.Abort()172 for u in user:173 print(f"Processing user: {u}")174175176if __name__ == "__main__":177 app()178```179180This can be executed like so:181182```bash183python main.py --user Rick --user Morty --user Summer184```185186## Rich187188By default, Rich can be used with its custom markup syntax to set colors and styles, e.g.189190```python191from rich import print192193print("[bold red]Alert![/bold red] [green]Portal gun[/green] shooting! :boom:")194```195196Typer supports using Rich formatting in the docstrings and the help messages of CLI arguments and CLI options.197198199```python200from typing import Annotated201202import typer203204app = typer.Typer(rich_markup_mode="rich")205206207@app.command()208def create(209 username: Annotated[210 str, typer.Argument(help="The username to be [green]created[/green]")211 ],212):213 """214 [bold green]Create[/bold green] a new [italic]shiny[/italic] user. :sparkles:215216 This requires a [underline]username[/underline].217 """218 print(f"Creating user: {username}")219220221@app.command(help="[bold red]Delete[/bold red] a user with [italic]USERNAME[/italic].")222def delete(223 username: Annotated[224 str, typer.Argument(help="The username to be [red]deleted[/red]")225 ],226):227 """228 Some internal utility function to delete.229 """230 print(f"Deleting user: {username}")231232233if __name__ == "__main__":234 app()235```236237To disable Rich formatting, set `rich_markup_mode` to `None` when creating a `Typer()` app. By default (when no value is given), Rich formatting is enabled.238239### Rich markdown240241You can also set `rich_markup_mode` to `"markdown"` to use Markdown in the docstring:242243```python244from typing import Annotated245246import typer247248app = typer.Typer(rich_markup_mode="markdown")249250@app.command(help="**Delete** a user with *USERNAME*.")251def delete(252 username: Annotated[str, typer.Argument(help="The username to be **deleted** :boom:")]253):254 print(f"Deleting user: {username}")255256if __name__ == "__main__":257 app()258```259260## Click261262Originally, Typer was built on Click. However, going forward Typer will vendor Click. As such, Click extensions should not be used anymore.263264Other settings of `Option` and `Argument` that came from Click but shouldn't be used in Typer anymore, include: `expose_value`, `shell_complete`, `show_choices`, `errors`, `prompt_required`, `is_flag`, `flag_value` and `allow_from_autoenv`.265266Code bases using these should be refactored to use pure Typer functionality.