Skip to the solution
HardBackend13 min read

How do Unpack and TypedDict enable type-safe **kwargs?

170 views

The problem

Question presented to candidate: "Say a function takes a bunch of optional settings through **kwargs β€” timeout, retries, verbose. How would you type that so a checker catches a misspelled keyword or a wrong value type? What do TypedDict and Unpack each contribute, and what happens at runtime?"

What a strong answer should cover:

  • The old form **kwargs: int types every value the same; it cannot give each keyword its own name and type, and inside the function kwargs is dict[str, int].
  • **kwargs: Unpack[SomeTypedDict] (PEP 692, Python 3.12; typing_extensions before that, and typing.Unpack itself exists from 3.11) tells the checker the function accepts exactly those keyword names, each with its own type.
  • total=False, Required[...] and NotRequired[...] (PEP 655, 3.11) decide which keywords are mandatory; required keys become required keyword arguments, the rest optional.
  • Checkers report unknown names, wrong types, missing required keys and a named parameter that overlaps a TypedDict key; inside the function kwargs has the TypedDict type.
  • Nothing is checked at runtime: the annotation is metadata, kwargs is a plain dict, and a typo still runs. Validate at the boundary if the input is untrusted.
  • Trade-off against explicit keyword-only parameters: Unpack shines when the same option set is shared by several functions or wrappers that forward **kwargs.

Clarifying questions expected:

  • Which Python version and type checker does the codebase use (3.12+ typing.Unpack support, or typing_extensions)?
  • Do the options come from Python callers only, or also from untrusted data that needs runtime validation?

Code / implementation expected: Yes β€” a TypedDict, a function using **kwargs: Unpack[...], and the checker errors it produces.

  • typing
  • unpack
  • typeddict

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonUnpack[TypedDict] at runtime, its metadata, and a tiny runtime check
PythonThe keyword-only signature a checker sees, Required/NotRequired and forwarding

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 137 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextHard

How does async/await work in Python?

Continue