Typer Async Command Options

Build async CLI commands with Typer, combining type-annotated options, enum choices, environment fallbacks, and per-command validation.

PythonCli Tooling

Code

snippet
import asyncio
from enum import Enum

import typer

app = typer.Typer(add_completion=False)


class Region(str, Enum):
    eu = 'eu'
    na = 'na'
    apac = 'apac'


@app.command()
async def replicate(
    region: Region = typer.Option(..., help='target region'),
    batch_size: int = typer.Option(500, min=1, max=5000, envvar='REPL_BATCH_SIZE'),
    api_key: str = typer.Option(..., envvar='REPLICATE_API_KEY', hide_input=True),
    dry_run: bool = typer.Option(False, '--dry-run/--execute'),
) -> None:
    """Replicate catalog entries into a regional store."""
    typer.echo(f'replicating to {region.value} with batch={batch_size}')
    if dry_run:
        typer.echo('dry run: no rows will be written')
        return

    for batch_index in range(3):
        await asyncio.sleep(0.1)
        typer.echo(f'batch {batch_index + 1}/3 done')

    typer.echo('replication complete')


@app.command()
def status(region: Region = typer.Option(Region.eu)) -> None:
    typer.echo(f'worker status in {region.value}: idle')


def main() -> None:
    asyncio.run(app())


if __name__ == '__main__':
    main()