Jacob Kaplan-Moss

Tag: Typer

TIL: Common Arguments With Typer

I mostly use Typer to write CLIs in Python. I find it mildly easier than Click, but one thing I hadn’t worked out until today was how to implement common options with subcommands. That is, I had code like this::

import typer

cli = typer.Typer()

@cli.command()
def all(pinboard_token: str = typer.Option(None, envvar="PINBOARD_TOKEN")):
    ...

@cli.command()
def new(pinboard_token: str = typer.Option(None, envvar="PINBOARD_TOKEN")):
    ...

if __name__ == '__main___':
    cli()

But I wanted --pinboard-token to be an option on the main command, not on the subcommands. It’s essentially required, so I need to check for it, and didn’t want to do that multiple times. I also want to not repeat myself in each command.

January 17th, 2022 • typer