- Nominal subtyping is strictly based on inheritance. A class that inherits from a parent class is a subtype of its parent.
- Structural subtyping is based on the internal structure of classes. Two classes with the same methods and attributes are structural subtypes of one another.
With protocols, you can focus on defining the desired behavior and characteristics without having to design complex inheritance relationships.
Generic Protocols
from typing import Protocol, TypeVar
T = TypeVar("T", bound=int | float)
class Adder(Protocol[T]):
def add(self, x: T, y: T) -> T:
...
class IntAdder:
def add(self, x: int, y: int) -> int:
return x + y
class FloatAdder:
def add(self, x: float, y: float) -> float:
return x + y
def add(adder: Adder) -> None:
print(adder.add(2, 3))
add(IntAdder())
add(FloatAdder())Protocols vs Abstract Base Classes
ABC is design to be inheritance while protocol is implement when inheritance not practical.
Generic Type
Consider this exampler
from typing import TypeVar
T = TypeVar('T', bound='Shape')
class Shape:
def set_scale(self: T, scale: float) -> T:
self.scale = scale
return self
class Circle(Shape):
def set_radius(self, r: float) -> 'Circle':
self.radius = r
return self
class Square(Shape):
def set_width(self, w: float) -> 'Square':
self.width = w
return self
circle: Circle = Circle().set_scale(0.5).set_radius(2.7)
square: Square = Square().set_scale(0.5).set_width(3.2)withour generic TypeVar, like:
class Shape:
def set_scale(self: T, scale: float) -> 'Shape':
self.scale = scale
return self
Circle().set_scale(0.5) will return Shape object which do not have set_radius method which fail to type check
using generic TypeVar bound to Shape compiler understand set_scale method can return to Shape object or it’s all subclass like Circle or Square, now since it can return Circle which have set_radius method, type checking will successfull
uuid | value id1 | 3 id2 | 5
→ uuid | value id7 | 5 id10 | 10
- writing script to copy cm-config to local
- Set up environment to run DAG locally success
- Reading code and understading DAG build flow
- Read CM docs, get familiar with system architecture and common issue
- Attend all KT sessions