`Protocol` and `TypedDict`
Protocol describes a type by the methods and attributes it has, not by its class tree. TypedDict describes a dictionary by its keys and the type of each value. Both live in typing and help checkers without changing runtime behaviour.
Detailed Explanation
Inheritance is not the only way two objects can be substitutable. If your function needs read() and close(), a file, a socket, and a fake in a test all work. In Java you would declare an interface and implement it. In Python you can, with an ABC, or you can write a Protocol and let structural typing do the matching.
class Closer(Protocol):
def close(self) -> None: ...
A checker accepts any object with a compatible close. You do not inherit from Closer. At runtime, Protocol is an ordinary ABC unless you mark it @runtime_checkable, in which case isinstance looks for the attributes (not full signature compatibility).
TypedDict is the other hole in dict[str, Any]. JSON objects and database rows are dicts with known keys. class UserRow(TypedDict): id: int; email: str tells a checker that row["email"] is a str and that row["missing"] is a mistake. Required keys are required. NotRequired[int] and total=False loosen that. TypedDict is still a dict at runtime: UserRow(id=1, email="a@b.c") is a constructor for a plain dict, not a new class of object.
Use a dataclass or a Pydantic model when you want an object with attributes, validation, and methods. Use TypedDict when the value really is a dict — because a library returns one, or because you are describing a JSON shape you do not control.
Protocol can describe mappings too, but TypedDict is the dedicated tool for key sets. Protocol can have methods, properties, and class attributes. A protocol with no methods and only data fields is usually a dataclass or a TypedDict in disguise.
Both features are for checkers first. They do not prevent a missing key at runtime. Validate at the system boundary, then let the hints describe the validated shape inside the program.
Code Examples
from typing import Protocol
class Reader(Protocol):
def read(self, n: int = -1) -> str: ...
def slurp(source: Reader) -> str:
return source.read()
print(slurp(open(__file__, encoding="utf-8"))[:7])from typing import TypedDict, NotRequired
class UserRow(TypedDict):
id: int
email: str
nickname: NotRequired[str]
def greeting(row: UserRow) -> str:
return row.get("nickname") or row["email"]
print(greeting({"id": 1, "email": "ada@example.com"}))from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
print(isinstance(open(__file__, encoding="utf-8"), Closeable)) # TrueCommon Gotchas
`TypedDict` is still a `dict`
`row.email` is an `AttributeError`. Use `row["email"]`. Extra keys may exist at runtime even if the checker forbids them.
`isinstance` on a Protocol needs `@runtime_checkable`
without it you get `TypeError`. Even then, `isinstance` does not check method signatures.
Inheritance is optional for Protocol, required for ABCs
do not `class File(Reader)` unless you want the runtime ABC registry. Structural match is the point.
`total=False` makes every key optional
prefer `NotRequired` on the few keys that are optional so required keys stay required.