Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Module

dataclasses

The dataclasses module generates common methods for classes whose fields are declared with type annotations. Its decorator and helper functions support initialization, comparison, immutability, conversion, inspection, and dynamic class creation.

Since
3.7

How it works

The dataclasses module turns annotated classes into data-focused classes by generating methods such as initialization and representation. The decorator inspects annotated fields, while options control comparison, ordering, immutability, slots, keyword-only initialization, and other generated behavior.

Syntax

@dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, **kwargs)

Parameters

NameTypeDescription
clstype | NoneClass to decorate; annotated attributes define its fields.
initboolGenerate an __init__ method.
reprboolGenerate a __repr__ method.
eqboolGenerate equality methods.
orderboolGenerate ordering methods.
unsafe_hashboolGenerate a hash method according to the documented rules.
frozenboolPrevent ordinary field assignment and deletion after initialization.
match_argsboolCreate __match_args__ for positional pattern matching.
kw_onlyboolMake fields keyword-only in the generated initializer.
slotsboolGenerate __slots__.
weakref_slotboolGenerate a weak-reference slot.

Returns

The @dataclass decorator returns the class it was applied to. fields() returns a tuple of Field objects; asdict() and astuple() return converted representations; is_dataclass() returns a boolean.

Key points

  • The module reduces boilerplate by generating common class methods from annotated fields.
  • Applying @dataclass converts the annotated class definition into a dataclass with generated behavior.
  • Annotate class attributes to declare which values belong to the dataclass field model.
  • With match_args enabled, positional structural pattern matching follows the non-keyword-only initializer fields.

Common mistakes

  • Do not assume every dataclass is hashable; hash generation depends on equality and frozen settings.

Example: Immutable user record with a per-instance list

from dataclasses import dataclass, field

@dataclass(frozen=True)
class User:
    name: str
    roles: list[str] = field(default_factory=list)

user = User("Ada")
print(user)
print(user.roles)

The decorator generates initialization and representation behavior from annotated fields; frozen=True prevents attribute reassignment, while default_factory creates a fresh list for each instance.

When to use it

Request and response records

Represent validated or transported application data with less handwritten initialization and representation code.

Domain value objects

Model configuration or domain values where equality and readable representations are useful.

Immutable data models

Create immutable, hashable-style records when the documented equality and frozen settings are appropriate.

Serialization preparation

Convert nested dataclass instances into dictionaries or tuples for serialization boundaries.

Interview questions

QWhat does @dataclass generate?

@dataclass examines annotated class variables and uses them as fields. It can then generate methods such as __init__() and __repr__() for the class.

Follow-up: How would you define a mutable default collection? Use field(default_factory=list) so each instance receives a separate list.

QWhen should field() and default_factory be used?

A field() specification supplies per-field options such as a default, a default factory, whether it participates in initialization, representation, comparison, or pattern matching. A factory is called when a new instance needs that field's value.

Follow-up: Why prefer default_factory over a list literal? A literal would be one class-level default object, while the factory creates a new value per instance.

QWhat does frozen=True guarantee?

frozen=True adds behavior that prevents ordinary field reassignment and deletion after construction. It does not make referenced mutable objects deeply immutable.

Follow-up: Does frozen=True automatically make an instance hashable? Hash generation also depends on eq and unsafe_hash settings, so inspect the documented rules rather than assuming it.

  • dataclass
  • field
  • fields
  • asdict
  • astuple
  • replace
  • make_dataclass
  • is_dataclass

Source: dataclasses — Data Classes — Python 3.15.0 documentation. Checked 2026-10-16.