Overview
Pydantic 1.8, released on March 28, 2021, introduces custom JSON encoders and strengthens strict types for finer validation.
Main Features
Custom JSON encoders
The json_encoders configuration lets you define how custom types are serialized to JSON, avoiding serialization errors for non-standard types.
python
from datetime import datetime
from pydantic import BaseModel
class Event(BaseModel):
name: str
date: datetime
attendees: set[str]
class Config:
json_encoders = {
datetime: lambda v: v.strftime('%Y-%m-%d %H:%M'),
set: list,
}
evt = Event(name='PyCon', date=datetime(2021, 5, 14), attendees={'Alice', 'Bob'})
print(evt.json()) # {"name": "PyCon", "date": "2021-05-14 00:00", ...}
Strict types
Strict types like StrictStr, StrictInt, and StrictBool reject implicit conversions, ensuring received data matches the expected type exactly.
python
from pydantic import BaseModel, StrictInt, StrictStr, ValidationError
class Config(BaseModel):
port: StrictInt
host: StrictStr
# OK: exact types
c = Config(port=8080, host='localhost')
# Error: '8080' is a string, not an int
try:
Config(port='8080', host='localhost')
except ValidationError as e:
print(e) # value is not a valid integer
