← Back to Python, page 5

python-0090 · Hard senior

Write a generic, type-safe repository class with TypeVar, Generic and Protocol, and explain what the type checker gains.

A TypeVar bound to a Protocol lets one class work with any entity type that has the required attributes, while the type checker tracks the concrete type through get and add. Python 3.12 syntax writes this as class Repo[T: HasId]. Annotations are not enforced at runtime, so a checker such as mypy or pyright provides the benefit.

Full answer
python
from dataclasses import dataclass
from typing import Generic, Protocol, TypeVar, get_type_hints

class HasId(Protocol):
    id: int

T = TypeVar("T", bound=HasId)

class Repo(Generic[T]):
    def __init__(self) -> None:
        self._items: dict[int, T] = {}
    def add(self, item: T) -> T:
        self._items[item.id] = item
        return item
    def get(self, id: int) -> T | None:
        return self._items.get(id)

@dataclass
class User:
    id: int
    email: str

class Repo312[E: HasId]:
    def first(self, items: list[E]) -> E:
        return items[0]

users: Repo[User] = Repo()
users.add(User(1, "a@x.in"))
print(users.get(1), users.get(2))
print(get_type_hints(Repo.get))
print(Repo312.__type_params__)
try:
    users.add("not a user")
except AttributeError as e:
    print("AttributeError:", e)

Output:

text
User(id=1, email='a@x.in') None
{'id': <class 'int'>, 'return': typing.Optional[~T]}
(E,)
AttributeError: 'str' object has no attribute 'id'

The repository stores and returns User objects, and a type checker infers that users.get(1) is User | None, so attribute typos on the result are caught before running. User satisfies HasId structurally, without inheriting from it. get_type_hints shows the annotations are available for introspection, and the 3.12 syntax stores its parameters in __type_params__. The last call passes a string, which a checker rejects at analysis time; at runtime nothing checks the annotation, and the call fails only when add reaches item.id, raising AttributeError. In larger code the bad value might travel far before failing, which is the main argument for running a checker in CI.

python
from dataclasses import dataclass
from typing import Generic, Protocol, TypeVar, get_type_hints

class HasId(Protocol):
    id: int

T = TypeVar("T", bound=HasId)

class Repo(Generic[T]):
    def __init__(self) -> None:
        self._items: dict[int, T] = {}
    def add(self, item: T) -> T:
        self._items[item.id] = item
        return item
    def get(self, id: int) -> T | None:
        return self._items.get(id)

@dataclass
class User:
    id: int
    email: str

class Repo312[E: HasId]:
    def first(self, items: list[E]) -> E:
        return items[0]

users: Repo[User] = Repo()
users.add(User(1, "a@x.in"))
print(users.get(1), users.get(2))
print(get_type_hints(Repo.get))
print(Repo312.__type_params__)
try:
    users.add("not a user")
except AttributeError as e:
    print("AttributeError:", e)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • TypeVar with a bound restricts generic types
  • Protocols are structural interfaces
  • 3.12 adds class C[T] syntax
  • Checkers enforce, the runtime does not
  • Generics carry concrete types through APIs

Common mistakes

  • Expecting annotations to validate at runtime
  • Using Any where a TypeVar fits

Follow-ups

  • When would you use ParamSpec?
  • How do you add type checking to CI gradually?

Tips

  • Separate checker from runtime