
Python 3.7+ @dataclass decorator auto-generates __init__, __repr__, and __eq__.
Without dataclass:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"With dataclass:
from dataclasses import dataclass, field
@dataclass
class Point:
x: float
y: float
p = Point(1.0, 2.0)
print(p) # Point(x=1.0, y=2.0)
p1 == p2 # compares by value automaticallyDefaults & post-init:
@dataclass
class Student:
name: str
grade: int = 0
courses: list = field(default_factory=list)
def __post_init__(self):
self.name = self.name.title()Frozen (immutable) dataclass:
@dataclass(frozen=True)
class Color:
r: int
g: int
b: intReference:
TaskLoco™ — The Sticky Note GOAT