Claude Code for Typer: Modern Python CLI Framework — Claude Skills 360 Blog
Blog / AI / Claude Code for Typer: Modern Python CLI Framework
AI

Claude Code for Typer: Modern Python CLI Framework

Published: November 26, 2027
Read time: 5 min read
By: Claude Skills 360

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.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free