Consider the following typer-based Python program:
#!/usr/bin/env python
import typer
app = typer.Typer()
from typing_extensions import Annotated
VERBOSE = False
books_app = typer.Typer()
app.add_typer(books_app, name="books")
authors_app = typer.Typer()
app.add_typer(authors_app, name="authors")
###
@books_app.command("list")
def books_list() -> str:
if (VERBOSE):
print("entering 'books_list'")
@books_app.command("delete")
def books_delete(
book_name: Annotated[str, typer.Argument(help="name of book to delete")],
) -> str:
if (VERBOSE):
print("entering 'books_delete'")
###
@app.callback(no_args_is_help=True, invoke_without_command=True)
def main(ctx: typer.Context,
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="runs in verbose mode")] = False
) -> None:
global VERBOSE
if (verbose):
VERBOSE = True
if __name__ == "__main__":
app()
I would like to be able to put the "global" option --verbose anywhere on the command line. That is, I want each of the following to work the same way:
$ ./myapp --verbose books list
$ ./myapp books --verbose list
$ ./myapp books list --verbose
As the above program is written only the first of the above three invocations works.
One way to accomplish this would be to add the --verbose option to each command/subcommand function definitions. However, that seems inefficient, especially if I have many command and subcommands.
Is there a better way to do this?