Sub topic 5
Methods, attributes and read-only properties in protocols
A protocol is a list of members that a class must have. Each member can be a method, a plain attribute, or a property, and each kind makes a different promise to the type checker. This chapter covers what each declaration requires and how a mistake shows up.
This chapter assumes you can write a basic Protocol class and annotate a parameter with it. It also assumes you know how a checker such as mypy or pyright reports an incompatible argument. Checker behavior can differ in small ways between tools. The rules below follow the typing specification.
Methods: the signature is the contract
A method in a protocol is written as a signature with ... as its body. A class matches when its method can be called in every way the protocol's method can be called.
from typing import Protocol
class Reader(Protocol):
def read(self, size: int = -1) -> bytes: ...
class FileLike:
def read(self, size: int = -1) -> bytes:
data = b"data"
return data if size < 0 else data[:size]
class Renamed:
def read(self, n: int = -1) -> bytes:
return b""
def consume(source: Reader) -> bytes:
return source.read(2)
print(consume(FileLike()))
# consume(Renamed()) # rejected: parameter "n" is not named "size"Renamed.read would work at runtime. A caller holding a Reader is allowed to write source.read(size=2), though, and that call would fail on Renamed. The checker therefore rejects it.
If callers never pass the argument by keyword, make the parameter positional-only with /. Then the name no longer matters:
from typing import Protocol
class Reader(Protocol):
def read(self, size: int = -1, /) -> bytes: ...
class Renamed:
def read(self, n: int = -1) -> bytes:
return b""
def consume(source: Reader) -> bytes:
return source.read(2)
print(consume(Renamed())) # accepted: callers can only pass size positionallyThe matching rules for methods are the usual substitution rules:
- Parameter types are contravariant. The implementation may accept a wider type than the protocol declares, but not a narrower one.
- The return type is covariant. The implementation may return a narrower type than the protocol declares.
- The implementation may add extra parameters only if they have defaults. A caller that follows the protocol's signature must still work.
- The implementation may not drop a parameter that the protocol allows callers to pass.
Attributes: a plain annotation means read and write
To require data instead of behavior, annotate a name in the protocol body without assigning a value:
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
counter = Counter()
bump(counter)
print(counter.count) # 1
# bump(Frozen()) # rejected: the protocol requires a writable countA plain count: int tells the checker that a holder of the protocol may read the attribute and assign to it. bump does both, so the protocol has to promise both. Frozen offers only a getter, so it cannot satisfy it.
Mutable attributes are invariant
A writable attribute must have exactly the declared type. A subtype is not accepted:
from typing import Protocol
class Point(Protocol):
x: float
class IntPoint:
def __init__(self) -> None:
self.x: int = 0
def nudge(p: Point) -> None:
p.x = 0.5 # legal for a Point, because x is declared float
# nudge(IntPoint()) # rejected: IntPoint.x is int, and 0.5 would break it
print(IntPoint().x)This surprises many people, because int is accepted where float is expected in most other places. The difference is that this protocol allows writes. If nudge could receive an IntPoint, it would store a float in an attribute declared int. Invariance prevents that. The same rule is why list[int] is not a list[float].
Read-only properties: the flexible choice
If callers only read a value, declare it as a property with no setter:
from dataclasses import dataclass
from typing import NamedTuple, Protocol
class HasX(Protocol):
@property
def x(self) -> float: ...
class Plain:
def __init__(self) -> None:
self.x = 1
class Computed:
@property
def x(self) -> int:
return 2
@dataclass(frozen=True)
class Frozen:
x: int
class Pair(NamedTuple):
x: int
y: int
def show(item: HasX) -> str:
return f"x={item.x}"
for candidate in (Plain(), Computed(), Frozen(3), Pair(4, 5)):
print(show(candidate))All four classes are accepted. The protocol promises only reads, so the implementation can be an ordinary attribute, a property, a frozen dataclass field, or a named tuple field. Because there are no writes, the type is covariant, and int satisfies float. A read-only property is more permissive than a plain attribute in both ways.
Choose the weakest declaration that covers what your function does.
| Protocol declares | Plain attribute in class | Read-only property in class | Property with setter in class | Frozen dataclass field |
|---|---|---|---|---|
| `x: int` | Accepted | Rejected | Accepted | Rejected |
| `x: float` | Rejected if declared `int` | Rejected | Rejected if the type is not exactly `float` | Rejected |
| Read-only `@property` returning `float` | Accepted, even if `int` | Accepted | Accepted | Accepted |
Rows two and three show the cost of a mutable declaration. A mutable declaration excludes many reasonable classes, while a read-only property excludes almost none.
Writable properties
If callers need to assign but you want classes with validation to qualify, declare a property with a setter in the protocol:
from typing import Protocol
class Leveled(Protocol):
@property
def level(self) -> int: ...
@level.setter
def level(self, value: int) -> None: ...
class Logger:
def __init__(self) -> None:
self._level = 0
@property
def level(self) -> int:
return self._level
@level.setter
def level(self, value: int) -> None:
if value < 0:
raise ValueError("level must be non-negative")
self._level = value
def raise_level(item: Leveled) -> None:
item.level += 1
logger = Logger()
raise_level(logger)
print(logger.level) # 1For type checking, this declaration means the same as level: int. Plain attributes and properties with setters both satisfy it. Use the plain annotation unless you want the setter spelled out.
Combining members
A protocol can mix all three kinds. Here a function needs a read-only name, a writable counter, and one operation:
from typing import Protocol
class Job(Protocol):
attempts: int
@property
def name(self) -> str: ...
def run(self) -> bool: ...
class EmailJob:
attempts = 0
def __init__(self, recipient: str) -> None:
self.recipient = recipient
@property
def name(self) -> str:
return f"email:{self.recipient}"
def run(self) -> bool:
print(f"sending to {self.recipient}")
return True
def execute(job: Job) -> None:
job.attempts += 1
ok = job.run()
print(f"{job.name} attempt {job.attempts}: {'ok' if ok else 'failed'}")
execute(EmailJob("[email protected]"))EmailJob defines attempts in its class body instead of __init__. A checker accepts that as an instance attribute for this protocol. EmailJob has extra members, such as recipient, and that is fine. Protocols set a minimum, not an exact shape.
Deciding which declaration to use
Common errors
- Declaring
name: strwhen you only read it. Classes with read-only properties and frozen dataclasses are rejected for no good reason. Switch to a read-only@property. - Mismatched parameter names in methods. An implementation with
ninstead ofsizeis rejected unless the protocol marks the parameter positional-only. - Expecting a subtype to satisfy a mutable attribute.
x: intdoes not satisfyx: floatwhen writes are allowed. Use a read-only property if you only read. - Treating the protocol's attribute annotation as a default.
count: intin a protocol declares a requirement. It does not create a value, andCounter.countdoes not exist unless the implementing class creates it. - Confusing a protocol property with a method. A property is read as
item.name. A method is called asitem.name(). A class that definesnameas a method does not satisfy a property protocol, becausestrandCallable[[], str]are different types.
Exercise
A function total(items) only reads item.price (a number) from each element. Write a protocol for the parameter, and explain why a plain price: float annotation would be a worse choice than the one you wrote.
Show answer
Declare class Priced(Protocol): with @property and def price(self) -> float: ..., then annotate items: Iterable[Priced]. A plain price: float requires a writable attribute of exactly type float. It would reject classes with an int price, classes with a read-only property, and frozen dataclasses. A read-only property accepts all of them, because reads are covariant.
Exercise
Given class Config(Protocol): timeout: int and a class Settings with a read-only @property def timeout(self) -> int, does Settings satisfy Config? What single change to the protocol makes it match, and what does that change stop callers from doing?
Show answer
No. The plain annotation requires a writable attribute, and Settings offers only a getter. Change the protocol to declare timeout as a read-only @property returning int. Callers of the protocol can then no longer assign to config.timeout, and the checker reports any such assignment.