Skip to content

Global version option, for use at top level and with subcommands #1195

Answered by peterjc
peterjc asked this question in Questions
Discussion options

You must be logged in to vote

A solution based on this stack overflow answer, but using type annotation style, and also explicitly adding the version option to all the subcommands.

import sys
import typer
from typing_extensions import Annotated


__version__ = "1.3.5"


def version_callback(version: bool = False) -> None:
    if version:
        print(f"myapp {__version__}")
        sys.exit(0)  # typer.Exit() does not quit immediately


VERSION_TYPE_DEF = Annotated[
    bool,
    typer.Option(
        "--version",
        "-v",
        help="Show tool version (on stdout) and quit.",
        show_default=False,
        is_eager=True,
        callback=version_callback,
    ),
]


app = typer.Typer(no_args_is_help=True)


Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@peterjc
Comment options

Answer selected by peterjc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem
1 participant