Dataclass (Python)
A Python dataclass is a decorator (@dataclass
) introduced in Python 3.7 that automatically generates special methods for classes that are primarily used to store data—such as __init__()
, __repr__()
, __eq__()
, etc.
Example
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
The code above is roughly equivalent to manually writing:
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x}, y={self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y