Sub topic 6
How a type checker decides a class matches
This chapter assumes you can write Python classes and annotations and have run mypy or pyright at least once. It explains what the checker does when you pass an object to a parameter annotated with a protocol.
The question the checker asks
For shutdown(Resource()), the checker doesn't look at Resource's base classes. It asks whether Resource has every member the protocol declares, and whether each member's type is compatible with the protocol's version.
The checker repeats this for every member. One failure rejects the class.
Methods: parameters and return types
A method is compatible when a call that is valid for the protocol's signature is also valid for the class's signature. This gives two rules:
- Return types are covariant. The class may return the same type or a subtype.
- Parameter types are contravariant. The class must accept at least what the protocol accepts, so it may use a wider type.
Names and kinds matter too. A positional parameter in the protocol can be matched by a positional-or-keyword parameter in the class, but a keyword-only parameter can't stand in for a positional one.
from typing import Protocol
class Reader(Protocol):
def read(self, size: int) -> bytes: ...
class FileLike:
# Accepts everything Reader.read accepts, plus a default: compatible.
def read(self, size: int = -1) -> bytes:
return b"data"
class WrongReturn:
def read(self, size: int) -> str: # str is not bytes
return "data"
class WrongName:
def read_all(self) -> bytes: # no read() at all
return b"data"
def load(source: Reader) -> bytes:
return source.read(4)
print(load(FileLike()))
# load(WrongReturn()) # rejected: return type "str" is incompatible with "bytes"
# load(WrongName()) # rejected: "WrongName" is missing "read"Checker messages usually print the protocol member next to the class member, so read both lines of the error to see which rule failed.
Attributes and mutability
A plain attribute in a protocol, such as count: int, means callers may read and assign it. A class satisfies it only if the attribute is also writable and has exactly the same type. The type must match exactly because a writable attribute is both read and written, so neither a wider nor a narrower type is safe.
A read-only @property in the protocol is weaker. It requires only that the value can be read, so a plain attribute, a property, or a subtype of the declared type all work (see the Named example in the earlier chapter on members).
from typing import Protocol
class HasCount(Protocol):
count: int
class Counter:
def __init__(self) -> None:
self.count = 0
class Frozen:
@property
def count(self) -> int:
return 0
def bump(item: HasCount) -> None:
item.count += 1
bump(Counter())
# bump(Frozen()) # rejected: protocol member "count" is writable,
# # but "Frozen.count" is read-onlyIf a function only reads the value, declare the protocol member as a read-only property. That accepts more classes and states the real requirement.
What the checker ignores
- Inheritance. A class with no relationship to the protocol matches if its members fit.
- Extra members. The class may have any number of members the protocol doesn't mention.
- Behavior. A
close()that does nothing, or raises, still matches. Only types are compared.
Exercise
Exercise
Given class Source(Protocol): def get(self) -> float: ..., which of these classes does a type checker accept: (a) def get(self) -> int, (b) def get(self, default: float = 0.0) -> float, (c) def get(self) -> str? Give the rule behind each answer.
Show answer
(a) and (b) are accepted, (c) is rejected. In (a), int is compatible with float, and return types are covariant, so a narrower return type is fine. In (b), the extra parameter has a default, so every call valid for the protocol is still valid. In (c), str is not compatible with float.