Sub topic 1
Python Protocols and Structural Subtyping
Prerequisites
This chapter assumes you can write Python classes and functions, use basic type annotations, and understand inheritance. You should also know that a static type checker, such as mypy or pyright, checks annotations before the program runs.
Subtyping by declaration: classes and inheritance
Python traditionally uses nominal subtyping. A class is a subtype of another class because it declares an inheritance relationship.
class Animal:
def speak(self) -> str:
return "sound"
class Dog(Animal):
def speak(self) -> str:
return "woof"
def announce(animal: Animal) -> None:
print(animal.speak())
announce(Dog()) # Dog is an Animal by declarationThe type checker accepts Dog because Dog inherits from Animal. The class declaration provides the relationship.
Duck typing and where it falls short
Duck typing checks an object by using it rather than checking its declared type. If an object has the operation you need, you use it.
class Robot:
def speak(self) -> str:
return "beep"
def announce(speaker) -> None:
print(speaker.speak())
announce(Robot()) # Works at runtime
announce(42) # AttributeError when this line runsDuck typing is flexible, but the unannotated parameter gives a type checker little information. A misspelled method or an invalid argument may be discovered only during execution.
Structural subtyping: compatible by shape
Structural subtyping accepts a value because it has the required members, regardless of its inheritance. The required members form the value's shape.
Structural subtyping preserves duck typing's flexibility while giving static tools a contract to check.
Defining your first Protocol
A Protocol declares the required shape. A class does not need to inherit from it.
from typing import Protocol
class Speaker(Protocol):
def speak(self) -> str: ...
class Robot:
def speak(self) -> str:
return "beep"
def announce(speaker: Speaker) -> None:
print(speaker.speak())
announce(Robot()) # Accepted: Robot has the required methodThe ellipsis marks a method declaration with no implementation. A type checker compares Robot with Speaker: its speak method accepts the same kind of call and returns str. This is called protocol compatibility.
Exercise
Why can Robot() be passed to announce without inheriting from Speaker?
Show answer
Because Robot structurally matches the protocol by providing a compatible speak() -> str method.