Duck typing and protocols

"If it walks like a duck and quacks like a duck, it's a duck." Python doesn't check what class an object is. It just calls the method. total_area works for anything with an .area() method, and Square and Circle share no parent class.

This is how the built-ins work too. for accepts anything iterable, and len accepts anything with __len__.

typing.Protocol writes the duck down. Shape says "has area() -> float". Type checkers then check calls to total_area, but classes don't need to inherit from Shape. That's structural typing.

Add @runtime_checkable and isinstance(obj, Shape) checks that the method exists. It doesn't check the signature.

Interviewers may ask "how does Python do interfaces?". Answer: duck typing, written down with Protocol, or enforced with an abstract base class (next page).

Run it, then add a Triangle class and pass it in.