Sub topic 3
Structural subtyping: compatible by shape
This chapter assumes you can write Python classes and functions, use basic type hints, understand inheritance and abstract base classes, and know that a static type checker such as mypy or pyright reads your annotations without running the program.
Two ways to decide that a type fits
A type checker must decide whether an argument of type B can be used where type A is expected. There are two rules for this.
- Nominal subtyping:
BfitsAonly ifBdeclares the relationship, usually withclass B(A). The name and the inheritance chain decide. - Structural subtyping:
BfitsAifBhas every member thatArequires, with compatible types. The shape decides, and inheritance is irrelevant.
Python's ordinary class system is nominal. Duck typing is the structural idea applied at runtime: if an object has a speak method, calling speak works. Structural subtyping brings that same idea into static checking, so the checker can verify the shape before the program runs.
The nominal baseline
Here a function demands an abstract base class.
from abc import ABC, abstractmethod
class Closer(ABC):
@abstractmethod
def close(self) -> None: ...
class File(Closer):
def close(self) -> None:
print("file closed")
class Socket:
def close(self) -> None:
print("socket closed")
def shutdown(item: Closer) -> None:
item.close()
shutdown(File()) # accepted: File inherits from Closer
shutdown(Socket()) # a type checker rejects this: Socket does not inherit from CloserThe last call would run fine, because Socket has a close method. The checker rejects it only because Socket never declared the relationship. If Socket comes from a library you cannot edit, you cannot fix this by inheriting.
The structural version
A Protocol class describes a shape instead of a family. The next chapter covers the syntax in detail. For now, read it as "anything with a matching close method".
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Socket:
def close(self) -> None:
print("socket closed")
def shutdown(item: SupportsClose) -> None:
item.close()
shutdown(Socket()) # accepted: Socket has a matching close()
shutdown(42) # rejected by a type checker: int has no close()Socket does not mention SupportsClose anywhere. The checker compares the two shapes and finds that Socket provides what the protocol requires.
What "compatible" means
Having a member with the right name is not enough. The checker also compares types:
- Parameter types must accept at least what the protocol's version accepts.
- The return type must be usable wherever the protocol's return type is expected.
- Required attributes must exist with compatible types.
A class whose close takes a required extra argument would be rejected, because a caller holding a SupportsClose would call close() with no arguments.
| Question | Nominal | Structural |
|---|---|---|
| What makes `B` fit `A`? | `B` inherits from `A` | `B` has the members `A` requires |
| Must you edit `B`? | Yes, to add the base class | No |
| Works with third-party classes? | Only through wrappers or registration | Yes, if the shape matches |
| Where is it checked? | Static checker and `isinstance` | Static checker (runtime support is limited) |
Why this matters
Structural subtyping lets the consumer of an object define the contract, instead of forcing every producer to import and inherit from a shared base. The function shutdown states the small slice of behavior it needs, and any class that provides it qualifies. This keeps coupling low and works with classes you did not write. The cost is that the relationship is implicit, so a reader cannot find "who implements this" by searching for subclasses.
Exercise
A class Logger has the method def write(self, text: str) -> None. A function takes sink: SupportsWrite, where the protocol SupportsWrite requires def write(self, text: str) -> None. Logger does not inherit from SupportsWrite. Will a type checker accept Logger() as the argument, and why?
Show answer
Yes. Under structural subtyping the checker compares members, and Logger has a write method with a compatible signature. Inheritance is not required.