The @dataclass decorator in Python is used to automatically generate special methods for classes, such as __init__(), __repr__(), __eq__(), and others, based on the class attributes you define. This makes it much easier and less error-prone to create classes that are mainly used to store data (sometimes called "data containers" or "plain old data objects").
The @dataclass decorator is available in Python 3.7 and later, in the dataclasses module.
Example
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1) # Output: Point(x=1, y=2)
print(p1 == p2) # Output: True
In this example:
- The
__init__ method is automatically created, so you can instantiate Point(x, y).
- The
__repr__ method is automatically created, so printing the object shows its fields.
- The
__eq__ method is automatically created, so two Point objects with the same values are considered equal.
Why Use @dataclass?
- Less boilerplate: No need to manually write
__init__, __repr__, __eq__, etc.
- Readability: The class definition is cleaner and easier to read.
- Immutability (optional): You can make dataclasses immutable by setting
frozen=True.
Common Options
frozen=True: Makes the dataclass immutable (fields cannot be changed after creation).
order=True: Adds comparison methods (<, <=, >, >=).
default and default_factory: Set default values for fields.
Example with options:
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Point:
x: int
y: int = 0 # default value
In summary:
@dataclass is a decorator that makes it easier to create classes for storing data by automatically generating common special methods.