from typing import Protocol
class Drawable(Protocol):
def draw(self) -> None:
pass
class Circle:
def draw(self):
print("Drawing a circle")
class Square:
def draw(self):
print("Drawing a square")
def render(shape: Drawable):
shape.draw()
render(Circle()) # β Output: Drawing a circle
render(Square()) # β Output: Drawing a square
def quack(obj: object):
if hasattr(obj, "quack"):
return obj.quack()
raise TypeError("Object does not have 'quack' method")
class Duck:
def quack(self):
return "Quack!"
print(quack(Duck())) # β Output: Quack!
from typing import Protocol
class Logger(Protocol):
@staticmethod
def log(message: str) -> None:
pass
class ConsoleLogger:
@staticmethod
def log(message: str):
print(f"Log: {message}")
def write_log(logger: Logger):
logger.log("Test message")
write_log(ConsoleLogger()) # β Output: Log: Test message
from typing import Protocol
class Flyable(Protocol):
def fly(self) -> str:
pass
class Airplane:
def fly(self):
return "Flying in the sky"
class Bird:
def fly(self):
return "Flapping wings"
class Car:
def drive(self):
return "Driving on the road"
def take_off(obj):
if hasattr(obj, "fly"):
return obj.fly()
raise TypeError("Object can't fly!")
def take_off_strict(obj: Flyable):
return obj.fly() # Ensures fly() exists
print(take_off(Airplane())) # β Output: Flying in the sky
print(take_off_strict(Bird())) # β Output: Flapping wings
print(take_off(Car())) # β TypeError: Object can't fly!