← All languages
Python function of the day
Random

dataclass

Decorator that automatically generates boilerplate methods for classes used as data containers.

Description

The @dataclass decorator from the dataclasses module automatically generates common dunder methods such as __init__, __repr__, and __eq__ based on a class's annotated attributes. It was added in Python 3.7 (PEP 557) to remove the boilerplate of writing simple data-holding classes by hand.

Fields are declared using regular type annotations, optionally with default values or default factories from dataclasses.field(). Decorator arguments such as frozen=True, order=True, kw_only=True, and slots=True customise the generated class to be immutable, comparable, keyword-only, or memory-efficient.

Dataclasses pair naturally with type hints, asdict()/astuple() helpers, and the typing module's NamedTuple and TypedDict alternatives. They are widely used for configuration objects, value objects, and lightweight DTOs in modern Python code.

Arguments

NameDescriptionOptional
frozen If True, instances are immutable; assignments raise FrozenInstanceError. Yes
order If True, ordering methods (__lt__, __le__, etc.) are generated. Yes
slots If True, the generated class uses __slots__ for memory efficiency. Yes

Example

from dataclasses import dataclass

@dataclass(frozen=True)
class Point:
    x: float
    y: float

p = Point(1.0, 2.0)
print(p)  # Point(x=1.0, y=2.0)

Reference