Editor

Predict the Output: runtime_checkable

Advanced · Predict the output · from Python Protocols: Duck Typing with Type Safety

From the lesson: Python Protocols: Duck Typing with Type Safety

Python has a famous saying: "If it walks like a duck and quacks like a duck, then it's a duck." This is called duck typing - you don't care what an object is, only what it can do. But duck typing has a downside: your editor and type checker have no idea what you expect.

Read the lesson

Read the code carefully and predict exactly what will be printed. Pay attention to which classes satisfy the Protocol and which do not.

from typing import Protocol, runtime_checkable

@runtime_checkable
class Speakable(Protocol):
    def speak(self) -> str: ...

class Dog:
    def speak(self) -> str:
        return "Woof"

class Rock:
    pass

class Parrot:
    def speak(self) -> str:
        return "Polly wants a cracker"

print(isinstance(Dog(), Speakable))
print(isinstance(Rock(), Speakable))
print(isinstance(Parrot(), Speakable))
# Predict the output, then run to check
from typing import Protocol, runtime_checkable
@runtime_checkable
class Speakable(Protocol):
def speak(self) -> str: ...
class Dog:
def speak(self) -> str:
return "Woof"
class Rock:
pass
class Parrot:
def speak(self) -> str:
return "Polly wants a cracker"
print(isinstance(Dog(), Speakable))
print(isinstance(Rock(), Speakable))
print(isinstance(Parrot(), Speakable))

More Protocol exercises

All Python exercises · 50 practice problems · Advanced Python quiz