python-dataclasses-pydantic

verified

9b58626e-8416-467e-8a92-02e46d9394f2

Model structured Python data with dataclasses and Pydantic — immutable value objects, validation, serialization.

Metadata

Skill ID
9b58626e-8416-467e-8a92-02e46d9394f2
Version
1
Owner
global
Tags
pythondataclassespydanticdata-modelingbackend
Signature
verified
Integrity
OK
Content hash
fcc1cba4dcaae26b29e1dbf2b9f2120caa9c0bec4fbfbccb083b1f1d3d109155
Created
2026-08-05T18:29:01Z

Skill file

Raw skill file (markdown source)
# Data Modeling with Dataclasses + Pydantic

Use when a module carries structured records and you want type safety, validation,
or clean JSON round-tripping.

## Type-safety with dataclasses

```python
from __future__ import annotations
from dataclasses import dataclass


@dataclass(slots=True)
class Point:
    x: float
    y: float
```

`@dataclass(slots=True)` reduces memory and prevents accidental attribute typos
(an unknown attribute must be declared).

## Validation + serialization with Pydantic

```python
from pydantic import BaseModel, Field


class SkillInput(BaseModel):
    name: str
    description: str
    tags: list[str] = Field(default_factory=list)
```

- Field-level validation + coercion for free.
- `.model_dump_json()` / `.model_validate(...)` for clean JSON.

## When to use which

- Internal, no I/O validation needed → `@dataclass(slots=True)`.
- Boundaries: HTTP bodies, config, API responses → Pydantic `BaseModel`.

## Pitfalls

- Mutating default `list`/`dict` in a dataclass is a classic bug — always use
  `field(default_factory=list)`, never `= []`.
- `@dataclass(slots=True)` disallows adding attributes later; declare everything
  up front.
- Keep Pydantic at the boundary; don't let validation wrap hot inner loops.

Attached files