Sub topic 3
Structural subtyping: compatible by shape
This chapter explains what structural subtyping is, how it differs from the nominal subtyping and duck typing you have already seen, and what a type checker compares when it decides two types are compatible. It assumes you can write Python classes and functions, use basic type hints, and know what a static type checker such as mypy or pyright does. Protocol syntax comes in the next chapter. Here the goal is the idea behind it.
Two ways to decide that a type fits
Every type system needs a rule for answering one question: may a value of type A be used where type B is expected? Python offers two rules.
- Nominal subtyping.
AfitsBonly ifAis declared as a subclass ofB, directly or through a chain of parents. The relationship is recorded by name, in theclass A(B)line. - Structural subtyping.
AfitsBifAhas everythingBrequires: the same member names, with compatible types. No declaration is needed. The relationship comes from the shape of the class.
Here is the same requirement written both ways.
from abc import ABC, abstractmethod
class Closer(ABC):
@abstractmethod
def close(self) -> None: ...
class NominalFile(Closer): # declared relationship
def close(self) -> None:
print("nominal close")
class OutsideFile: # no declared relationship
def close(self) -> None:
print("outside close")
def shutdown(item: Closer) -> None:
item.close()
shutdown(NominalFile()) # accepted: subclass of Closer
shutdown(OutsideFile()) # rejected by a type checker: not a subclass of CloserAt runtime both calls work, because Python never checks the annotation. A type checker, however, rejects the second call. OutsideFile has a perfectly good close method, but it never declared itself a Closer. Under nominal rules, that is enough to fail.
This is a real cost when the class is not yours. You cannot add Closer as a parent of a class from a third-party library. You can wrap it or register it, but both are extra work for a relationship that is already obvious from its methods.
Duck typing, and what it leaves out
Python code has always been written in a structural style. The saying "if it walks like a duck and quacks like a duck, it is a duck" means that you do not ask what an object is. You call the method you need and see whether it works.
class Duck:
def speak(self) -> str:
return "Quack"
class Robot:
def speak(self) -> str:
return "Beep"
def announce(speaker) -> None:
# No type information: any object with .speak() works at runtime,
# and a wrong argument only fails when the line executes.
print(speaker.speak())
announce(Duck())
announce(Robot())
announce(42) # AttributeError at runtimeDuck typing is flexible, since Duck and Robot share no parent and still work. Its weakness is that the requirement lives only in the body of announce. Three problems follow:
- A reader must read the whole function to learn what
speakerneeds. - A type checker has nothing to compare against, so
announce(42)passes review and fails in production. - If
announcelater starts callingspeaker.volume()as well, no caller is warned.
Duck typing is structural subtyping done in the programmer's head. The remaining step is to write the structure down where a tool can read it.
Structural subtyping: writing the shape down
Structural subtyping keeps the freedom of duck typing and adds a checkable description of what is required. The description is a type that lists the members a value must have. Any class that has those members is a subtype of it, whether or not it ever heard of the description.
In Python, that description is a Protocol class, defined in PEP 544 and available in the typing module. A short preview:
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
class Resource:
def close(self) -> None:
print("closed")
def shutdown(item: SupportsClose) -> None:
item.close()
shutdown(Resource()) # accepted: Resource has a matching close()
shutdown(42) # rejected by a type checker: int has no close()Resource does not inherit from SupportsClose. The checker accepts it anyway because it has a close method that takes no arguments and returns None. The call with 42 is reported as an error before the program runs, and the message names the missing method.
What "compatible by shape" means
Saying that a class "has the right shape" needs a precise reading. A type checker compares a candidate class C against a protocol P member by member. For each member declared in P, the checker asks three questions.
- Does
Chave a member with that name? - Is that member the same kind of thing, such as a method, a plain attribute, or a read-only property?
- Is its type compatible with the one in
P?
Compatibility of types uses the usual substitution rules. For a method, the parameters of C's version must accept at least what P's version accepts, and the return type must be usable wherever P's return type is expected. Extra members on C are fine. Only the members named in P matter.
The next table shows how a few candidate classes fare against SupportsClose.
| Candidate | Result | Reason |
|---|---|---|
| `def close(self) -> None` | Compatible | Same name, parameters and return type. |
| `def close(self, force: bool = False) -> None` | Compatible | The extra parameter has a default, so every call allowed by the protocol still works. |
| `def close(self, force: bool) -> None` | Incompatible | A caller using only the protocol would call `close()` and fail. |
| `def close(self) -> int` | Incompatible | `None` is expected; `int` is a different type. |
| `def shut(self) -> None` | Incompatible | The name differs. |
| `close = None` | Incompatible | The member is not callable. |
The third and fourth rows show that the check is about substitution, not about equality. The question is always whether code written against the protocol would still work if given C.
Passing and failing: a worked example
Consider a protocol for anything that can report its size in bytes, and three candidates.
from typing import Protocol
class HasSize(Protocol):
def size_bytes(self) -> int: ...
class Image:
def __init__(self, pixels: int) -> None:
self.pixels = pixels
def size_bytes(self) -> int:
return self.pixels * 4
def resize(self, factor: float) -> None: # extra member: allowed
self.pixels = int(self.pixels * factor)
class Document:
def size_bytes(self) -> str: # wrong return type
return "1 KB"
class Folder:
def total_size(self) -> int: # wrong name
return 0
def report(item: HasSize) -> str:
return f"{item.size_bytes()} bytes"
print(report(Image(100)))
print(report(Document())) # checker error: incompatible return type
print(report(Folder())) # checker error: missing size_bytesOnly the first call type-checks. Image has extra members, which the protocol ignores. Document has the right name but returns str, so f"{...} bytes" would still run but the contract is broken. Folder has no size_bytes at all.
Note that the program runs to the end, because Document and Folder both happen to work with the f-string or are only reached if called. For Folder, item.size_bytes() raises AttributeError at runtime. The type checker reports both problems earlier, without running the code.
Where the check happens
The comparison described above is made by the type checker, not by Python itself. This is the most important fact in the chapter.
- Python does not read annotations when it runs a call.
shutdown(42)is a normal call that fails only if42lacksclose. - A protocol does not change how classes behave. It does not add methods, and it does not register classes anywhere.
- All of the compatibility analysis described in this chapter happens in tools such as mypy, pyright, or an editor using one of them.
The diagram shows how the two parts relate.
Structural against nominal in practice
Neither rule is better in every case. The following table summarizes what changes when you move from one to the other.
| Question | Nominal (inheritance) | Structural (protocol) |
|---|---|---|
| Where is the relationship recorded? | In the class definition, as a parent. | Nowhere. It is computed by comparing members. |
| Can you add it to a class you do not own? | Not without wrapping or registering. | Yes, if the class already has the members. |
| Can a class match by accident? | No. | Yes, if names and types coincide. |
| Can a class inherit shared behavior? | Yes. | Only if you subclass the protocol explicitly (a later chapter). |
| Does the requirement appear in one place? | Yes, the base class. | Yes, the protocol. |
The third row deserves attention. Two unrelated classes may both have close(self) -> None and mean different things by it. A structural check treats them as interchangeable. In most programs this is harmless, because the protocol describes only what the caller needs. Still, a shape match does not prove intent, and members with generic names such as run or get match more often than they should.
Common mistakes
- Expecting an error at runtime. Calling
shutdown(42)still raises only the ordinaryAttributeError. The protocol does nothing during execution. Run the checker to see the problem. - Thinking inheritance is required. The point of the feature is that
Resourceneeds no parent. Adding one is allowed but is optional. - Requiring more than the function uses. If
shutdowncalls onlyclose, the protocol should list onlyclose. Extra members shut out classes that would have worked. - Matching names but not types. A method called
closethat returns a value is still incompatible with a protocol that expectsNone. - Assuming a protocol is a class you can instantiate. A protocol describes a shape. You use it in annotations, not to create objects.
Summary
Nominal subtyping asks whether a class declared a relationship. Structural subtyping asks whether the class has the members that the other type requires. Duck typing already works this way at runtime, but it gives tools nothing to check. A protocol writes the expected shape down so the type checker can compare it with each candidate: the names must match, the member kinds must match, and the types must be substitutable. Extra members never cause a failure, and the check happens before the code runs. The next chapter shows the syntax for defining protocols in detail.
Exercise
A protocol requires def read(self, n: int) -> bytes. Which of these classes would a type checker accept, and why? (a) def read(self, n: int) -> bytes, plus an extra method seek. (b) def read(self, n: int, strict: bool) -> bytes. (c) def read(self, n: int, strict: bool = False) -> bytes. (d) def read(self, n: int) -> str.
Show answer
(a) and (c) are accepted. In (a) the extra seek method is ignored, since only members named in the protocol matter. In (c) the added parameter has a default, so every call allowed by the protocol still works. (b) is rejected because a caller using only the protocol would call read(5) and omit the required strict argument. (d) is rejected because str is not compatible with the required bytes return type.
Exercise
Why does announce(42) in the duck-typing example fail only at runtime, and what is the smallest change that lets a type checker catch it before the program runs?
Show answer
The parameter speaker has no annotation, so the checker has no required shape to compare int against. Python itself only discovers the missing speak attribute when the line executes. Defining a protocol with def speak(self) -> str: ... and annotating the parameter with it gives the checker a shape to compare. The checker then rejects 42 before execution.