Overview
Pydantic 2.0, released on July 1, 2023, is a complete rewrite with a Rust core (pydantic-core). Validations are 5-50x faster and the API has been modernized.
Main Features
Rust core (5-50x faster)
The validation engine is rewritten in Rust via pydantic-core, delivering massive performance gains on data validation and serialization.
python
from pydantic import BaseModel
from datetime import datetime
class User(BaseModel):
name: str
email: str
age: int
registered_at: datetime
# Validation 5-50x faster than v1
u = User(
name='Alice',
email='alice@example.com',
age=30,
registered_at='2023-07-01T10:00:00',
)
print(u.model_dump()) # new v2 API
New API
The API is renamed for clarity: .dict() becomes .model_dump(), .json() becomes .model_dump_json(), and .parse_obj() becomes .model_validate().
python
from pydantic import BaseModel, field_validator
class Product(BaseModel):
name: str
price: float
stock: int = 0
@field_validator('price')
@classmethod
def price_must_be_positive(cls, v):
if v <= 0:
raise ValueError('Price must be positive')
return v
p = Product(name='Widget', price=9.99, stock=100)
print(p.model_dump_json()) # JSON serialization
print(p.model_json_schema()) # JSON schema
Custom serialization
The new serialization system allows customizing output with @field_serializer decorators and json/python modes.
python
from pydantic import BaseModel, field_serializer
from datetime import datetime
class Event(BaseModel):
title: str
date: datetime
@field_serializer('date')
def serialize_date(self, v: datetime, _info):
return v.strftime('%d/%m/%Y %H:%M')
e = Event(title='Python Conf', date='2023-07-01T14:00:00')
print(e.model_dump())
# {'title': 'Python Conf', 'date': '01/07/2023 14:00'}
