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

pythonsnippet
45 lines
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()

How it works

The code’s whole job belongs to the class Region and the functions replicate, status and main.

for batch_index in range(3) is the loop that carries the per-item work. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. From asyncio it pulls Enum — the imports name exactly which library surface the snippet touches.

What to watch for

  • Plan for an install step: asyncio and typer are a real dependency, resolved by the package manager.

Using it

The primary signature is def replicate( region: Region = typer.Option(..., help='target region')

Key statements

def status(region: Region = typer.Option(Region.eu)) -> None:
    typer.echo(f'worker status in {region.value}: idle')
def main() -> None:
    asyncio.run(app())
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:

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `asyncio` and `typer`. Add them to your project before running the snippet.