Code

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

  1. Make Glows a @runtime_checkable Protocol with one method: brightness(self) -> int.
  2. brightest(things: list[Glows]) -> Glows returns the thing with the highest brightness().
  3. count_glowing(objects: list[object]) -> int counts how many objects are isinstance(..., Glows).

Note that Lantern and Firefly never mention Glows!