Dec 14, 2021

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")

I get:

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")

I get:

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.

About the Author

Mike Hostetler profile.

Mike Hostetler

Principal Technologist

Mike has almost 20 years of experience in technology. He started in networking and Unix administration, and grew into technical support and QA testing. But he has always done some development on the side and decided a few years ago to pursue it full-time. His history of working with users gives Mike a unique perspective on writing software.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Blog Posts
Airflow Logging: Task logs to Elasticsearch
This is part three of a five-part series addressing Airflow at an enterprise scale. I will update these with links as they are published. Airflow: Planning a Deployment Airflow + Helm: Simple Airflow Deployment More […]
Using Nix as a Professional
How to use Nix as a tool to optimize developer time with real-life examples.
Enterprise Auth for Airflow: Azure AD
This is part three of a five-part series addressing Airflow at an enterprise scale. I will update these with links as they are published. Airflow: Planning a Deployment Airflow + Helm: Deploying the Chart Without […]
More Charts: Adding TLS to Airflow
In this post, we will be adding TLS to Airflow on Azure Kubernetes Service. This is part three of a five-part series addressing Airflow at an enterprise scale. I will update these with links as […]