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.
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))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.
`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.
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.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.