context.md
This file
Path
docs/reference/context.md
38 lines 路 1.1 KiB 路 Markdown
Last changed by
馃摑 Add reference (code API) docs (#1504)Sofie Van Landeghembefore adoption2d529b2
History of this fileTake it
context.md
Context
When you create a Typer application it uses Click underneath.
And every Click application has a special object called a Context that is normally hidden.
But you can access the context by declaring a function parameter of type typer.Context.
The same way you can access the context by declaring a function parameter with its value,
you can declare another function parameter with type typer.CallbackParam to get the specific Click Parameter object.
from typing import Annotated
import typer
app = typer.Typer()
def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):
if ctx.resilient_parsing:
return
print(f"Validating param: {param.name}")
if value != "Rick":
raise typer.BadParameter("Only Rick is allowed")
return value
@app.command()
def main(name: Annotated[str | None, typer.Option(callback=name_callback)] = None):
print(f"Hello {name}")
if __name__ == "__main__":
app()
::: typer.Context
::: typer.CallbackParam