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

Python Dataclasses & Pydantic

Python Python 3.7+ Intermediate
debt(d5/e3/b3/t5)
d5 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'specialist tool catches' (d5), pylint/ruff flag mutable default arguments and ruff has rules (RUF008/009) for dataclass mutable defaults, but subtler misuses like missing frozen=True or behavior-heavy dataclasses pass silently.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3), per quick_fix adding @dataclass(frozen=True) or replacing field(default=[]) with field(default_factory=list) is a small pattern-replacement within the class definition.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3), dataclasses are scoped to individual data-holder classes per applies_to (web/cli); the choice between dataclass/NamedTuple/Pydantic affects local model code but doesn't gravitationally shape the whole system.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5), per misconception devs conflate dataclasses with NamedTuples and miss mutability defaults; the field(default_factory=...) requirement for mutable defaults is a documented gotcha most Python devs eventually learn.

About DEBT scoring →

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 53
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 1 ping 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 3 pings S 0 pings S 2 pings M 1 ping T 0 pings W 0 pings T 0 pings F 1 ping S 1 ping S 0 pings M 1 ping T 0 pings W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W
No pings yet today
Sogou 1
Amazonbot 8 Perplexity 5 Scrapy 5 Ahrefs 4 Unknown AI 3 Google 3 Bing 3 Claude 2 ChatGPT 1 Meta AI 1 Sogou 1
crawler 32 crawler_json 3 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