Sub topic 2
Methods, Attributes, and Properties in Protocols
Assume you know Python classes, inheritance, type annotations, and the purpose of a static type checker such as mypy or pyright.
A Protocol describes the operations an object must provide. A class does not need to inherit from the protocol. The type checker compares the class's shape with the protocol's members.
Methods, attributes, and read-only properties
Protocols can declare methods, attributes, and properties.
from typing import Protocol
class Named(Protocol):
@property
def name(self) -> str: ...
def describe(self) -> str: ...
class User:
def __init__(self, name: str) -> None:
self.name = name
def describe(self) -> str:
return f"User: {self.name}"
class Product:
@property
def name(self) -> str:
return "Keyboard"
def describe(self) -> str:
return f"Product: {self.name}"
def print_description(item: Named) -> None:
print(item.name)
print(item.describe())
print_description(User("Ada"))
print_description(Product())The name property is read-only from the protocol's point of view. A plain instance attribute, such as User.name, can satisfy it. A property, such as Product.name, can also satisfy it. The caller only depends on being able to read a string named name.
How static checking decides a match
A static type checker inspects the members available on the supplied class. It checks that:
- Every required member exists.
- Method parameters and return types are compatible.
- Attribute and property types are compatible.
Inheritance is not required. If BadUser has describe() but no name, passing it to print_description produces a type-checking error. The error appears before the program runs.
> callout note > Protocol compatibility is based on what callers can safely use. Extra methods and attributes are allowed.
Explicitly subclassing a protocol
A class may inherit from a protocol to document its intent:
class ConsoleUser(Named):
def __init__(self, name: str) -> None:
self.name = name
def describe(self) -> str:
return f"Console user: {self.name}"This inheritance is optional. It can make the relationship clearer, but structural matching still allows unrelated classes such as User and Product.
Runtime checks and their limits
Add @runtime_checkable when you need an isinstance check:
from typing import Protocol, runtime_checkable
@runtime_checkable
class Closeable(Protocol):
def close(self) -> None: ...
class FileLike:
def close(self) -> None:
print("closed")
print(isinstance(FileLike(), Closeable)) # TrueThe runtime check verifies that the named member exists. It does not verify the method signature, parameter types, or return type. Static checking remains necessary for detailed type safety.
Exercise
Does a class need to inherit from a protocol to satisfy it?
Show answer
No. A class satisfies a protocol structurally when it provides compatible required members.