Pydantic for data validation and hydration
https://blog.narf.ssji.net/2025/03/30/pydantic-for-data-validation-and-hydration/
When using Python in any serious way, one quickly encounters Pydantic. While I’ve run into it in many frameworks, up to now, I never took the time to sit down and work out what it was doing, beyond something like “data models and validation based on type annotations”.
I have so far used dataclasses for my data models and data transfer objects (DTO). But it finally happened, and I needed finer validation on the data within my model. So I decided to take Pydantic for a spin myself, and see what it was doing for real.
tl;dr:
Pydantic _is_ data models and validation based on type annotations (amongst other things)
It’s a (almost) drop-in replacement for dataclasses
Type resolution and validation does add one order of magnitude over dataclasses, but it’s quite acceptable as a tradeoff for not having to write any bespoke validation code
Not only can it validate data, but it can also construct nested Pydantic objects, with support for polymorphism.
The pydantic.TypeAdapter exposes some lower-level mechanisms allowing to compose Pydantic behaviours as needed
[…]