Sub topic 7
Explicitly subclassing a protocol
This chapter assumes you can define a Protocol and know that a type checker matches classes to it by shape. It covers the other option: naming the protocol in a class's bases. You will see what that changes at runtime and in the checker, when it helps, and where it goes wrong.
Implicit and explicit implementation
A class satisfies a protocol implicitly when it has the right members and never mentions the protocol. A class satisfies it explicitly when the protocol appears in its base list. Both are valid, and the checker treats the resulting instances as compatible with the protocol type.
from typing import Protocol
class Shape(Protocol):
def area(self) -> float: ...
class Circle: # implicit: no mention of Shape
def __init__(self, radius: float) -> None:
self.radius = radius
def area(self) -> float:
return 3.14159 * self.radius ** 2
class Square(Shape): # explicit: Shape is a base class
def __init__(self, side: float) -> None:
self.side = side
def area(self) -> float:
return self.side ** 2
def total_area(shapes: list[Shape]) -> float:
return sum(s.area() for s in shapes)
print(total_area([Circle(1.0), Square(2.0)]))Both Circle and Square are accepted by total_area. The difference is what the checker does with Square. Because Shape is a declared base, the checker validates Square as a subclass at the point where you define it. A wrong signature is reported on the class statement or the method, not later where the object is passed to a function.
What explicit subclassing changes
Subclassing a protocol turns your class into an ordinary class with that protocol as a base. It is not a protocol itself, so you can instantiate it. The protocol's members now behave like inherited members.
| Aspect | Implicit (no base) | Explicit (protocol as base) |
|---|---|---|
| Where errors appear | At each call site that passes the object | At the class definition (override checks) |
| Inherits default method bodies | No | Yes |
| Can use `@abstractmethod` enforcement | No | Yes |
| Depends on importing the protocol | No | Yes |
| `isinstance(obj, YourClass)` | Works | Works |
| Reader sees the intent | Only by inspection | Directly in the class header |
The import dependency matters for library design. If a protocol lives in your package, a third-party class cannot subclass it without importing your package. Implicit matching has no such coupling.
Inheriting default implementations
A protocol method may have a real body. Implicit implementers never receive it, because they do not inherit anything. Explicit subclasses do.
from typing import Protocol
class HasName(Protocol):
name: str
def greet(self) -> str:
return f"Hello, {self.name}"
class Person(HasName):
def __init__(self, name: str) -> None:
self.name = name
print(Person("Ada").greet())This prints Hello, Ada. Person gets greet for free and supplies name itself.
Note that name: str in the protocol is only an annotation. It creates no class attribute, so an explicit subclass must assign name, normally in __init__. If it does not, reading self.name raises AttributeError. Some checkers flag a protocol attribute that is never initialized in an explicit subclass, but you should not rely on that.
The same default method is a trap for a structurally matched class. A class that merely has a name attribute satisfies HasName for the checker, but calling greet on it fails, because it never inherited greet. When a protocol carries real method bodies, say so in its documentation, or restrict those bodies to a class meant to be inherited.
Making missing members an error
A protocol method written as ... returns None when called on an explicit subclass that forgot to override it. This is a silent bug. Two mechanisms prevent it.
@abstractmethod.Protocoluses a metaclass derived fromABCMeta, so the decorator is enforced at runtime for explicit subclasses.- Checker support. Mypy and pyright treat a protocol method with a trivial body (
...,passor a docstring only) as abstract when you subclass the protocol explicitly. Instantiating a subclass that omits it is reported. Check your checker's version and settings, because this behavior has changed over time.
from abc import abstractmethod
from typing import Protocol
class Shape(Protocol):
@abstractmethod
def area(self) -> float: ...
class Incomplete(Shape):
pass
try:
Incomplete()
except TypeError as exc:
print("TypeError:", exc)The call to Incomplete() raises TypeError because area is abstract. The wording of the message differs between Python versions, so do not match on it.
@abstractmethod has no effect on implicit implementers. A class that does not inherit from Shape is never instantiated through Shape, so the decorator never runs. For those classes the checker enforces the contract only where the object is used as a Shape.
Override checks at the class definition
An explicit subclass is held to the usual override rules. Parameters must accept at least what the protocol accepts, and the return type must be a subtype of the protocol's.
from typing import Protocol
class Reader(Protocol):
def read(self, size: int) -> bytes: ...
class GoodReader(Reader):
def read(self, size: int) -> bytes:
return b"x" * size
class BadReader(Reader):
def read(self, size: str) -> bytes: # checker error: incompatible override
return b""The checker reports BadReader.read at its definition. If BadReader had no base, the same mistake would appear only where a BadReader is passed as a Reader. That can be in another module, far from the cause.
Extending a protocol with another protocol
Subclassing a protocol does not make the new class a protocol. To build a larger protocol from smaller ones, list Protocol again as a base.
from typing import Protocol
class Readable(Protocol):
def read(self) -> str: ...
class Writable(Protocol):
def write(self, data: str) -> None: ...
class ReadWrite(Readable, Writable, Protocol):
pass
class Buffer:
def __init__(self) -> None:
self._data = ""
def read(self) -> str:
return self._data
def write(self, data: str) -> None:
self._data += data
def copy(src: Readable, dst: Writable) -> None:
dst.write(src.read())
def roundtrip(stream: ReadWrite) -> str:
stream.write("hi")
return stream.read()
print(roundtrip(Buffer()))Buffer does not inherit from any of these, yet it matches ReadWrite because it has both methods. If you left Protocol out of the ReadWrite bases, ReadWrite would be a plain class. A checker would then require callers to pass real ReadWrite instances, and Buffer would be rejected.
Calling `super()` into a protocol method
An explicit subclass can call the protocol's implementation with super(). This is safe when the protocol method has a real body, as greet does above. It is a bug when the body is just ..., because the call returns None regardless of the declared return type. Mypy reports such calls as unsafe. Do not call super() into a stub method unless the protocol documents that it does something useful.
Mixing explicit bases and other classes
Protocols compose with ordinary bases. Put the protocol in the list like any other base.
from typing import Protocol
class Closeable(Protocol):
def close(self) -> None: ...
class Base:
def __init__(self) -> None:
self.closed = False
class Connection(Base, Closeable):
def close(self) -> None:
self.closed = True
conn = Connection()
conn.close()
print(conn.closed)Connection is a normal class with two bases. Because it names Closeable, the checker confirms the override of close. If a class both inherits from a protocol and relies on being matched structurally elsewhere, nothing conflicts. Inheritance is simply an additional declaration of intent.
When to subclass and when not to
Subclass explicitly when:
- You own both the protocol and the class, and want errors reported at the definition.
- You want to inherit default method bodies.
- You want runtime enforcement of required methods through
@abstractmethod. - You want readers to see which contract a class fulfils.
Leave the protocol out of the bases when:
- The class belongs to a different package that should not import yours.
- The class satisfies several unrelated protocols and listing them all adds noise.
- You want the protocol to describe existing code without changing it.
You can also mix: subclass the protocol in your own implementations and let outside classes match structurally. The function that accepts the protocol type treats both the same way.
Common mistakes
- Expecting
isinstance(obj, SomeProtocol)to work because a class inherits from it. The check is on the protocol class itself, which raisesTypeErrorunless the protocol is@runtime_checkable. The next chapters cover that decorator. - Trying to instantiate the protocol directly.
Shape()raisesTypeError, because protocol classes cannot be instantiated. - Relying on
...bodies as abstract markers without@abstractmethodor checker support, which leaves methods that returnNone. - Defining a protocol attribute with only an annotation and never assigning it in the explicit subclass.
Exercise
You define class Plugin(Protocol) with def run(self) -> None: ..., then write class Logger(Plugin): pass and call Logger().run(). Without @abstractmethod, what happens at runtime, and what two changes would make the mistake visible earlier?
Show answer
At runtime Logger().run() succeeds and returns None, because Logger inherits the stub body from Plugin. The mistake is hidden. Decorating run with @abstractmethod makes Logger() raise TypeError at instantiation. Running a type checker that treats trivial protocol bodies as abstract for explicit subclasses reports the problem before the program runs.
Exercise
You write class ReadWrite(Readable, Writable): ... meaning to create a combined protocol. A class Buffer that has read and write but no base classes is rejected when passed to def f(s: ReadWrite). Why, and how do you fix it?
Show answer
ReadWrite does not list Protocol in its bases, so it is an ordinary class and requires nominal subtyping. Buffer does not inherit from it, so the checker rejects the call. Fix it by writing class ReadWrite(Readable, Writable, Protocol): ....