Today I Remember - Python Pydantic
Are you tired of dealing with the hassle of manual data validation in your Python code? If so, Pydantic might be the solution you are looking for. Pydantic is a data validation and settings management library that uses Python’s type annotations to define the shape of your data.
With Pydantic, you can define data models as standard Python classes with type annotations, making it easy to declare the types of your variables and get editor support for your code. For example, here is a simple function that takes a user ID as a string argument and returns it:
from datetime import date
from pydantic import BaseModel
# Declare a variable as a str and get editor support inside the function
def main(user_id: str):
return user_id
# A Pydantic model
class User(BaseModel):
id: int
name: str
joined: date
In this code, we are using Python’s built-in datetime module and Pydantic’s BaseModel
class to define a simple data model for a user. The User
class has three fields: an integer id, a string name, and a date object representing the date the user joined.
Once you have defined your data model, you can use it to validate and manipulate data with ease. Here is an example of how you might create and manipulate instances of the User
class:
my_user: User = User(id=3, name="John Doe", joined="2018-07-19")
second_user_data = {
"id": 4,
"name": "Mary",
"joined": "2018-11-30",
}
my_second_user: User = User(**second_user_data)
In this code, we are creating two instances of the User
class: my_user
and my_second_user
. The first instance is created using explicit arguments, while the second instance is created using a dictionary that’s unpacked using the **
operator.
For more information on how to use Pydantic, check out the official documentation1.