Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.6 — Protocols and Structural Typing
Python · Example 1 of 2

runtime_checkable only checks names

Dog never inherits Speaker. WrongSpeaker has a different signature yet passes isinstance, because only the name speak is tested.

A Protocol describes the methods and attributes an object must have, and anything that has them qualifies, with no inheritance. It is duck typing that a checker can verify: "if it quacks like this, it fits".

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 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a Protocol Greeter with greet(self, name: str) -> str and a class that satisfies it. Write welcome(g: Greeter) that prints g.greet("Asha").

02

Write a Protocol HasLength with __len__, and a function that returns "empty" or "not empty" for any object with a length. Call it with a list and a string.

03

Write a Protocol Clock with now(self) -> str and a FixedClock for tests that always returns "12:00".

Explain it without notes

01

What is structural typing, and how does a Protocol give it to Python?

02

How does a Protocol differ from an abstract base class? When do you pick each?

03

What does @runtime_checkable let you do, and what is the catch?

04

Why do Protocols make code easier to test?

05

A function accepts a Handler Protocol with __call__. When would you choose that over Callable[[str], bool]?

runtime_checkable only checks names
Sign in to run this example in your browser.

Expected output

announce: Woof
Dog is a Speaker: True
Rock is a Speaker: False
WrongSpeaker is a Speaker: True
issubclass(Dog, Speaker): True
AttributeError: 'Rock' object has no attribute 'speak'