← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Python Dataclasses & Pydantic

python Python 3.7+ Intermediate

Also Known As

Python dataclasses @dataclass data class Python

TL;DR

@dataclass auto-generates __init__, __repr__, __eq__; Pydantic adds runtime validation and serialisation — Python's equivalent of typed DTOs.

Explanation

@dataclass (Python 3.7+) generates boilerplate from type-annotated fields: __init__ with defaults, __repr__, __eq__ (and optionally __hash__, __lt__ for ordering). @dataclass(frozen=True) makes instances immutable — Python's equivalent of PHP 8.1 readonly classes. field() allows customisation: default_factory for mutable defaults, compare=False, repr=False. Pydantic v2 goes further: validates types at runtime (coercing '42' to int or rejecting invalid data), generates JSON Schema, and serialises to dict/JSON with model.model_dump(). Widely used in FastAPI for request/response models. Compared to PHP DTOs backed by readonly classes + PHPStan: Python dataclasses give the same structural benefits; Pydantic adds the runtime validation that PHP's type declarations provide natively.

Common Misconception

Python dataclasses and NamedTuples are interchangeable. Dataclasses are mutable by default (frozen=True for immutability), support inheritance, and can have methods with full class flexibility. NamedTuples are immutable tuples with named fields — lighter but less flexible.

Why It Matters

Python dataclasses auto-generate __init__, __repr__, __eq__, and optionally __hash__ from field declarations — eliminating the repetitive boilerplate of manual data-holding classes.

Common Mistakes

  • Mutable default arguments: field(default=[]) is required — bare list defaults are shared across instances.
  • Not using frozen=True for value objects that should be immutable.
  • Using dataclasses for classes with significant behaviour — they are for data containers, not services.
  • Not using __post_init__ for validation — the generated __init__ provides no validation hook otherwise.

Code Examples

✗ Vulnerable
# Without dataclass — repetitive boilerplate:
class Point:
    def __init__(self, x, y): self.x = x; self.y = y
    def __repr__(self): return f'Point({self.x}, {self.y})'
    def __eq__(self, other): return self.x == other.x and self.y == other.y

# With dataclass:
from dataclasses import dataclass
@dataclass(frozen=True)
class Point:
    x: float
    y: float
✓ Fixed
from dataclasses import dataclass, field

@dataclass(frozen=True)
class Money:
    amount: int
    currency: str
    tags: list[str] = field(default_factory=list)

    def __post_init__(self):
        if self.amount < 0:
            raise ValueError('Amount cannot be negative')

Added 15 Mar 2026
Edited 22 Mar 2026
Views 26
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 1 ping T 0 pings F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 6 Perplexity 5 Unknown AI 3 Ahrefs 2 ChatGPT 1 Google 1
crawler 17 pre-tracking 1
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Use @dataclass(frozen=True) for immutable value objects — frozen dataclasses raise FrozenInstanceError on mutation and have automatic __eq__ and __hash__ based on field values
📦 Applies To
python 3.7 web cli
🔗 Prerequisites
🔍 Detection Hints
Manual __init__ __eq__ __repr__ boilerplate that @dataclass would auto-generate; mutable class used as dict key without __hash__
Auto-detectable: ✓ Yes pylint ruff mypy
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: Medium ✓ Auto-fixable Fix: Low Context: Class

✓ schema.org compliant