Unpack allows TypedDict values to be unpacked as keyword arguments.
1from typing import TypedDict, Unpack23class Options(TypedDict, total=False):4 timeout: int5 retries: int6 headers: dict[str, str]78def fetch(url: str, **kwargs: Unpack[Options]) -> str:9 timeout = kwargs.get("timeout", 30)10 retries = kwargs.get("retries", 3)11 return f"Fetching {url} with timeout={timeout}"1213# Type-safe keyword arguments14fetch("http://example.com", timeout=10, retries=5) # OK15# fetch("http://example.com", invalid="param") # Type error!1617# With FastAPI18from fastapi import FastAPI1920app = FastAPI()2122class QueryParams(TypedDict, total=False):23 skip: int24 limit: int25 search: str2627@app.get("/items/")28async def get_items(**params: Unpack[QueryParams]):29 skip = params.get("skip", 0)30 limit = params.get("limit", 10)31 return {"skip": skip, "limit": limit}
Benefits: