Fix the Bug: Missing Protocol Method
Advanced · Fix the bug · 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 lessonThe code below defines a Cacheable Protocol and a UserProfile class. The cache_item function should work with any Cacheable, but there's a bug - UserProfile is missing a method required by the Protocol. Fix UserProfile so it satisfies Cacheable.
The cache_key() method should return f"user:{self.user_id}".
from typing import Protocol, runtime_checkable
@runtime_checkable
class Cacheable(Protocol):
def cache_key(self) -> str: ...
def to_dict(self) -> dict: ...
class UserProfile:
def __init__(self, user_id: int, name: str):
self.user_id = user_id
self.name = name
def to_dict(self) -> dict:
return {'user_id': self.user_id, 'name': self.name}
def cache_item(item: Cacheable) -> None:
print(f"Caching {item.cache_key()}: {item.to_dict()}")
profile = UserProfile(42, 'Alice')
print(isinstance(profile, Cacheable))
cache_item(profile)
More Protocol exercises
All Python exercises · 50 practice problems · Advanced Python quiz