Pydantic v2 Model Patterns
Define and validate data models with Pydantic v2 using field validators, computed fields, and serialization.
from pydantic import BaseModel, Field, field_validator, computed_field
from datetime import datetime
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str
age: int = Field(ge=0, le=150)
created_at: datetime = Field(default_factory=datetime.now)
@field_validator("email")
@classmethod
def validate_email(cls, v: str) -> str:
if "@" not in v:
raise ValueError("Invalid email address")
return v.lower().strip()
@computed_field
@property
def display_name(self) -> str:
return f"{self.name} ({self.email})"
# Usage
user = User(name="Alice", email="ALICE@EXAMPLE.COM", age=30)
print(user.model_dump_json(indent=2))Use Cases
- API request/response models
- Configuration parsing
- Data transformation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Dataclasses with Post-Init Processing
Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.
Data Validation with Pydantic
Validate and parse data records using Pydantic models with custom validators and error reporting.
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Type-Safe Settings with Pydantic
Load and validate environment variables into a typed settings object using pydantic-settings with defaults.