
If It Glows…
Python is famous for duck typing: if it walks like a duck and quacks like a duck, treat it as a duck. We care about what an object can do, not which class it comes from.
A Protocol writes that idea down as a type:
from typing import Protocol
class Quacks(Protocol):
def quack(self) -> str: ...
def chorus(birds: list[Quacks]) -> str:
return " ".join(b.quack() for b in birds)
Any class with a matching quack method fits Quacks. It does
not need to inherit from it. This is structural typing,
unlike abc.ABC, where classes must inherit explicitly.
Checking at runtime
Add @runtime_checkable and isinstance(obj, Quacks) works. It only
checks that the method exists, not its parameters or return type.
Pip tip: The
...(Ellipsis) body is the usual way to write "no implementation here" in protocols and stubs.
Assignment
- Make
Glowsa@runtime_checkableProtocolwith one method:brightness(self) -> int. brightest(things: list[Glows]) -> Glowsreturns the thing with the highestbrightness().count_glowing(objects: list[object]) -> intcounts how many objects areisinstance(..., Glows).
Note that Lantern and Firefly never mention Glows!
- Make
Glowsa@runtime_checkableProtocolwith one method:brightness(self) -> int. brightest(things: list[Glows]) -> Glowsreturns the thing with the highestbrightness().count_glowing(objects: list[object]) -> intcounts how many objects areisinstance(..., Glows).
Note that Lantern and Firefly never mention Glows!
Press Run to try your code, then Check to test it.