Typer — Build Python CLIs from Type Hints
Typer turns Python functions into CLI commands using only type hints. It is built on Click but removes the boilerplate — write a function, and Typer auto-generates parsing, help text, and shell completions.
这个资产会安全暂存
这个资产会先安全暂存。复制的指令会要求 Agent 读取暂存文件,并在激活脚本、MCP 配置或全局配置前先确认。
npx -y tokrepo@latest install 6942f03e-37b5-11f1-9bc6-00163e2b0d79 --target codex先暂存文件;激活前需要读取暂存 README 和安装计划。
What it is
Typer is a Python library that turns regular Python functions into command-line interface commands using only type hints. Built on top of Click, Typer removes the boilerplate of argument parsing, help text generation, and shell completion setup.
Typer is created by the same developer behind FastAPI. It follows the same philosophy: use standard Python type annotations to define the interface, and let the framework handle the rest.
How it saves time or tokens
Traditional CLI libraries like argparse require verbose argument definitions separate from the function logic. Typer eliminates this duplication. The function signature is the CLI definition. A single function with type-annotated parameters becomes a complete CLI command with help text, validation, and tab completion.
For AI agents generating CLI tools, Typer is the shortest path from a Python function to a working command. The type-hint-driven approach means LLMs can produce correct CLI code with minimal context.
How to use
- Install Typer:
pip install typer
- Write a function with type hints:
import typer
def greet(name: str, count: int = 1, formal: bool = False):
greeting = 'Good day' if formal else 'Hello'
for _ in range(count):
print(f'{greeting}, {name}')
if __name__ == '__main__':
typer.run(greet)
- Run it from the terminal:
python greet.py --name World --count 3 --formal
Typer auto-generates --help, validates types, and provides shell completion.
Example
import typer
app = typer.Typer()
@app.command()
def deploy(env: str = typer.Argument(..., help='Target environment'),
dry_run: bool = typer.Option(False, help='Preview without applying')):
if dry_run:
print(f'Would deploy to {env}')
else:
print(f'Deploying to {env}...')
@app.command()
def rollback(env: str, steps: int = 1):
print(f'Rolling back {steps} step(s) in {env}')
if __name__ == '__main__':
app()
This creates a CLI with deploy and rollback subcommands, each with typed arguments and auto-generated help.
Related on TokRepo
- AI Tools for Coding — AI tools that generate CLI applications
- AI Tools for Automation — Automation tools that pair with CLI workflows
Common pitfalls
- Forgetting that Typer requires Python 3.7+ for proper type hint support. Older Python versions will not work correctly with the annotation-driven approach.
- Not installing the
shellinghamandclick-completionextras for shell completion. Runpip install 'typer[all]'to get the full feature set. - Using mutable default arguments (like lists or dicts) as parameter defaults. Use
typer.Option(default_factory=list)instead to avoid shared state bugs. - Failing to review community discussions and changelogs before upgrading. Breaking changes in major versions can disrupt existing workflows. Pin versions in production and test upgrades in staging first.
常见问题
Typer is built on top of Click and uses it under the hood. The difference is the developer experience: Click requires decorators and explicit parameter definitions, while Typer infers everything from function signatures and type hints. Typer produces the same result with less code.
Yes. Use the typer.Typer() app object and decorate functions with @app.command(). Each decorated function becomes a subcommand. You can also nest Typer apps for complex CLI hierarchies with command groups.
Yes. Typer generates shell completion scripts for bash, zsh, fish, and PowerShell. Install with typer[all] and run the completion install command. Arguments, options, and even Enum values get tab-completed automatically.
Typer was created by Sebastian Ramirez, the same developer behind FastAPI. Both libraries share the philosophy of using Python type annotations to define interfaces and auto-generate documentation and validation.
Yes. Typer's type-hint-driven approach is well-suited for AI code generation. An LLM can produce a complete CLI tool by writing a single Python function with type annotations. The minimal boilerplate means fewer opportunities for generation errors.
引用来源 (3)
- Typer GitHub— Typer turns Python functions into CLI commands using type hints, built on Click
- Typer Documentation— Typer documentation and tutorial
- Python PEP 484— Python type hints PEP 484 specification
讨论
相关资产
HTTPX — The Next-Generation HTTP Client for Python
HTTPX provides the ergonomics of requests with the power of async, HTTP/2, and strict type safety. The same API works in sync and async code, making it the go-to client for modern Python applications.
pipx — Install and Run Python CLI Apps in Isolated Environments
pipx installs Python CLI tools (black, poetry, httpie, youtube-dl) into isolated venvs and exposes their commands globally. It eliminates the mess of mixing app dependencies into your system Python.
tqdm — Fast Extensible Progress Bars for Python and CLI
tqdm wraps any Python iterable to display a smart progress bar with speed, ETA, and throughput metrics. It works in terminals, notebooks, and GUI frameworks with zero overhead.
Python Fire — Auto-Generate CLIs from Any Python Object
Python Fire by Google turns any Python function, class, or module into a command-line interface with a single call. No decorators, no argument definitions — just code.