Pydantic

From CodeAtCode/oss-ai-skills · View interactive version

Pydantic is an AI agent skill from the GitHub repository CodeAtCode/oss-ai-skills. Use when validating and serializing Python data with Pydantic v2 - models, field and model validators, constrained and special types, TypeAdapter, discriminated unions, BaseSettings, or FastAPI integration

How to use this skill

Skill file

Objective: Use this skill to prevent data-validation gaps and serialization bugs by enforcing boundary-level validation, Field constraints over manual checks, and v2 migration patterns that avoid silent coercion failures.

Pydantic

Data validation using Python type annotations.

Overview

Pydantic provides data validation and settings management using Python type hints. Validates at runtime and generates JSON Schema.

Source: https://docs.pydantic.dev/ | https://github.com/pydantic/pydantic

Installation

pip install pydantic          # Core
pip install pydantic[email]   # Email validation
pip install pydantic orjson   # Best performance
pip install pydantic-settings # Settings management

Quick Start

from pydantic import BaseModel, Field

class User(BaseModel):
    id: int
    name: str
    email: str
    age: int | None = None

# Validation + coercion
user = User(id="1", name="John", email="john@example.com")  # id coerced to int

# From dict/JSON
user = User.model_validate({"id": 2, "name": "Jane", "email": "jane@example.com"})
user = User.model_validate_json('{"id": 3, "name": "Bob", "email": "bob@example.com"}')

# Serialization
data = user.model_dump()           # dict
json_str = user.model_dump_json()  # JSON string

Field Constraints

Compact examples—see validators.md for full reference.

from pydantic import BaseModel, Field
from typing import Optional, List

class ConstrainedModel(BaseModel):
    # Strings
    name: str = Field(min_length=1, max_length=100)
    username: str = Field(pattern=r'^[a-zA-Z0-9_]+$')
    
    # Numbers
    age: int = Field(ge=0, le=150)
    price: float = Field(gt=0)
    
    # Collections
    tags: List[str] = Field(min_length=1)
    
    # Optional
    nickname: Optional[str] = Field(default=None, max_length=50)

Validators

See validators.md for comprehensive patterns.

from pydantic import BaseModel, field_validator, model_validator, Field
import re

class ValidatedModel(BaseModel):
    username: str
    password: str
    
    @field_validator('username')
    @classmethod
    def validate_username(cls, v: str) -> str:
        if len(v) < 3:
            raise ValueError('Username must be at least 3 characters')
        return v.strip().lower()
    
    @model_validator(mode='after')
    def validate_password_strength(self):
        if len(self.password) < 8:
            raise ValueError('Password too short')
        if not re.search(r'[A-Z]', self.password):
            raise ValueError('Password needs uppercase')
        return self

v1 → v2 Migration Checklist

Critical: v2 changes can silently break v1 code. Check each item.

| v1 | v2 | Symptom |

|----|----|---------|

| @validator | @field_validator | Import error; validator deprecated |

| @validator(..., each_item=True) | @field_validator with PlainSerializer | List validation fails |

| @root_validator | @model_validator(mode='before'/'after') | root_validator removed; need mode |

| class Config | model_config = ConfigDict(...) | Config class ignored |

| .dict() | .model_dump() | Method not found |

| .json() | .model_dump_json() | Method not found |

| .parse_obj() | .model_validate() | Method not found |

| .parse_raw() | .model_validate_json() | Method not found |

| .schema() | .model_json_schema() | Method not found |

| Field(..., regex=r'...') | Field(pattern=r'...') | regex removed |

| Field(..., min_length=...) | Field(min_length=...) | Works (unchanged) |

| copy(update={...}) | model_copy(update={...}) | copy is shallow; use model_copy |

| allow_population_by_field_name | populate_by_name | Config key renamed |

| orm_mode | from_attributes | Config key renamed |

| Optional[X] = None default behavior | Defaults no longer filled for None | None stays None, not replaced |

Source: https://docs.pydantic.dev/latest/migration/

Serialization Performance

Measure before optimizing: use timeit or a profiler on model_dump() for deeply nested models.

from pydantic import BaseModel
from typing import Optional, List
import time

class NestedModel(BaseModel):
    data: dict
    items: List[str]

class DeepModel(BaseModel):
    level1: NestedModel
    level2: NestedModel
    level3: NestedModel

model = DeepModel(
    level1=NestedModel(data={}, items=[]),
    level2=NestedModel(data={}, items=[]),
    level3=NestedModel(data={}, items=[])
)

# Measure
start = time.perf_counter()
for _ in range(10000):
    model.model_dump()
print(f"Time: {time.perf_counter() - start:.3f}s")

Guidance:

Django Integration

See django.md for detailed patterns.

from pydantic import BaseModel, ConfigDict
from myapp.models import User as UserModel

class UserPydantic(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    
    id: int
    username: str
    email: str

# Accept ORM objects
user_orm = UserModel.objects.get(id=1)
user_py = UserPydantic.model_validate(user_orm)  # from_attributes=True enables this

# DjangoChoices for enum validation
from django.db import models

class Status(models.TextChoices):
    PENDING = "pending"
    ACTIVE = "active"

# Must be TextChoices, not plain str for enum validation
from pydantic import BaseModel

class Task(BaseModel):
    status: Status  # Works with TextChoices

Pitfalls:

When Not to Use a Strict Model

Not every case benefits from Pydantic's coercion:

# Good: Validate at boundary
def handle_request(raw_data: dict):
    user = User.model_validate(raw_data)  # Boundary
    process_user(user)  # Internal—no re-validation

def process_user(user: User):
    # Use user directly; trust the type
    send_email(user.email)

# Bad: Re-validating internally
def process_user_bad(raw_data: dict):
    user = User.model_validate(raw_data)
    # ...
    user_again = User.model_validate(user.model_dump())  # Unnecessary

Best Practices

  1. Use Field(default_factory=...) for mutable defaults

```python

class Model(BaseModel):

tags: List[str] = Field(default_factory=list) # Good

# tags: List[str] = [] # Bad in v2

```

  1. Separate schemas for operations

```python

class UserBase(BaseModel):

email: str

class UserCreate(UserBase):

username: str

password: str

class UserResponse(UserBase):

id: int

model_config = ConfigDict(from_attributes=True)

```

  1. Validate once at the boundary (see above)

Common Issues

Performance

Deep Dives

Load these reference files on demand:

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.