Module 3: Advanced Typing and Interface Design

Generics and Type Variables

Generics and Type Variables

Generics preserve relationships between input and output types. A type variable means one consistent but unspecified type, which communicates more than Any and prevents callers from losing useful information.

Module: Module 3: Advanced Typing and Interface Design

Core mental model

This lesson is built around four connected ideas. Read them as a decision framework, then prove each one with the walkthrough.

  • TypeVar connects repeated type positions.
  • Generic containers retain the type of the value they hold.
  • Bounds and constraints narrow valid type variables for real operations.
  • Modern type-parameter syntax depends on the supported Python version.

Walkthrough

from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar("T")

@dataclass
class Result(Generic[T]):
    value: T | None = None
    error: Exception | None = None

def first(values: list[T]) -> T:
    if not values:
        raise ValueError("values must not be empty")
    return values[0]

first returns the same element type the input list contains. Result[int] and Result[str] retain different value contracts without duplicating the class.

Hands-on lab

Implement generic Page[T] and map_page(Page[T], Callable[[T], U]) -> Page[U]. Use a checker to prove the output type follows the transform.

What to watch for

  • Any erases relationships that a type variable can preserve.
  • Overly complex variance and bounds can reduce readability.
  • Runtime external-data validation remains necessary.

Engineering checklist

  • Connect the lesson's mental model to the choices made in the walkthrough.
  • Test the normal case, an empty or boundary case, and one invalid case.
  • Keep external input, side effects, and reusable logic in clearly separated layers.
  • Prefer the clearest correct implementation before optimizing or generalizing it.

Completion check

You can implement the lab without copying the example, explain the core concepts in your own words, and show tests or terminal output that demonstrate the expected and failure paths.