[Python] How can I get a --version to the root of a typer.Typer application?

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    My CLI applications typically have subcommands. I want to have the --version flag at the root of my CLI applications, but with Typer I've only seen ways to put it to a command. I want to add it to the typer.Typer object (the root) itself. How can I do that?

    What I've tried


    import typer
    from typing import Optional

    __version__ = "0.1.0"


    def version_callback(value: bool):
    if value:
    typer.echo(f"Awesome CLI Version: {__version__}")
    raise typer.Exit()


    app = typer.Typer(
    add_completion=False,
    )


    @app.command()
    def main(
    version: Optional[bool] = typer.Option(
    None, "--version", callback=version_callback
    ),
    ) -> None:
    pass


    @app.command()
    def foo() -> None:
    pass


    if __name__ == "__main__":
    app()


    This gives

    $ python cli.py --help
    Usage: cli.py [OPTIONS] COMMAND [ARGS]...

    Options:
    --help Show this message and exit.

    Commands:
    foo
    main

    $ python cli.py main --help
    Usage: cli.py main [OPTIONS]

    Options:
    --version
    --help Show this message and exit.


    What I wanted:

    $ python cli.py --help
    Usage: cli.py [OPTIONS] COMMAND [ARGS]...

    Options:
    --version
    --help Show this message and exit.

    Commands:
    foo

    Continue reading...

Compartilhe esta Página