Lab 10: Protocol Typing
Overview
Step 1: typing.Protocol — Structural Subtyping
typing.Protocol — Structural Subtypingfrom typing import Protocol, runtime_checkable
@runtime_checkable
class Drawable(Protocol):
def draw(self) -> str: ...
def area(self) -> float: ...
class Circle:
def __init__(self, radius: float):
self.radius = radius
def draw(self) -> str:
return f"Circle(r={self.radius})"
def area(self) -> float:
import math
return math.pi * self.radius ** 2
class Square:
def __init__(self, side: float):
self.side = side
def draw(self) -> str:
return f"Square(s={self.side})"
def area(self) -> float:
return self.side ** 2
# No inheritance needed — structural compatibility!
shapes = [Circle(5), Square(4)]
for shape in shapes:
print(f"{shape.draw()}: area={shape.area():.2f}")
print(f" isinstance(Drawable): {isinstance(shape, Drawable)}")Step 2: Protocol with __call__
__call__Step 3: Generic Protocols
Step 4: Covariant and Contravariant TypeVar
Step 5: ParamSpec — Preserving Callable Signatures
ParamSpec — Preserving Callable SignaturesStep 6: TypeVarTuple — Variadic Generics
TypeVarTuple — Variadic GenericsStep 7: overload — Multiple Signatures
overload — Multiple SignaturesStep 8: Capstone — Type-Safe Plugin Framework
Summary
Concept
API
Use Case
Last updated
