Sub topic 6
How a type checker decides a class matches
This chapter assumes you can write a basic Protocol, you know type hints, and you have run mypy or pyright at least once. Here you will learn the exact rules a checker applies when it compares a class to a protocol. That helps you predict errors and read their messages.
Where the check happens
A class never declares that it implements a protocol. The checker therefore has nothing to verify when it sees the class definition. It compares the two only where a value of one type flows into a place that expects the other. That happens when you:
- pass an argument to a parameter annotated with the protocol
- assign to a variable annotated with the protocol
- return a value from a function whose return type is the protocol
The error shows up at that line, not on the class. If a class is never used where the protocol is expected, no check ever runs.
The comparison goes member by member. For every member the protocol declares, the candidate class must provide a member that is compatible. Members the candidate has beyond that are ignored.
Missing members and extra members
The simplest rule is that every protocol member must exist on the candidate. The reverse is not required.
from typing import Protocol
class SupportsArea(Protocol):
def area(self) -> float: ...
class Square:
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
def perimeter(self) -> float: # extra member: ignored by the check
return 4 * self.side
class Point:
pass
def total_area(shapes: list[SupportsArea]) -> float:
return sum(s.area() for s in shapes)
print(total_area([Square(2), Square(3)]))
def _rejected() -> None:
total_area([Point()]) # error: Point has no member "area"Inside total_area, the checker only lets you use area. Calling s.perimeter() there would be an error even though Square has it, because the parameter is typed as the protocol, not as Square.
Method compatibility: calls must keep working
For methods, the checker asks one question: can every call that is valid on the protocol's method also be made on the candidate's method? If so, the candidate is a substitute. This gives the standard rules:
- Parameters are contravariant. The candidate may accept a wider type than the protocol declares, never a narrower one.
- The return type is covariant. The candidate may return a narrower type than the protocol declares, never a wider one.
from typing import Protocol
class Parser(Protocol):
def parse(self, text: str) -> float: ...
class IntParser:
def parse(self, text: str) -> int: # narrower return: ok, int is usable as float
return int(text)
class AnyParser:
def parse(self, text: object) -> int: # wider parameter: ok, accepts every str
return int(str(text))
class BytesParser:
def parse(self, text: bytes) -> float: # narrower parameter: rejected
return float(text)
def run(parser: Parser) -> float:
return parser.parse("3")
print(run(IntParser()))
print(run(AnyParser()))
def _rejected() -> None:
run(BytesParser()) # error: parse() cannot accept a strBytesParser fails because run may call parse("3") with a str, and BytesParser.parse does not promise to handle one.
Parameter names and positional-only parameters
A call can pass an argument by keyword, so for an ordinary parameter the name is part of the contract. If the protocol declares factor and the candidate calls it ratio, the call scaler.scale(factor=2.0) would break.
from typing import Protocol
class Scaler(Protocol):
def scale(self, factor: float) -> float: ...
class PositionalScaler(Protocol):
def scale(self, factor: float, /) -> float: ...
class Doubler:
def scale(self, factor: float) -> float:
return factor * 2
class Renamed:
def scale(self, ratio: float) -> float:
return ratio * 2
def use_scaler(s: Scaler) -> float:
return s.scale(factor=2.0)
def use_positional(s: PositionalScaler) -> float:
return s.scale(2.0)
print(use_scaler(Doubler()))
print(use_positional(Renamed())) # ok: protocol never lets callers use the keyword
def _rejected() -> None:
use_scaler(Renamed()) # error: parameter name differsThe / in PositionalScaler makes the parameter positional-only. Callers cannot use the keyword, so the candidate may name it anything. This is why protocols for operators such as __lt__ use / in their signatures. The same applies to names that start with two underscores in older code.
Extra parameters and defaults
The candidate may add parameters only if callers of the protocol's version can still omit them.
from typing import Protocol
class Greeter(Protocol):
def greet(self, name: str) -> str: ...
class Polite:
def greet(self, name: str, title: str = "Dr.") -> str: # extra with default: ok
return f"Hello, {title} {name}"
class Strict:
def greet(self, name: str, title: str) -> str: # extra required: rejected
return f"Hello, {title} {name}"
def welcome(g: Greeter) -> str:
return g.greet("Ada")
print(welcome(Polite()))
def _rejected() -> None:
welcome(Strict()) # error: call greet("Ada") is missing "title"The reverse also holds. If the protocol has a defaulted parameter, the candidate must also accept the call without it, so it needs a default too. The candidate also cannot drop *args or **kwargs that the protocol declares.
Attributes: mutability matters
A plain attribute in a protocol, such as label: str, promises that callers can both read and assign it. The candidate must therefore provide a settable attribute of exactly that type. The type is invariant because assignment makes it work in both directions.
from dataclasses import dataclass
from typing import Protocol
class HasLabel(Protocol):
label: str
class Plain:
def __init__(self) -> None:
self.label = "plain"
@dataclass(frozen=True)
class Frozen:
label: str
def relabel(item: HasLabel) -> None:
item.label = "changed"
relabel(Plain())
def _rejected() -> None:
relabel(Frozen("fixed")) # error: protocol attribute is writable, Frozen's is read-onlyIf the protocol declares label: float and the candidate has label: int, the checker also rejects it. A caller could assign 1.5 through the protocol, and that would break the candidate's int promise.
If you only need to read the value, declare a read-only property in the protocol. The candidate may then satisfy it with a plain attribute, a property, or a frozen dataclass field. The candidate's type only needs to be a subtype of the declared one, which is the covariant case.
from dataclasses import dataclass
from typing import Protocol
class ReadsLabel(Protocol):
@property
def label(self) -> float: ...
@dataclass(frozen=True)
class Frozen:
label: int # int is usable as float, and read-only access is enough
def show(item: ReadsLabel) -> str:
return f"label={item.label}"
print(show(Frozen(3)))Prefer read-only properties in protocols whenever the function does not assign to the attribute. They accept more classes.
Summary of the rules
| Protocol member | Candidate must provide | Type rule |
|---|---|---|
| Method | A callable that accepts every call the protocol allows | Parameters contravariant, return covariant |
| Ordinary parameter | Same name, or a compatible `*args`/`**kwargs` | Name is part of the contract |
| Positional-only parameter | Any name in that position | Position and type only |
| Attribute `x: T` | A writable attribute | Exactly `T` (invariant) |
| Read-only property | Attribute, property or frozen field | Subtype of the declared type |
| Members the protocol lacks | Nothing | Ignored |
Reading the checker's output
Checkers differ in wording, but the report usually has two parts: the failing argument and a note naming the conflicting members. For run(BytesParser()), mypy reports an incompatible argument type, expected Parser, and then lists parse with the expected and the actual signature. Pyright prints a similar tree under the assignment error. Read the expected and actual signatures side by side. The mismatch is almost always in one of four places: a name, a parameter type, a return type, or mutability.
Exercise
Given the protocol below, which of the two classes does a type checker accept, and why? class Sink(Protocol): def write(self, data: bytes, /) -> int: ... name: str class A: name: str = "a" def write(self, payload: bytes) -> int: return len(payload) class B: @property def name(self) -> str: return "b" def write(self, data: bytes, /) -> int: return len(data)
Show answer
A is accepted. The positional-only parameter in the protocol lets A use the name payload, and name is a writable str attribute. B is rejected. The protocol declares name as a plain attribute, which callers may assign, but B exposes it as a read-only property. To accept B, the protocol would declare name as a read-only property.
Exercise
A protocol declares def load(self, path: str) -> dict[str, object]. A candidate defines def load(self, path: str, strict: bool) -> dict[str, object]. Why is it rejected, and what is the smallest change to the candidate that makes it match?
Show answer
Callers of the protocol write load("x") without strict, so the candidate would fail with a missing argument. Giving strict a default value, as in strict: bool = False, makes every protocol call valid, and the candidate then matches.