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
📝 Add reference (code API) docs (#1504)Sofie Van Landeghembefore adoption2d529b2
lines 1–38why, one step back1# Context23When you create a Typer application it uses Click underneath.4And every Click application has a special object called a [`Context`](https://click.palletsprojects.com/en/stable/api/#click.Context) that is normally hidden.5But you can access the context by declaring a function parameter of type `typer.Context`.67The same way you can access the context by declaring a function parameter with its value,8you can declare another function parameter with type `typer.CallbackParam` to get the specific Click [`Parameter`](https://click.palletsprojects.com/en/stable/api/#click.Parameter) object.910```python11from typing import Annotated1213import typer1415app = typer.Typer()161718def name_callback(ctx: typer.Context, param: typer.CallbackParam, value: str):19 if ctx.resilient_parsing:20 return21 print(f"Validating param: {param.name}")22 if value != "Rick":23 raise typer.BadParameter("Only Rick is allowed")24 return value252627@app.command()28def main(name: Annotated[str | None, typer.Option(callback=name_callback)] = None):29 print(f"Hello {name}")303132if __name__ == "__main__":33 app()34```3536::: typer.Context3738::: typer.CallbackParam