Pydantic
The most widely used Python data validation library. Powers OpenAI SDK, Anthropic SDK, LangChain, FastAPI, LlamaIndex, and hundreds of other libraries. V2 released June 2023 — a near-complete rewrite in Rust via pydantic-core, 4-50x faster than V1. Current version is 2.12.5 (Mar 2026). V1 security fixes ended June 2024. V3 planned roughly annually.
Warnings
- breaking @validator decorator is deprecated in V2 and will be removed in V3. LLMs trained on pre-2023 data consistently generate @validator code. Raises PydanticDeprecatedSince20 warning.
- breaking @root_validator deprecated in V2, removed in V3. Replace with @model_validator(mode='before') or @model_validator(mode='after').
- breaking Inner class Config: is deprecated. Use model_config = ConfigDict(...) at class level.
- breaking orm_mode = True renamed to from_attributes = True in ConfigDict.
- breaking .dict() method deprecated. Use .model_dump() instead. .json() deprecated, use .model_dump_json().
- breaking parse_obj() and parse_raw() removed. Use model_validate() and model_validate_json() instead.
- breaking BaseSettings moved to separate pydantic-settings package. 'from pydantic import BaseSettings' raises ImportError in V2.
- breaking Field(regex=...) renamed to Field(pattern=...) in V2.
- gotcha V1 compat layer available via 'from pydantic.v1 import BaseModel' for gradual migration. But mixing V1 and V2 BaseModel in same codebase causes hard-to-debug errors.
- gotcha pydantic-core is a Rust extension. On unsupported platforms or Python versions, installation fails with no binary wheel available. Requires Python 3.8+.
Install
-
pip install pydantic -
pip install 'pydantic[email]' -
pip install pydantic-settings
Imports
- BaseModel
from pydantic import BaseModel, field_validator, model_validator class User(BaseModel): name: str age: int @field_validator('age') @classmethod def age_must_be_positive(cls, v): if v <= 0: raise ValueError('age must be positive') return v - model_validator
from pydantic import BaseModel, model_validator class User(BaseModel): name: str age: int @model_validator(mode='before') @classmethod def check_root(cls, values): return values - ConfigDict
from pydantic import BaseModel, ConfigDict class User(BaseModel): model_config = ConfigDict(from_attributes=True) name: str - BaseSettings
from pydantic_settings import BaseSettings class Settings(BaseSettings): api_key: str model_config = ConfigDict(env_file='.env')
Quickstart
from pydantic import BaseModel, field_validator, ConfigDict
class User(BaseModel):
model_config = ConfigDict(from_attributes=True)
name: str
age: int
@field_validator('age')
@classmethod
def age_positive(cls, v):
assert v > 0, 'age must be positive'
return v
user = User(name='Alice', age=30)
print(user.model_dump()) # not .dict()
print(user.model_dump_json()) # not .json()