Skip to the solution
MediumDSA13 min read

What are generics and TypeVar in Python?

366 views

The problem

Question presented to candidate: "Say I write def first(items: list) -> object. A caller passes a list of ints and gets back something the type checker only knows is an object. How do generics and TypeVar fix that, and what does a generic class look like?"

What a strong answer should cover:

  • A type variable (T = TypeVar("T")) is a placeholder the checker solves at each call, so first(list[int]) returns int: it links input and output types, which Any cannot do
  • Generic classes subclass Generic[T] (or use class Stack[T]: on 3.12+); Stack[int] is checked as a stack of ints
  • Bounds (TypeVar("N", bound=float)) allow any subtype and keep it; constraints (TypeVar("S", str, bytes)) allow exactly one of a fixed list
  • Variance: list is invariant (a list[int] is not a list[float]), read-only types like Sequence are covariant; a mutable write is why
  • Type erasure at runtime: Stack[int]() is a plain Stack, the parameter is never checked, and isinstance(x, Stack[int]) raises TypeError

Code / implementation expected: Optional β€” a generic function such as first or a small generic container class, ideally with what a type checker infers for it.

  • typing
  • 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

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.

PythonA generic function and a generic Stack, and what survives at runtime
PythonBound, constrained and covariant TypeVars, and why list is invariant

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 96 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 nextMedium

How do you enforce match/case exhaustiveness in Python?

Continue