Python Snippet

dataclass Basics

Difficulty: Easy

`@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.

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

530 views

5

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.