Sub topic 9
Structural typing with Protocol
This chapter assumes you can annotate functions, read checker errors from mypy or Pyright, and understand unions and narrowing from earlier chapters. It covers how Protocol lets you describe an interface by its shape, where that differs from inheritance, and where it can mislead you.
Nominal and structural typing
Normal class annotations are nominal. A parameter annotated Animal accepts only instances of Animal or its subclasses. The class must name its parent in its definition.
Python code often ignores that rule. A function that only calls .close() on its argument works with files, sockets, database connections, and your own classes. None of them share a base class. This habit is called duck typing.
A Protocol lets a checker verify duck typing statically. You list the members a value must have, and any class with matching members is accepted. This is structural typing: compatibility depends on the shape of the class, not on its declared ancestry.
Defining and using a protocol
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Connection:
def close(self) -> None:
print("closed")
def shutdown(resource: SupportsClose) -> None:
resource.close()
shutdown(Connection())Connection never mentions SupportsClose. The checker compares the two. Connection has a close method that takes no arguments and returns None, so it matches. The ... body is the conventional placeholder for a method that is only a signature.
What counts as a match
A class matches only if every protocol member is present with a compatible type. Compatibility is stricter than name matching. Here is a class with the right method name but a different signature:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Resource:
def close(self, force: bool) -> None:
print("closed", force)
def shutdown(resource: SupportsClose) -> None:
resource.close()
shutdown(Resource()) # flagged: close() requires an argumentBoth mypy and Pyright reject the last call. If it ran, resource.close() would raise a TypeError. The error message lists which members of Resource conflict with the protocol. Read that note first, because it names the exact mismatch.
Parameter and return types follow the usual variance rules. Return types are covariant, so an implementation may return a subtype of what the protocol declares. Parameters are contravariant, so an implementation may accept a wider type. An implementation may also add optional parameters that the protocol does not mention.
Parameter names matter for ordinary parameters. A protocol method def read(self, size: int) -> bytes can be called as read(size=10). An implementation whose parameter is named n therefore does not match. To let implementations choose their own names, make the parameter positional-only with /, as in def read(self, size: int, /) -> bytes.
Attributes and properties
Protocols can declare attributes as well as methods:
from dataclasses import dataclass
from typing import Protocol
class HasName(Protocol):
@property
def name(self) -> str: ...
@dataclass(frozen=True)
class User:
name: str
def label(item: HasName) -> str:
return f"<{item.name}>"
print(label(User("ada")))The protocol uses a read-only @property. This matters. If the protocol declared a plain name: str, it would promise that callers can assign to name. A frozen dataclass forbids assignment, so the checker would reject User. A mutable attribute is also invariant: a class whose name is a narrower type than str cannot satisfy a writable name: str. Declare read-only properties unless the function really assigns to the attribute.
Protocols and abstract base classes
Both Protocol and abc.ABC describe interfaces. They differ in what they require of the implementer.
| Question | `Protocol` | `ABC` |
|---|---|---|
| Must implementers inherit from it? | No | Yes |
| Can it describe a class you do not control? | Yes | Only by registering a virtual subclass |
| Does it enforce anything at runtime? | Not by default | Instantiation fails if abstract methods are missing |
| Can it supply shared method code? | Only to classes that explicitly subclass it | Yes, to all subclasses |
Use a protocol for a function parameter that should accept anything shaped right, especially types from other libraries. Use an ABC when you own the whole hierarchy and want runtime enforcement, or want to share implementation.
You can also subclass a protocol explicitly: class Connection(SupportsClose): .... The checker then verifies the class against the protocol at the class definition, which gives an earlier and clearer error than a failure at a later call site. An explicit subclass also inherits any default method bodies the protocol provides. Methods in a protocol that are only ... and have no body inherited are not safe to call through super().
Runtime checks are shallower than static checks
A protocol is a static construct. Passing it to isinstance raises a TypeError unless you decorate it with @runtime_checkable:
from typing import Protocol, runtime_checkable
@runtime_checkable
class SupportsClose(Protocol):
def close(self) -> None: ...
class Wrong:
def close(self, force: bool) -> None: ...
print(isinstance(Wrong(), SupportsClose)) # TrueThe result is True even though a checker rejects Wrong for this protocol. At runtime, isinstance only checks that an attribute named close exists. It does not compare signatures or types. Protocols that declare data attributes also cannot be used with issubclass.
Checkers do narrow with isinstance on a runtime-checkable protocol, so inside the if branch you get the protocol type. That narrowing is only as reliable as the shallow check behind it.
Common errors and gotchas
- Missing
selfor wrong return type in the protocol. A protocol method written asdef close() -> Noneis not a method of the shape you meant. Writeselflike in any method. - Asking for a mutable attribute you never write. This rejects frozen dataclasses and read-only properties. Use a property in the protocol.
- Assuming a match inside untyped code. If the implementing method has no annotations, the checker treats its parameters and return as
Any, so mismatches may go unreported. Annotate the implementation. - Instantiating the protocol. You cannot create an instance of a protocol class directly. The checker reports it, and Python raises a
TypeError. - Differences between tools. mypy and Pyright agree on straightforward cases. They can differ on subtle member-variance and overload matching, so run both when a protocol error looks wrong.
Exercise
A protocol declares name: str. You pass an instance of a @dataclass(frozen=True) class that has a field name: str, and the checker reports an incompatible type. Why does it fail, and how do you fix the protocol?
Show answer
A plain name: str in a protocol means the attribute is writable. A frozen dataclass does not allow assignment, so it is not a compatible implementation. Fix the protocol by declaring the attribute as a read-only property: @property followed by def name(self) -> str: .... The frozen dataclass then matches, because the function only reads name.
Exercise
isinstance(obj, SupportsClose) returns True for a class whose close method takes a required force argument. Yet the checker rejects passing that object to shutdown. Why do the two results differ?
Show answer
A @runtime_checkable protocol makes isinstance check only that a member named close exists. The static checker compares full signatures and sees that close(force) cannot be called as close(). Use the checker's result as the guarantee.