Lesson 30 of 52Types in depth
Generics and Protocols in Depth
Write reusable typed code with PEP 695 generics, bounds, variance and Protocols, and design APIs that accept wide types and return precise ones.
You are asked to build a small data layer: one repository class for users, orders and invoices. Copy and paste three times and you have three classes to keep in sync. Write it once with object everywhere and every caller needs a cast to get a User back out. Generics let you write the class once and still have the checker know that users.get(1) returns a User | None. Protocols let that class accept anything with an id, without forcing every model to inherit from your base class. This lesson starts where Type Hints stopped: bounds, variance, protocol design, and the mistakes that show up in code review. This unit goes deeper than most everyday code needs, so on a first pass you can skip ahead to Python power tools and come back when your team turns on a strict type checker.
PEP 695: the syntax to write today
In Type Hints you saw def first[T](items: list[T]) -> T. That square-bracket syntax arrived in Python 3.12 (PEP 695) and covers three things: generic functions, generic classes and generic type aliases.
def first[T](items: list[T]) -> T: ... # generic function
class Cache[K, V]: # generic class
def __init__(self) -> None:
self._data: dict[K, V] = {}
type Pair[T] = tuple[T, T] # generic alias
type JsonValue = str | int | float | bool | None | list[JsonValue] | dict[str, JsonValue]The type statement creates a lazily evaluated alias, which is why JsonValue can refer to itself without quotes. The type parameters are scoped to the function, class or alias that declares them. You no longer create a module-level T = TypeVar("T") that leaks into everything else in the file.
The type parameters are real objects at runtime, which is how libraries like Pydantic can inspect them:
Press Run (⌘ Enter) to see what happens.Page[T = str] is a type parameter default (PEP 696, Python 3.13). If a caller writes a bare Page, the checker treats it as Page[str] instead of Page[Any]. Defaults are handy when you add a type parameter to a class that already has users: old annotations keep a sensible meaning.
You will still read the older style in most existing code and in libraries that support versions before 3.12:
from typing import Generic, TypeVar
T = TypeVar("T")
T_co = TypeVar("T_co", covariant=True)
class Box(Generic[T_co]):
def __init__(self, value: T_co) -> None:
self._value = value
def get(self) -> T_co:
return self._valueIt means the same thing. The _co suffix is a naming convention for covariant type variables, and the new syntax makes it unnecessary, as you will see in the variance section.
Bounds, constraints, object and Any
An unconstrained T can be anything, so inside the function you can only do what every object can do. To call methods on T, you bound it:
from collections.abc import Iterable
from typing import Any, Protocol
class Comparable(Protocol):
def __lt__(self, other: Any, /) -> bool: ...
def biggest[T: Comparable](items: Iterable[T]) -> T:
it = iter(items)
best = next(it)
for x in it:
if best < x:
best = x
return best
biggest([3, 1, 2]) # int
biggest(["a", "b"]) # str
biggest([object()]) # error: T cannot be "object"[T: Comparable] reads "T is some type that is a Comparable". The caller still gets back the exact type they passed in, int or str, not Comparable. That is the whole point: the bound limits what goes in, the variable keeps the precise type flowing out.
A tuple after the colon means something different. [S: (str, bytes)] is a constraint: S must be exactly str or exactly bytes, and both arguments must agree.
def concat[S: (str, bytes)](a: S, b: S) -> S:
return a + b
concat("a", "b") # str
concat("a", b"b") # error: cannot mix str and bytesA subtle difference: with a constraint, passing a subclass of str gives back plain str, because the checker picks one of the listed types. With a bound [S: str], the function promises to return the caller's exact subclass, so return a + b is an error (str + str produces a str, not an S). Constraints fit functions like concat that work on a small fixed family. Bounds fit everything else, and you will use them far more.
Two top types look similar and are opposites:
objectaccepts every value and lets you do almost nothing with it until you narrow it withisinstance. It is the safe "I accept anything".Anyaccepts every value and lets you do everything with it.x.whatever()passes the checker. It switches checking off for that value, and it spreads: anything you get from anAnyis alsoAny.
Reach for object (or a type variable) when you mean "any value". Keep Any for genuinely untyped boundaries, such as a raw JSON blob you are about to validate.
def concat[S: (str, bytes)](a: S, b: S) -> S, what type does a checker give concat(MyStr('a'), MyStr('b')), where MyStr subclasses str?Variance: why list[Dog] is not a list[Animal]
This is the concept that confuses most people and that interviewers love. A Dog is an Animal. Is a list[Dog] a list[Animal]? It feels like it should be. Run this to see why the checker says no:
Press Run (⌘ Enter) to see what happens.add_cat did nothing wrong for a list[Animal]. The bug is that a list is mutable: if you could pass a list[Dog] where a list[Animal] is expected, the function could write a Cat into it, and the caller who still believes it holds only dogs crashes later. So list is invariant: list[Dog] and list[Animal] are simply unrelated types.
Sequence[Dog] is a Sequence[Animal], because Sequence has no append. If you can only read, every dog you read out is a fine animal. That is covariance: the subtype relation goes the same direction as the element type. The same holds for Iterable, Mapping values, tuple, and frozenset.
Function parameters go the other way. A Callable[[Animal], None] can be used where a Callable[[Dog], None] is expected: a handler that copes with any animal certainly copes with a dog. The reverse is unsafe, because a dog-only handler might call .fetch() on a cat. That is contravariance, and it applies to argument types. Return types are covariant.
Start with the plain fact: a Dog can go wherever an Animal is expected.
The practical lesson: accept wide, return narrow. Type parameters as Sequence[Animal], Iterable[str] or Mapping[str, int] from collections.abc when your function only reads them. Callers can then pass lists, tuples, dict views or generators of any subtype. Return concrete types like list[str] or dict[str, int] so callers get every method. Mypy even suggests this in its error message: "list is invariant, consider using Sequence instead, which is covariant".
Variance in your own classes
With the old TypeVar you had to declare variance by hand with covariant=True, and the checker complained if you got it wrong. With PEP 695, the checker infers it from how the class uses T:
class ReadBox[T]:
def __init__(self, v: T) -> None:
self._v = v
def get(self) -> T: # T only comes out
return self._v
class RWBox[T]:
def __init__(self, v: T) -> None:
self.v = v # public mutable attribute: T goes in and out
rb: ReadBox[Animal] = ReadBox[Dog](Dog()) # OK: inferred covariant
wb: RWBox[Animal] = RWBox[Dog](Dog()) # error: inferred invariantT that only appears in return types makes the class covariant. T that appears in a parameter, or in a public writable attribute, makes it invariant. The underscore on _v matters: checkers treat it as private for this purpose. If you want a container that callers can pass around as its parent type, keep it read-only.
Match each type to its variance in its element or parameter type.
Protocols in depth
You met Protocol in Inheritance and Composition and again in Type Hints as "any object with these methods". Here is what you need to design them well.
Structural, not nominal. A class satisfies a protocol if it has the right members with compatible types. It never mentions the protocol. This is how you type third-party objects you cannot change, and how you keep your core code from importing infrastructure classes. Your service depends on a PaymentGateway protocol; Stripe and fake test gateways both fit without inheriting anything.
Members can be attributes and properties, and the difference matters.
from typing import Protocol
class HasMutableId(Protocol):
id: int # caller may also WRITE .id
class HasId(Protocol):
@property
def id(self) -> int: ... # caller only reads .idA frozen dataclass with id: int satisfies HasId but not HasMutableId: mypy reports "expected settable variable, got read-only attribute". A plain attribute in a protocol promises the reader they can assign to it. Use a property when you only need to read, which is almost always. It is variance again: a writable member is invariant.
Generic protocols combine both ideas. Here is a cut-down version of the SupportsRead protocol that typeshed (the stubs every checker ships with) uses for file-like objects:
import io
from typing import Protocol
class SupportsRead[T](Protocol):
def read(self, n: int = -1, /) -> T: ...
def slurp[T](src: SupportsRead[T]) -> T:
return src.read()
slurp(io.StringIO("x")) # str
slurp(io.BytesIO(b"x")) # bytesOne function now works on text files, binary files, sockets wrapped as files and your own test doubles, and the return type follows the source.
@runtime_checkable is weaker than it looks. It lets you use a protocol in isinstance, but the runtime check only asks "does the object have attributes with these names?". It never looks at signatures or types:
Press Run (⌘ Enter) to see what happens.Door passes even though its close is a string. Protocols with data members also refuse issubclass. Treat a runtime-checkable protocol as a cheap shape sniff for dispatch, and rely on the static checker for correctness. Runtime isinstance checks against protocols are also much slower than against a normal class, so keep them out of hot loops.
What does this print?
from typing import Protocol, runtime_checkable
@runtime_checkable
class Sender(Protocol):
def send(self, to: str, body: str) -> bool: ...
class Pigeon:
def send(self) -> None:
pass
print(isinstance(Pigeon(), Sender))Protocol or ABC?
Use a Protocol when you describe what you need from a parameter, especially for objects you do not own. Use an abstract base class when you are building a family of classes that should share code (concrete helper methods) and you want registration to be explicit. The standard library's collections.abc classes are ABCs, but checkers treat the simple ones like Iterable, Sized and Container structurally, so any class with __iter__ counts as an Iterable.
Self for fluent methods and alternative constructors
Before Python 3.11, a method that returned self was awkward to type. Annotating -> "QueryBuilder" breaks subclasses: calling it on a subclass gives back the base type and you lose the subclass's methods. typing.Self means "whatever class this was called on":
from typing import Self
class QueryBuilder:
def __init__(self) -> None:
self.parts: list[str] = []
def where(self, cond: str) -> Self:
self.parts.append(cond)
return self
@classmethod
def create(cls) -> Self:
return cls()
class AuditedQuery(QueryBuilder):
def audited(self) -> Self:
return self
q = AuditedQuery.create().where("active").audited() # AuditedQueryUse Self for builders, copy-style methods, and from_json or from_row classmethod constructors. Do not use it for a method that always builds a base-class instance, because the annotation would then lie for subclasses.
Putting it together: a typed generic repository
Here is the repository from the introduction. It combines a bound to a protocol, Self, Callable, and accept-wide parameters:
Press Run (⌘ Enter) to see what happens.Design choices worth defending in review:
T: HasIdwith a property protocol, so frozen dataclasses, Pydantic models and plain classes all fit.InMemoryRepo[str]()is rejected by the checker.from_itemsaccepts anyIterable[T]and returnsSelf, so a subclass likeAuditedRepokeeps its own type.wherereturns a concretelist[T], so callers can index and sort the result.- The explicit
InMemoryRepo[User]matters. mypy infersTfrom the arguments offrom_items, but pyright leavesTunsolved when you call a classmethod on the bare generic class. Writing the parameter keeps both checkers precise.
In a real service, this class becomes the in-memory fake behind a UserRepository protocol that your database class also satisfies. Tests use the fake, production uses Postgres, and the service code never knows the difference.
Person objects and never modifies the group. Which parameter type serves callers best?- PEP 695 syntax
- Python 3.12 syntax for generics:
def f[T],class C[T]andtype Alias[T] = ..., with parameters scoped to their declaration. - bound
- An upper limit on a type variable,
[T: HasId]. The caller's exact type still flows through. - constraint
- A fixed list of allowed types,
[S: (str, bytes)]. The variable resolves to exactly one of them. - invariant
- No subtype relation between
C[Dog]andC[Animal]. Required for anything you can write into, likelist. - covariant
C[Dog]is a subtype ofC[Animal]. Safe for read-only types likeSequenceand return types.- contravariant
- The relation flips:
Callable[[Animal], R]is usable whereCallable[[Dog], R]is expected. Applies to argument types. - Protocol
- A structural type: any class with matching members satisfies it, without inheriting from it.