Code Snippets
/

dataclass Basics

dataclass Basics

`@dataclass` writes the boring boilerplate for you: `__init__`, `__repr__`, and `__eq__`. You declare fields with type hints and (optionally) defaults, and Python builds the constructor and the value-equality semantics. This entry covers the basic shape, default values done right, and the `field()` escape hatch for mutable defaults.

Python
Easy
3 snippets
py-dataclasses
py-type-hints
py-standard-library

531 views

5

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

p1 = Point(3, 4)
p2 = Point(3, 4)
p3 = Point(0, 0)

print(p1)            # Point(x=3, y=4)
print(p1 == p2)      # True  (value equality, not identity)
print(p1 == p3)      # False
print(p1 is p2)      # False (still two distinct objects)

# Attributes work like any other object.
p1.x = 10
print(p1)            # Point(x=10, y=4)

The decorator scans the class body for type-annotated names and turns them into fields. The synthesized __init__ takes the fields in declaration order (positional or keyword), __repr__ prints the class name with all field values, and __eq__ compares by field values, not identity. Two instances with the same field values are equal even though they are different objects. By default fields are still mutable (p1.x = 10 works); frozen=True makes them read-only, covered in the frozen-slots entry.