Sub topic 12
Typing **kwargs with Unpack
This chapter assumes you know how **kwargs works, how to define a TypedDict, and how total=False, Required and NotRequired mark optional keys. It also assumes you run a static checker such as mypy or pyright. Unpack with a TypedDict is a typing feature only, so the checker is what enforces it.
The problem with annotating **kwargs
A plain annotation on **kwargs applies to every value. This signature says all extra keyword arguments are floats:
def fetch(url: str, **kwargs: float) -> None:
...That fits a function that takes many values of the same kind. It does not fit options like timeout: float and retries: int, which have different names and different types. The usual workaround is **kwargs: Any. It removes all checking: a misspelled name such as timeuot=2.5 passes, and so does retries="many".
Unpack solves this. It lets one TypedDict describe the full set of accepted keyword names and the type of each.
Unpack with a TypedDict
Annotate **kwargs with Unpack[SomeTypedDict]. The checker then treats each key of the TypedDict as a keyword argument.
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)
retries = kwargs.get("retries", 0)
print(f"GET {url} with timeout {timeout} and {retries} retries")
fetch("https://example.com", timeout=2.5)
fetch("https://example.com", timeout=2.5, retries=3)
fetch("https://example.com")With total=False, every key is optional, so all three calls are accepted. A checker rejects these calls:
fetch("https://example.com", timeout="slow") # wrong value type
fetch("https://example.com", retrys=3) # unknown nameThe first fails because timeout must be a float. The second fails because retrys is not a key of RequestOptions. Neither error would appear with **kwargs: Any.
Two views of the same annotation
The annotation looks different from inside and outside the function.
- Outside (the caller): the function takes the keyword-only parameters
timeoutandretries, each with the declared type. - Inside (the body):
kwargshas the typeRequestOptions. You read it like aTypedDict, withkwargs["timeout"]orkwargs.get("timeout").
Inside the body the NotRequired rules apply. If timeout is optional, kwargs["timeout"] is reported as a possible KeyError unless you first check "timeout" in kwargs. Using .get() with a default is the usual way to read optional keys.
Required and optional keys
The keys of the TypedDict decide which keyword arguments the caller must pass. Required keys become required keyword arguments. Optional keys become keyword arguments with defaults.
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="db.local"))
print(connect(host="db.local", port=6543))The call connect() is rejected by the checker because host is required. Inside connect, kwargs['host'] is safe because host is required. Reading kwargs['port'] directly would be flagged.
| Key declaration | Caller must pass it? | Safe to read as `kwargs["key"]`? |
|---|---|---|
| `name: str` in a default (total) class | Yes | Yes |
| `name: NotRequired[str]` | No | Only after `"name" in kwargs` |
| `name: str` in a `total=False` class | No | Only after `"name" in kwargs` |
| `name: Required[str]` in a `total=False` class | Yes | Yes |
Mixing Unpack with other parameters
Unpack only covers the **kwargs part. You can still have positional parameters, defaults and *args before it. Here url is an ordinary parameter and the options are keyword-only.
from typing import TypedDict, Unpack
class RequestOptions(TypedDict, total=False):
timeout: float
retries: int
def post(url: str, body: bytes = b"", **kwargs: Unpack[RequestOptions]) -> None:
print(url, len(body), kwargs)
post("https://example.com", b"data", timeout=1.0)Some rules apply:
Unpack[...]is accepted on**kwargs. It is not a replacement for a*argsannotation.- The
TypedDictkeys must not repeat the name of another parameter in the same function. IfRequestOptionshad aurlkey,post(url, **kwargs: Unpack[RequestOptions])would be ambiguous, and checkers report it as an error. - Only a
TypedDictcan be unpacked this way. A plain class or adict[str, int]cannot.
Forwarding options to another function
The main use of this feature is a wrapper that passes its options on. If both functions share the same TypedDict, the checker verifies the whole chain.
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}"
def connect_with_log(**kwargs: Unpack[ConnectOptions]) -> str:
print("connecting", kwargs)
return connect(**kwargs)
print(connect_with_log(host="db.local", port=1234))The call connect(**kwargs) is accepted because kwargs has type ConnectOptions, which matches the parameters of connect. Without Unpack, a wrapper typed with **kwargs: Any would forward anything, and mistakes would only surface at runtime.
You can also pass a dictionary into such a function with **. The checker accepts it when the dictionary's type is compatible with the TypedDict.
opts: ConnectOptions = {"host": "db.local"}
print(connect(**opts))A dict[str, object] fails this check, because the checker cannot know which keys it holds.
What happens at runtime
Unpack changes nothing at runtime. Inside the function, kwargs is an ordinary dict, and Python does not check names or types. Any keyword argument is accepted, because the function still has a **kwargs parameter.
from typing import TypedDict, Unpack
class RequestOptions(TypedDict, total=False):
timeout: float
retries: int
def fetch(url: str, **kwargs: Unpack[RequestOptions]) -> None:
print(type(kwargs))
print(kwargs)
fetch("https://example.com", timeout="slow", proxy="p") # flagged by a type checker, runs without errorThis prints <class 'dict'> and then {'timeout': 'slow', 'proxy': 'p'}. The checker would report two errors on that call, and the interpreter reports none.
The diagram shows where each check happens.
Read-only keys in the options
If the TypedDict marks a key as ReadOnly, the function body may not assign to kwargs["key"]. The caller can still pass the key as normal. This is useful when a function must not change an option that was supplied. ReadOnly needs Python 3.13, or typing_extensions on older versions.
Common mistakes
- Annotating with the
TypedDictdirectly. Writing**kwargs: RequestOptionstells the checker that every extra keyword value is a wholeRequestOptionsdictionary. That is almost never what you want. UseUnpack[RequestOptions]. - Forgetting
total=False. A defaultTypedDictmakes every key required, so callers must supply every option. For a set of optional settings, usetotal=FalseorNotRequired. - Reading optional keys with
[]. Use.get()or anincheck, as shown above. - Expecting an error at runtime. A wrong call fails only in the checker. If a test must catch it, add explicit validation or run the type checker in CI.
- Reusing a parameter name as a key. Keep the explicit parameters and the
TypedDictkeys disjoint.
When to choose Unpack
Use Unpack when a function takes many optional named settings, when several functions share the same set, or when a wrapper forwards options to a library function. For two or three arguments, ordinary keyword parameters are clearer, because the signature is visible in one place. If the options arrive as data rather than keyword arguments, accept the TypedDict itself as a normal parameter.
Exercise
A function is declared as def send(msg: str, **kwargs: Unpack[Opts]) -> None, where class Opts(TypedDict): priority: int; ttl: NotRequired[float]. State which of these calls a type checker accepts and what happens when each one runs: (a) send("hi", priority=1), (b) send("hi", ttl=5.0), (c) send("hi", priority="high").
Show answer
Only (a) is accepted. Call (b) is rejected because the required key priority is missing. Call (c) is rejected because priority must be an int. At runtime all three calls execute without any error from Python, because Unpack is not enforced and kwargs is a plain dict. Any failure would come from the function body, not from the annotation.
Exercise
Inside send, you want to read ttl and fall back to 30.0 when the caller did not pass it. Why is kwargs["ttl"] flagged by the checker, and what are two ways to write it correctly?
Show answer
ttl is NotRequired, so the key may be absent and kwargs["ttl"] could raise a KeyError. Write kwargs.get("ttl", 30.0), or check first with if "ttl" in kwargs: and then read kwargs["ttl"] inside that branch.