pythonintermediate
Data Validation with Pydantic Models
Define and validate data models with Pydantic for type-safe Python applications.
pythonPress ⌘/Ctrl + Shift + C to copy
from pydantic import BaseModel, Field, field_validator
from datetime import datetime
from typing import Optional
class Address(BaseModel):
street: str
city: str
zip_code: str = Field(pattern=r"^\d{5}(-\d{4})?$")
class User(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str
age: int = Field(ge=0, le=150)
address: Optional[Address] = None
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()
# Validates and coerces automatically
user = User(
name="Alice",
email="ALICE@example.com",
age="30", # coerced to int
address={"street": "123 Main", "city": "NYC", "zip_code": "10001"}
)
print(user.model_dump_json(indent=2))Use Cases
- API request validation
- Config parsing
- Data pipelines
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
Data Validation with Pydantic
Validate and parse data records using Pydantic models with custom validators and error reporting.
Best for: Validating incoming data before warehouse loading
#validation#pydantic
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonbeginner
Pydantic v2 Model Patterns
Define and validate data models with Pydantic v2 using field validators, computed fields, and serialization.
Best for: API request/response models
#pydantic#validation
pythonbeginner
Dataclasses with Post-Init Processing
Use Python dataclasses with __post_init__ for computed fields, validation, and default factories.
Best for: Domain models
#dataclasses#python