{
    "slug": "py_dataclasses",
    "term": "Python Dataclasses & Pydantic",
    "category": "python",
    "difficulty": "intermediate",
    "short": "@dataclass auto-generates __init__, __repr__, __eq__; Pydantic adds runtime validation and serialisation — Python's equivalent of typed DTOs.",
    "long": "@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.",
    "aliases": [
        "Python dataclasses",
        "@dataclass",
        "data class Python"
    ],
    "tags": [
        "python",
        "oop",
        "typing"
    ],
    "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."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "py_type_hints",
        "py_decorators",
        "readonly_classes_82"
    ],
    "prerequisites": [
        "py_type_hints",
        "immutability",
        "value_object"
    ],
    "refs": [
        "https://docs.python.org/3/library/dataclasses.html",
        "https://docs.pydantic.dev/"
    ],
    "bad_code": "# Without dataclass — repetitive boilerplate:\nclass Point:\n    def __init__(self, x, y): self.x = x; self.y = y\n    def __repr__(self): return f'Point({self.x}, {self.y})'\n    def __eq__(self, other): return self.x == other.x and self.y == other.y\n\n# With dataclass:\nfrom dataclasses import dataclass\n@dataclass(frozen=True)\nclass Point:\n    x: float\n    y: float",
    "good_code": "from dataclasses import dataclass, field\n\n@dataclass(frozen=True)\nclass Money:\n    amount: int\n    currency: str\n    tags: list[str] = field(default_factory=list)\n\n    def __post_init__(self):\n        if self.amount < 0:\n            raise ValueError('Amount cannot be negative')",
    "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",
    "severity": "low",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/py_dataclasses",
        "html_url": "https://codeclaritylab.com/glossary/py_dataclasses",
        "json_url": "https://codeclaritylab.com/glossary/py_dataclasses.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Python Dataclasses & Pydantic](https://codeclaritylab.com/glossary/py_dataclasses) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/py_dataclasses"
            }
        }
    }
}