Back to all snippets
Library/Python/Dataclasses
pythonintermediatedataclassestypesmodelsoop

How to implement Dataclasses in Python

Create clean, type-annotated data models with Python dataclasses

Quick Answer

The `@dataclass` decorator auto-generates `__init__`, `__repr__`, and `__eq__` from your type-annotated fields, eliminating boilerplate without the overhead of a full ORM.

Code Snippet

1from dataclasses import dataclass, field
2from typing import Optional
3
4@dataclass
5class User:
6    id: int
7    name: str
8    email: str
9    tags: list[str] = field(default_factory=list)
10    is_active: bool = True
11
12# Auto-generated __init__, __repr__, __eq__
13user = User(id=1, name='Alice', email='alice@example.com')
14print(user)
15# User(id=1, name='Alice', email='alice@example.com', tags=[], is_active=True)
16
17# Frozen (immutable) dataclass
18@dataclass(frozen=True)
19class Point:
20    x: float
21    y: float
22
23    def distance_to(self, other: 'Point') -> float:
24        return ((self.x - other.x) ** 2 + (self.y - other.y) ** 2) ** 0.5
25
26# Post-init validation
27@dataclass
28class Product:
29    name: str
30    price: float
31
32    def __post_init__(self):
33        if self.price < 0:
34            raise ValueError('Price cannot be negative')
35
36# Serialize to dict
37from dataclasses import asdict
38print(asdict(user))

What is Dataclasses?

Introduced in Python 3.7, dataclasses automatically generate boilerplate methods like __init__, __repr__, and __eq__ from your type-annotated fields. They are ideal for modelling structured data — API responses, database records, configuration objects — without the verbosity of writing dunder methods by hand.

How It Works

  1. 1`@dataclass` inspects the class body for annotated fields and generates `__init__`, `__repr__`, and `__eq__`.
  2. 2`field(default_factory=list)` creates a new list for each instance — never use a mutable default like `tags: list = []` directly.
  3. 3`frozen=True` generates `__hash__` and makes instances immutable (raises `FrozenInstanceError` on assignment).
  4. 4`__post_init__` is called after `__init__` for validation or derived field calculation.

Common Use Cases

  • API response models - Represent parsed JSON payloads as typed Python objects
  • Configuration objects - Group related settings with type validation
  • Database records - Model table rows in a lightweight way before reaching for an ORM
  • Value objects - Immutable data containers using frozen=True

Key Benefits

  • Eliminates boilerplate __init__, __repr__, and __eq__ methods
  • Full type-annotation support works with mypy and IDEs
  • Supports default values, default_factory, and post-init hooks
  • Compatible with JSON serialization via dataclasses.asdict()

Common Mistakes to Avoid

  • Using a mutable default like `tags: list = []` directly — Python shares the same list across all instances. Use `field(default_factory=list)` instead.
  • Expecting `@dataclass` to do deep equality on nested objects — it uses `==` on fields, so nested dicts and lists compare by value but custom objects compare by identity unless they also implement `__eq__`.
  • Using `frozen=True` with a field that contains a mutable object — the field reference is frozen, but the object itself can still be mutated.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

What is the difference between a dataclass and a NamedTuple?

`NamedTuple` creates an immutable tuple subclass with field names. `@dataclass` creates a mutable class with full OOP support. Use `NamedTuple` for simple immutable records; use `@dataclass` when you need methods, inheritance, or mutable fields.

About This Python Code Snippet

This free python code snippet for dataclasses is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement dataclasses quickly and correctly.

All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.

Tags: dataclasses, types, models, oop  | Language: python  | Difficulty: intermediate  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.