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

Object Partners profile.
Leave a Reply

Your email address will not be published.

Related Blog Posts
Natively Compiled Java on Google App Engine
Google App Engine is a platform-as-a-service product that is marketed as a way to get your applications into the cloud without necessarily knowing all of the infrastructure bits and pieces to do so. Google App […]
Building Better Data Visualization Experiences: Part 2 of 2
If you don't have a Ph.D. in data science, the raw data might be difficult to comprehend. This is where data visualization comes in.
Unleashing Feature Flags onto Kafka Consumers
Feature flags are a tool to strategically enable or disable functionality at runtime. They are often used to drive different user experiences but can also be useful in real-time data systems. In this post, we’ll […]
A security model for developers
Software security is more important than ever, but developing secure applications is more confusing than ever. TLS, mTLS, RBAC, SAML, OAUTH, OWASP, GDPR, SASL, RSA, JWT, cookie, attack vector, DDoS, firewall, VPN, security groups, exploit, […]