Introduction to Pydantic
I’ve been using the Pydantic library in my Python projects lately and it’s pretty great. At first glance, it seems very similar to Python 3’s built-in dataclass decorator but when you see it supports easy JSON serialization and deserialization with ease, you won’t go back. The real killer feature of Pydantic is data validation—you declare the types of properties in your class, optional or required, and even default values if you want. If you have a validation problem, you will get a very useful error.
Here is a simplistic example:
from pydantic import BaseModel class Book(BaseModel): title: str author: str publisher: str year_published: int book= Book(title="The Way Of Kings")
pydantic.error_wrappers.ValidationError: 3 validation errors for Book author field required (type=value_error.missing) publisher field required (type=value_error.missing) year_published field required (type=value_error.missing)
if you use the wrong object type:
book= Book(title="The Way Of Kings", author="Brandon Sanderson", year_published="forty-two", publisher="Tor")
pydantic.error_wrappers.ValidationError: 1 validation error for Book year_published value is not a valid integer (type=type_error.integer)
While Pydantic does well with JSON, sometimes you need to go with something older—like CSV. Luckily a generic CSV serializer was easy to write.
So if you need some easy and powerful data validation and serialization in your Python project, you should give Pydantic a look.