Skip to the solution
HardDSA12 min read

What is TypeVarTuple and Unpack for variadic generics?

579 views

The problem

Question presented to candidate: "A normal TypeVar stands for one type. How would you type a function like call_soon(callback, *args) so the checker verifies that args match the callback's parameters, or an Array class whose type includes its shape, like Array[float, Height, Width]? What are TypeVarTuple and Unpack?"

What a strong answer should cover:

  • TypeVarTuple (PEP 646, Python 3.11) is a placeholder for any number of types, in order; it is always used unpacked, as *Ts or the equivalent Unpack[Ts]
  • Variadic generic classes: class Array(Generic[DType, *Shape]) lets Array[float, Height, Width] carry a shape; the motivating use is array shapes in NumPy-style libraries
  • Typed *args: def f(*args: *Ts) -> tuple[*Ts] keeps each argument type; Callable[[*Ts], R] with *args: *Ts ties a callback to its arguments (how typeshed types asyncio call_soon)
  • Combining with TypeVar for prefix/suffix (tuple[T, *Ts]), and unpacking concrete tuple types (*tuple[int, ...])
  • Limits: only one TypeVarTuple per parameter list, *Ts only on *args, no keyword arguments (use ParamSpec for that), the runtime checks none of it; 3.12 syntax class Array[DType, *Shape], 3.13 defaults

Code / implementation expected: Optional β€” a typed *args function or a callback scheduler using Callable[[*Ts], R], with what the checker infers.

  • typing
  • typevartuple
  • generics

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

12 min read Β· 11 sections

Run the code

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

PythonTypeVarTuple in a generic Array, *Ts vs Unpack, typed *args and head/tail
PythonA typed call_soon(callback, *args) scheduler, and unpacking tuple types

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 129 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

What is the difference between a generator and a coroutine?

Continue