Sobes.tech
Junior

What is the @dataclass decorator in Python?

sobes.tech AI

Answer from AI

@dataclass is a decorator from the dataclasses module that automatically generates special methods such as __init__, __repr__, __eq__, and others for classes intended to store data. This greatly simplifies the creation of data container classes.

Example:

# Without decorator
class PointManual:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"PointManual(x={self.x}, y={self.y})"

    def __eq__(self, other):
        if not isinstance(other, PointManual):
            return NotImplemented
        return self.x == other.x and self.y == other.y

# With @dataclass decorator
from dataclasses import dataclass

@dataclass
class PointData:
    x: int
    y: int

# Usage
p1_manual = PointManual(1, 2)
p2_manual = PointManual(1, 2)
print(p1_manual)        # Output: PointManual(x=1, y=2)
print(p1_manual == p2_manual) # Output: True

p1_data = PointData(1, 2)
p2_data = PointData(1, 2)
print(p1_data)          # Output: PointData(x=1, y=2)
print(p1_data == p2_data)   # Output: True

Main advantages:

  • Reduction of boilerplate code: Automatic creation of standard methods
  • Readability: Clearly shows that the class is meant for data storage
  • Type annotations: Supports type hints
  • Customizability: Allows enabling/disabling generation of specific methods (init=False, repr=False, etc.)

Disadvantages (compared to namedtuple):

  • Classes created with @dataclass are mutable by default unless fields are declared as field(frozen=True).
  • Consume slightly more memory than namedtuple.

Parameters of the @dataclass(...) decorator:

Parameter Description Default
init Whether to generate the __init__() method. True
repr Whether to generate the __repr__() method. True
eq Whether to generate the __eq__() method. True
order Whether to generate comparison methods (__lt__, __le__, __gt__, __ge__). False
unsafe_hash Whether to force generation of __hash__(). Use with caution. False
frozen Make the instance immutable (attempts to assign will raise an exception). False

Fields can also be defined using the field() function from the same module to specify additional parameters, such as default values, metadata, or to exclude a field from automatically generated methods.

from dataclasses import field

@dataclass
class Item:
    name: str
    price: float = field(default=0.0) # Default value
    quantity: int = field(default=1, init=False, repr=False) # Exclude from init and repr

@dataclass is a modern and preferred way to create simple data storage classes in Python 3.7+.