Typer builds CLI apps from type-annotated Python functions. pip install typer[all]. import typer. App: app = typer.Typer(). Command: @app.command(). def greet(name: str, count: int = typer.Option(1, "--count", "-c", help="Times to greet"), loud: bool = False): typer.echo(f"Hello {name}"). Run: if __name__=="__main__": app(). Option: typer.Option(default, "--flag", "-f", help="...", show_default=True, envvar="MY_VAR"). Argument: typer.Argument(..., help="Required positional arg"). Types: Path, Enum, List[str], Optional[str] all work automatically. Required: use ... as default. Colored output: typer.secho("Warning!", fg=typer.colors.YELLOW, bold=True), typer.style("text", fg="red", underline=True). Confirm: typer.confirm("Delete all?", abort=True). Prompt: name = typer.prompt("Your name", default="World"). Progress: with typer.progressbar(range(100)) as progress: for _ in progress: .... Exit: raise typer.Exit(code=1). Abort: raise typer.Abort(). Subcommands: users_app = typer.Typer(), @users_app.command("list"), app.add_typer(users_app, name="users"). Groups: @app.callback() def main(verbose: bool = False): .... Launch: typer.launch("https://example.com"). Test: from typer.testing import CliRunner, runner = CliRunner(), result = runner.invoke(app, ["cmd", "--flag"]). Completion: typer --install-completion. Claude Code generates Typer multi-command CLIs, interactive prompts, file management tools, and devops scripts.
CLAUDE.md for Typer
## Typer Stack
- Version: typer >= 0.12 | pip install "typer[all]" for rich/shellcomplete
- App: app = typer.Typer(help="Description") | @app.command()
- Options: param: type = typer.Option(default, "--flag", "-f", help, envvar)
- Arguments: name: str = typer.Argument(..., help="Required positional")
- Output: typer.echo | typer.secho(text, fg=typer.colors.GREEN, bold=True)
- Interactive: typer.confirm("Sure?", abort=True) | typer.prompt("Name")
- Subcommands: app.add_typer(sub_app, name="sub") | @app.callback()
- Test: CliRunner().invoke(app, ["cmd", "--opt", "val"])
Typer CLI Pipeline
#!/usr/bin/env python3
# cli/typer_pipeline.py — building CLIs with Typer
from __future__ import annotations
import json
import os
import sys
import time
from enum import Enum
from pathlib import Path
from typing import Optional
import typer
app = typer.Typer(
name="myapp",
help="A multi-command CLI built with Typer.",
add_completion=True,
)
# ── Sub-applications ───────────────────────────────────────────────────────────
# files sub-group
files_app = typer.Typer(help="File management commands.")
app.add_typer(files_app, name="files")
# db sub-group
db_app = typer.Typer(help="Database management commands.")
app.add_typer(db_app, name="db")
# ── Enums for constrained choices ─────────────────────────────────────────────
class OutputFormat(str, Enum):
"""Output format choices."""
json = "json"
table = "table"
csv = "csv"
class LogLevel(str, Enum):
debug = "debug"
info = "info"
warning = "warning"
error = "error"
# ── State object (global options from callback) ───────────────────────────────
class State:
def __init__(self):
self.verbose: bool = False
self.log_level: LogLevel = LogLevel.info
self.config: dict = {}
state = State()
# ── 1. App-level callback (global flags) ──────────────────────────────────────
@app.callback()
def main_callback(
verbose: bool = typer.Option(False, "--verbose", "-v", help="Enable verbose output."),
log_level: LogLevel = typer.Option(LogLevel.info, "--log-level", help="Logging verbosity."),
config: Path = typer.Option(None, "--config", help="Config file path.",
exists=False, file_okay=True, dir_okay=False),
) -> None:
"""
myapp — A Typer CLI demo.
All global options are inherited by every subcommand.
"""
state.verbose = verbose
state.log_level = log_level
if config and config.exists():
state.config = json.loads(config.read_text())
if verbose:
typer.secho(f"Verbose mode ON (log level: {log_level.value})", fg=typer.colors.CYAN)
# ── 2. Simple commands ────────────────────────────────────────────────────────
@app.command()
def greet(
name: str = typer.Argument(..., help="Name to greet."),
count: int = typer.Option(1, "--count", "-c", min=1, max=100, help="Times to greet."),
loud: bool = typer.Option(False, "--loud", "-l", help="UPPERCASE output."),
color: bool = typer.Option(True, "--color/--no-color", help="Colored output."),
) -> None:
"""Say hello to NAME."""
for _ in range(count):
message = f"Hello, {name}!"
if loud:
message = message.upper()
if color:
typer.secho(message, fg=typer.colors.GREEN, bold=loud)
else:
typer.echo(message)
@app.command()
def version() -> None:
"""Print version and exit."""
typer.echo("myapp version 1.0.0")
raise typer.Exit(0)
@app.command()
def process(
input_file: Path = typer.Argument(..., exists=True, readable=True,
help="Input file to process."),
output_file: Optional[Path] = typer.Option(None, "--output", "-o", help="Output path."),
format_: OutputFormat = typer.Option(OutputFormat.json, "--format", "-f",
help="Output format."),
dry_run: bool = typer.Option(False, "--dry-run",
help="Validate without writing output."),
) -> None:
"""
Process INPUT_FILE and optionally write to OUTPUT_FILE.
Supports JSON, table, and CSV output formats.
"""
typer.echo(f"Processing: {input_file}")
content = input_file.read_text(encoding="utf-8")
lines = content.splitlines()
if state.verbose:
typer.secho(f" {len(lines)} lines read", fg=typer.colors.CYAN)
# Simulate processing with progress bar
results = []
with typer.progressbar(lines, label="Parsing") as progress:
for line in progress:
if line.strip():
results.append({"line": line.strip(), "length": len(line)})
typer.secho(f"Found {len(results)} non-empty lines.", fg=typer.colors.GREEN)
if dry_run:
typer.secho("Dry run — no files written.", fg=typer.colors.YELLOW)
return
if output_file is None:
output_file = input_file.with_suffix(f".{format_.value}")
if format_ == OutputFormat.json:
output_file.write_text(json.dumps(results, indent=2))
elif format_ == OutputFormat.csv:
lines_out = ["line,length"] + [f"{r['line']},{r['length']}" for r in results]
output_file.write_text("\n".join(lines_out))
else:
col_w = max(len(r["line"]) for r in results[:50]) + 2
rows = "\n".join(f" {r['line']:<{col_w}} {r['length']:>5}" for r in results[:50])
output_file.write_text(rows)
typer.secho(f"Output written to {output_file}", fg=typer.colors.GREEN, bold=True)
# ── 3. Interactive commands ───────────────────────────────────────────────────
@app.command()
def init(
project_name: str = typer.Argument(..., help="Project name."),
directory: Path = typer.Option(Path("."), "--dir", "-d", help="Target directory."),
force: bool = typer.Option(False, "--force", help="Overwrite existing files."),
) -> None:
"""Initialize a new project scaffold."""
target = directory / project_name
if target.exists() and not force:
typer.confirm(
f"Directory '{target}' exists. Overwrite?",
abort=True,
)
typer.echo(f"Creating project: {typer.style(str(target), bold=True)}")
files = {
"README.md": f"# {project_name}\n\nA new project.\n",
"main.py": "def main():\n print('Hello World')\n\nif __name__ == '__main__':\n main()\n",
"requirements.txt": "",
}
target.mkdir(parents=True, exist_ok=True)
for filename, content in files.items():
fp = target / filename
fp.write_text(content)
typer.echo(f" Created {fp}")
typer.secho(f"\nProject '{project_name}' ready!", fg=typer.colors.GREEN, bold=True)
# ── 4. File management subcommands ────────────────────────────────────────────
@files_app.command("list")
def list_files(
directory: Path = typer.Argument(Path("."), exists=True, help="Directory to list."),
pattern: str = typer.Option("*", "--pattern", "-p", help="Glob pattern."),
recursive: bool = typer.Option(False, "--recursive", "-r", help="Recursive listing."),
sort_by: str = typer.Option("name", "--sort",
help="Sort key: name, size, modified."),
) -> None:
"""List files in DIRECTORY matching PATTERN."""
glob_fn = directory.rglob if recursive else directory.glob
files = sorted(
glob_fn(pattern),
key=lambda p: getattr(p.stat(), {"size":"st_size","modified":"st_mtime"}.get(sort_by,"st_mtime"), p.name),
)
if not files:
typer.secho("No matching files.", fg=typer.colors.YELLOW)
raise typer.Exit(0)
typer.secho(f"Found {len(files)} file(s):", bold=True)
for f in files:
size = f.stat().st_size if f.is_file() else 0
typer.echo(f" {f.relative_to(directory)!s:<50} {size:>10,} bytes")
@files_app.command("copy")
def copy_files(
source: Path = typer.Argument(..., exists=True, help="Source path."),
destination: Path = typer.Argument(..., help="Destination path."),
overwrite: bool = typer.Option(False, "--overwrite", help="Overwrite existing."),
) -> None:
"""Copy SOURCE to DESTINATION."""
import shutil
if destination.exists() and not overwrite:
typer.secho(f"Destination {destination} exists. Use --overwrite.", fg=typer.colors.RED)
raise typer.Exit(1)
shutil.copy2(source, destination)
typer.secho(f"Copied {source} → {destination}", fg=typer.colors.GREEN)
# ── 5. Database subcommands ───────────────────────────────────────────────────
@db_app.command("migrate")
def db_migrate(
env: str = typer.Option("development", "--env", "-e", help="Environment."),
dry_run: bool = typer.Option(False, "--dry-run", help="Show SQL without running."),
target: Optional[str] = typer.Option(None, "--target", help="Target revision."),
) -> None:
"""Run database migrations."""
typer.echo(f"Running migrations (env={env}" + (", DRY RUN" if dry_run else "") + ")")
steps = ["schema_v1", "add_indices", "seed_data"]
with typer.progressbar(steps, label="Migrating") as progress:
for step in progress:
time.sleep(0.1) # Simulate work
if state.verbose:
typer.secho(f" Applied: {step}", fg=typer.colors.CYAN)
typer.secho("Migrations complete.", fg=typer.colors.GREEN, bold=True)
@db_app.command("reset")
def db_reset(
env: str = typer.Option("development", "--env", "-e"),
) -> None:
"""Reset database (destructive!). Requires confirmation."""
typer.secho(f"⚠️ This will DELETE all data in '{env}' database!", fg=typer.colors.RED, bold=True)
typer.confirm("Are you absolutely sure?", abort=True)
typer.secho("Database reset complete.", fg=typer.colors.GREEN)
# ── Entry point ───────────────────────────────────────────────────────────────
if __name__ == "__main__":
app()
For the argparse alternative — argparse is the stdlib choice but requires verbose add_argument calls for every parameter, no type coercion beyond basic types, and no testing utilities, while Typer infers argument names from Python parameter names, validates paths with Path(exists=True), clamps integers with min/max, and generates --help from docstrings, making a complete multi-command CLI with subcommands buildable in half the code. For the Click alternative — Click is Typer’s foundation and provides the same features while Typer wraps Click with type annotations, so name: str = typer.Argument(...) replaces @click.argument("name") and the IDE provides type inference throughout, and typer.testing.CliRunner inherits Click’s runner with zero additional setup, making Typer strictly additive over Click without losing any capability. The Claude Skills 360 bundle includes Typer skill sets covering Typer app with callback globals, Option and Argument with type hints, Enum choices, Path validation, secho colored output, confirm and prompt, progressbar, Exit codes, add_typer subcommand trees, and CliRunner unit testing. Start with the free tier to try CLI code generation.