Sub topic 5
Methods, attributes and read-only properties in protocols
This chapter assumes you can write Python classes, use basic type hints, and know that a type checker such as mypy or pyright reads annotations without running your code. You should also have seen a minimal Protocol class.
What a protocol can require
A protocol describes the members an object must have. Three kinds of member matter in practice:
- Methods, with a name, parameters and a return type.
- Attributes, declared as annotated names in the class body.
- Properties, declared with
@property.
A class satisfies the protocol if it has every member with a compatible type. It never has to inherit from the protocol.
Methods
A method in a protocol has a body of ..., because it only describes a shape. The checker compares the parameters and return type of the method on the candidate class with the declared ones.
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Resource:
def close(self) -> None:
print("closed")
def shutdown(item: SupportsClose) -> None:
item.close()
shutdown(Resource())Attributes versus read-only properties
Protocol members can be declared as attributes, which means callers may read and write them:
from typing import Protocol
class HasName(Protocol):
name: strThis is a strong requirement. Any class passed in must have a name that is a writable str. A read-only property would be rejected, and so would a frozen dataclass field.
Most functions only read the value. For those, declare a read-only property:
from typing import Protocol
class Named(Protocol):
@property
def name(self) -> str: ...
class User:
def __init__(self, name: str) -> None:
self.name = name
class Product:
@property
def name(self) -> str:
return "widget"
def greet(item: Named) -> str:
return f"Hello, {item.name}"
print(greet(User("Ada")))
print(greet(Product()))User stores a plain attribute and Product computes a property. Both satisfy Named, because the protocol only says that reading item.name gives a str. The protocol constrains what the caller needs and nothing more.
The table summarizes the rule.
| Protocol declares | Plain attribute | Read-write property | Read-only property |
|---|---|---|---|
| `name: str` | Accepted | Accepted | Rejected |
| `@property def name` | Accepted | Accepted | Accepted |
Common errors
Declaring a writable attribute when you only read it is the most frequent mistake. It makes the protocol reject classes that are perfectly usable, such as frozen dataclasses and classes that expose a computed property.
Other errors to watch for:
- Mismatched types. A protocol attribute
name: stris not satisfied by a class whosenameisstr | None. A writable attribute must match exactly, because a checker must allow both reads and writes. - Missing
self. Methods in a protocol takeselflike any method. Leaving it out changes the signature the checker sees. - Wrong parameter names. A candidate method with a different parameter name can be rejected when callers might pass that argument by keyword. Make the parameters positional-only with
/if the name should not matter.
Exercise
Exercise
A function label(item) only reads item.title, which must be a str. A teammate wrote the parameter type as a protocol with title: str. A frozen dataclass with a title field is rejected by the type checker. How do you change the protocol so the dataclass is accepted?
Show answer
Declare title as a read-only property: @property on def title(self) -> str: .... A plain attribute declaration requires a writable member, and a frozen dataclass field is read-only. A read-only property only requires that reading title gives a str, so the dataclass satisfies it.