python Feb 28, 2024
Dataclass Validation with Pydantic
Defining validated data models in Python using Pydantic — automatic parsing, coercion, and clear error messages.
Pydantic validates data at runtime using Python type annotations. Define a model, and Pydantic handles parsing, coercion, and error reporting.
Defining a model
models.py
from pydantic import BaseModel, Field, field_validator
from datetime import datetime
class UserCreate(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: str
age: int = Field(ge=0, le=150)
bio: str | None = None
created_at: datetime = Field(default_factory=datetime.now)
@field_validator("email")
@classmethod
def validate_email(cls, v: str) -> str:
if "@" not in v or "." not in v.split("@")[-1]:
raise ValueError("invalid email format")
return v.lower().strip()
# Valid — age is coerced from string to int
user = UserCreate(name="Ada", email="ADA@example.com", age="29")
print(user.email) # "ada@example.com"
print(user.age) # 29
# Invalid — raises ValidationError with clear messages
try:
UserCreate(name="", email="bad", age=-1)
except Exception as e:
print(e) Nested models
nested.py
class Address(BaseModel):
street: str
city: str
country: str = "US"
class UserProfile(BaseModel):
user: UserCreate
address: Address
tags: list[str] = [] Pydantic validates the entire object graph recursively, giving precise error paths like address.city.