Reference / Python
dataclasses.dataclass
A decorator that automatically generates special methods such as __init__(), __repr__(), and __eq__() for class definitions.
Syntax
@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, slots=False)Parameters
| Name | Type | Description |
|---|---|---|
| frozen | bool | If True, assigning to fields will raise FrozenInstanceError. |
| slots | bool | If True (Python 3.10+), generates __slots__ to conserve memory. |
Examples
Immutable user model with slots
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class UserProfile:
id: int
username: str
email: str
is_active: bool = True
user = UserProfile(1, 'alex', 'alex@syntaxis.local')
print(user)Using slots=True dramatically decreases object memory footprint and accelerates attribute access.