Sub topic 7
Explicitly subclassing a protocol
This chapter assumes you can write a basic Protocol and know how a type checker matches a class to it structurally. Here you will see the other option: naming the protocol in the class's base list.
Structural and explicit are both allowed
A class does not need to inherit from a protocol to satisfy it. It may inherit anyway. The checker then treats the class in two ways at once. It is a nominal subclass, because you declared the relationship. It is also checked structurally, because the protocol defines the required shape.
What explicit subclassing gives you
Subclassing a protocol has three effects.
- Default implementations. A protocol can contain methods with real bodies. Explicit subclasses inherit them, much like a mixin.
- Checking at the class definition. If your class has a method with an incompatible signature, the checker reports it on the class itself. Without inheritance, the error appears later, where you pass the object to a function.
- Visible intent. A reader sees which contract the class is meant to fulfil.
from abc import abstractmethod
from typing import Protocol
class Shape(Protocol):
name: str
@abstractmethod
def area(self) -> float: ...
def describe(self) -> str:
return f"{self.name}: area {self.area():.2f}"
class Square(Shape):
def __init__(self, side: float) -> None:
self.name = "square"
self.side = side
def area(self) -> float:
return self.side ** 2
print(Square(2).describe())This prints square: area 4.00. Square never writes describe. It gets it from Shape.
Protocol classes versus ordinary subclasses
Two rules decide what you get when you inherit.
- A protocol class cannot be instantiated.
Shape()is a type error, and it also fails at runtime. - A subclass is a protocol only if
Protocolis in its bases.class Square(Shape)creates an ordinary class that you can instantiate. To extend a protocol with a new protocol, list both:class Solid(Shape, Protocol).
The silent-method pitfall
A protocol method written as ... has a body that returns None. If a subclass forgets to override it, nothing fails at runtime unless you mark the method abstract.
from abc import abstractmethod
from typing import Protocol
class Closer(Protocol):
def close(self) -> None: ...
class Strict(Protocol):
@abstractmethod
def close(self) -> None: ...
class ForgetfulCloser(Closer):
pass
class ForgetfulStrict(Strict):
pass
ForgetfulCloser().close() # runs, does nothing
try:
ForgetfulStrict()
except TypeError as error:
print(error)The first call does nothing and raises no error. The second class cannot be created, because @abstractmethod makes Python refuse to instantiate it. Some type checkers also warn about the first case, but you should not depend on that. When a protocol will be subclassed explicitly, decorate the required members with @abstractmethod.
Calling super().close() from an override has the same trap. It runs the placeholder body and returns None, which looks like success.
Mixing explicit and structural use
The two styles work together. A function annotated with Shape accepts Square, because it inherits from Shape. It also accepts any other class with a compatible name, area and describe, even one that never mentions Shape. Explicit subclassing is an addition to structural matching and does not replace it.
| Approach | Checker verifies class at definition | Inherits default methods | Needs import of the protocol |
|---|---|---|---|
| Structural only | No, only at use sites | No | No |
| Explicit subclass | Yes | Yes | Yes |
The last column matters across package boundaries. Structural matching lets a library accept your classes without your depending on it. Explicit subclassing ties your code to the module that defines the protocol.
Exercise
A protocol Notifier declares def send(self, text: str) -> None: ... with no decorator. You write class EmailNotifier(Notifier): pass and call EmailNotifier().send("hi"). What happens at runtime, and how do you make the mistake fail early?
Show answer
The call runs the protocol's placeholder body, returns None and raises no error, so the missing implementation goes unnoticed. Decorate send with @abstractmethod in the protocol. Then EmailNotifier() raises a TypeError at instantiation, because the abstract method was not overridden.