Abstract base classes and collections.abc
Try creating Shape() yourself. Then implement area in Broken and watch the TypeError disappear.
An abstract base class (ABC) is a parent that cannot be instantiated and forces subclasses to implement certain methods. A Protocol describes a required shape (method names and signatures) so any class that fits can be used, without inheriting, which is how duck typing becomes checkable.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write an ABC Notifier with an abstract method send(message) and a concrete method notify_all(messages) that calls send for each. Make PrintNotifier that prints each message. Run it on ["a", "b"].
Write a Protocol Speaker with speak() -> str, two unrelated classes Cat and Robot with speak, and a function chorus(speakers) that returns the list of what each says.
Write a FakeClock with a method now() returning a number you set, and a function age(clock, born) that returns clock.now() - born. Show that the test is deterministic.
Explain it without notes
What is duck typing, and what is its main weakness?
How does an abstract base class work, and when does Python raise the error for a missing method?
What is a Protocol, and how is it different from an ABC?
Why are protocols useful for testing code that calls an AI model?
Expected output
TypeError: Can't instantiate abstract class Shape without an implementation for abstract method 'area'
TypeError: Can't instantiate abstract class Broken without an implementation for abstract method 'area'
Square with area 16
True True
[4, 3, 2, 1] 4 True 2 1 [1, 2, 3, 4]
True True True