Lesson 2 of 9 · 24m
click and typer: Frameworks for Real Command Trees
When a tool grows subcommands and shared options, click gives explicit control while typer trades type annotations for less ceremony.
Once a tool has init, sync, doctor, and config subcommands, hand-rolled argparse becomes a shell game of nested parsers. click has been the dependable answer for years; typer builds on click and uses type hints to remove boilerplate. Choose either deliberately — the sin is letting every subcommand invent its own conventions.
click: explicit, composable, conservative
import click
@click.group()
@click.option("--config", type=click.Path(exists=True), help="Path to config file.")
@click.pass_context
def cli(ctx, config):
ctx.obj = {"config": config}
@cli.command()
@click.argument("environment")
@click.option("--dry-run", is_flag=True, help="Print actions without changing state.")
def deploy(environment, dry_run):
'''Deploy the application to ENVIRONMENT.'''
click.echo(f"deploying to {environment}, dry_run={dry_run}")The decorator stack reads almost like the usage line. click.Path validates filesystem input, is_flag=True makes booleans honest, and @click.pass_context gives subcommands a place for shared objects. Do not stuff global mutable state into modules because passing it feels inconvenient.
typer: less ceremony, more inference
import typer
app = typer.Typer(help="Operate the widget fleet.")
@app.command()
def restart(name: str, force: bool = typer.Option(False, "--force")):
'''Restart one widget.'''
typer.echo(f"restart {name} force={force}")Typer is pleasant for application teams already fluent in type annotations. The cost is inference: parameter names become option names, annotations drive parsing, and small signature changes can alter the public CLI. That is fine when you treat command signatures as stable API and review them like one.
Design a command tree users can guess
Good trees are noun-verb or verb-noun consistently. Pick one:
fleet restart web-01
fleet status
fleet config set region us-eastDo not mix fleet restart web-01, fleet web-01 restart, and fleet restart-web-01. Hidden consistency is what lets users predict commands they have never read about. Put shared options such as --config on the root group; command-specific safety flags such as --force stay on leaf commands.
Field notes
- Pin the framework major version in application requirements. CLI parsing is user-visible API, not an implementation detail.
- Use
click.echo()ortyper.echo()instead of bareprint()when output needs encoding and terminal handling across platforms. - Boolean flags should be positive (
--force,--cache) rather than negative (--no-cache) unless the default already enables the behavior. - A hidden option is sometimes appropriate for a migration, but undocumented safety-critical behavior is an operational trap.
Was this lesson helpful?