Sub topic 12
Typing **kwargs with Unpack
This chapter shows how to describe the keyword arguments of a function with a TypedDict. It assumes you know how to define a TypedDict, how total=False makes keys optional, and that a type checker such as mypy or pyright checks annotations without running the code.
The problem with plain **kwargs
Before Unpack, you annotated **kwargs with a single type. That annotation applies to every extra keyword argument.
def fetch(url: str, **kwargs: float) -> None:
print(url, kwargs)With this signature, every option must be a float. You cannot say that timeout is a float while retries is an int. You also cannot restrict the names a caller may pass. A misspelled option such as timout=2.5 passes the check.
Unpack with a TypedDict
Unpack (in typing since Python 3.12, or in typing_extensions on older versions) lets you annotate **kwargs with a TypedDict. Each key of the TypedDict becomes a keyword argument with its own type.
from typing import TypedDict, Unpack
class RequestOptions(TypedDict, total=False):
timeout: float
retries: int
def fetch(url: str, **kwargs: Unpack[RequestOptions]) -> None:
timeout = kwargs.get("timeout", 10.0)
print(f"GET {url} with timeout {timeout}")
fetch("https://example.com", timeout=2.5)Here total=False makes both keys optional, so a caller may pass either, both, or neither. Inside the function, kwargs is typed as RequestOptions. Use kwargs.get("timeout", 10.0) or an in check to read optional keys safely.
A checker now reports these calls:
fetch("https://example.com", timout=2.5)becausetimoutis not a key ofRequestOptions.fetch("https://example.com", retries="3")becauseretriesmust be anint.
Required keys
Keys without total=False stay required. A caller must then pass them as keyword arguments.
from typing import NotRequired, TypedDict, Unpack
class ConnectOptions(TypedDict):
host: str
port: NotRequired[int]
def connect(**kwargs: Unpack[ConnectOptions]) -> str:
port = kwargs.get("port", 5432)
return f"{kwargs['host']}:{port}"
print(connect(host="localhost"))
print(connect(host="localhost", port=6543))Calling connect() with no arguments is an error in the checker, because host is required. Mixing NotRequired with a total TypedDict, as above, lets you choose optionality per key.
How it works at runtime
Unpack is only a hint for the checker. At runtime, kwargs is an ordinary dict, and Python does not validate names or types. The call fetch("https://example.com", timout=2.5) runs without error and puts timout into kwargs. Your code then silently ignores it unless you check it yourself.
Common errors
- Using
Unpackwith a normal class. The argument must be a TypedDict. A dataclass or a plain class is not accepted. - Forgetting that keys are keyword-only. The caller cannot pass the values by position. The names must appear in the call.
- Reading an optional key with
kwargs["timeout"]. The checker flags this, and it raisesKeyErrorif the caller left the key out. Use.getor test within. - Duplicate names. A TypedDict key must not repeat the name of another parameter in the same function, such as
urlinfetch. The checker reports the clash. - Expecting runtime errors. Unknown keywords are not rejected when the program runs. Rely on the checker, or add explicit validation for input from outside your code.
Exercise
A function is declared as def run(cmd: str, **kwargs: Unpack[Opts]), where Opts is a TypedDict with the required key cwd: str and the optional key env: NotRequired[dict[str, str]]. Which of these calls does a type checker accept: run("ls"), run("ls", cwd="/tmp"), run("ls", cwd="/tmp", env=None)? Why?
Show answer
Only run("ls", cwd="/tmp") is accepted. run("ls") omits the required key cwd. The third call passes env=None, but env must be a dict[str, str] when present, so None is the wrong type. At runtime all three calls would start without any complaint from Python itself, because kwargs is a plain dict and nothing validates it.