How Validation Works
Pydantic validates data when you create a model instance. If something's wrong, it raises a ValidationError with details.
from pydantic import BaseModel, ValidationError
class User(BaseModel):
name: str
age: int
try:
user = User(name="Alice", age="thirty")
except ValidationError as e:
print(e)
The error message tells you exactly what failed and why.
Pydantic also coerces compatible types:
user = User(name="Alice", age="30") # String "30" becomes int 30
print(user.age) # 30 (as integer)
This is helpful when parsing JSON, where numbers often come as strings. Pydantic converts them if possible, or fails with a clear error if not.
You control how strict this coercion is through configuration.
I explain validation modes in my Pydantic course.