Использование Pydantic сегодня стало нормой, и это правильно. Но иногда на ревью вижу, что используют его не всегда корректно.
Например, метод BaseModel.model_dump() по умолчанию не преобразует стандартные типы, такие как datetime, UUID или Decimal, в простой сериализуемый для JSON вид. Тогда пишут кастмоный сериализатор для этих типов чтобы функция json.dump() не падала с ошибкой.
import uuid
from datetime import datetime
from decimal import Decimal
from uuid import UUID
from pydantic import BaseModel
class MyModel(BaseModel):
id: UUID
date: datetime
value: Decimal
obj = MyModel(
id=uuid.uuid4(),
date=datetime.now(),
value='1.23'
)
print(obj.model_dump())
# не подходит для json.dump
# {
# 'id': UUID('4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1'),
# 'date': datetime.datetime(2025, 12, 12, 12, 12, 12, 111111),
# 'value': Decimal('1.23')
# }
# добавляем свой кастомный сериализатор
json.dumps(obj.model_dump(), cls=MySerializer)
# {
# 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1',
# 'date': '2025-12-12T12:12:12.111111',
# 'value': '1.23'
# }
В данном случае класс MySerializer обрабатывает datetime, UUID и Decimal. Например так:
class MySerializer(json.JSONEncoder):
def default(self, o):
if isinstance(o, Decimal):
return str(o)
elif isinstance(o, datetime):
return o.isoformat()
elif isinstance(o, UUID):
return str(o)
return super().default(o)
Специально для тех, кто всё еще так делает - в этом нет необходимости!
Pydantic может это сделать сам, просто нужно добавить параметр mode="json".
json.dumps(obj.model_dump(mode="json"))
# {
# 'id': '4f8c1bc4-25fd-40cd-9dbe-2c73639b0dc1',
# 'date': '2012-12-12T12:12:12.111111',
# 'value': '1.23'
# }
#pydantic#libs
During the 09 years period (2018-2026) for Delhi, the month of April witnessed its lowest monthly average AQI of 178 in the current year 2026 (barring 2020 - the year of lockdown due to Covid): Commission for Air Quality Management
#Environment
- 60-metre garbage mountain in Okhla is just 20 m now
- Recycled landfill waste is used for massive Eco park
- "Trees" have been planted too
#Environment
Tata Steel pilots HIsarna tech with ~50% lower capex and ~50% CO₂ reduction. 1 MTPA demo plant planned at Jamshedpur with ₹4,000 cr capex vs ₹9,000 cr blast furnace baseline. CO₂ cut up to 80% with CCS; commercialization targeted ~2030. #Environment
https://t.co/fc7NwWIvTP
An unprecedented weather event was witnessed in Jammu, where a tornado struck the area for nearly 10 minutes in Akhnoor. No damage to life or property has been reported. This marks the first recorded instance of a tornado in the region’s weather history. #Environment
India just turned plastic waste into a massive business opportunity. This policy is not about recycling, it’s about building the next manufacturing wave. #Environment
Discord @smileswe Midjourney #environment Francis henri de roche, julieta london, in the style of detailed fantasy art, imaginative prison scenes, dark blue and gold, trompe - l'œil illusionistic detail, intricate cityscapes, rustic renaissance realism
subscribe • free midjourney
Discord @Nikruz Midjourney #environment Map of fantasy land, two main buildings, one castle and one house, 2 big chests full of gold, graphiti style, vibrant colors, birds eye view, colourful
subscribe • free midjourney