Today, let’s dive into the world of Pydantic, because who doesn’t love a tool that makes your life easier when dealing with data? But first things first, what on earth is Pydantic?
What is Pedantic?
Well, it’s actually Pydantic, not pedantic (easy to mix up, right?). Pydantic is a Python library that helps you model and validate data effortlessly. No more pulling your hair out over messy data—Pydantic has your back!
External Lib Models the Data
Pydantic shines when it comes to handling data models. Imagine you have this beautiful, intricate dataset, and you want to make sure it stays neat and tidy. Pydantic lets you model your data externally with ease.
Main Pros of Using Pydantic
- IDE Type Hints
Pydantic plays well with IDEs, providing type hints that make your code more readable and less error-prone. Who doesn’t want their IDE to be their coding BFF? - Data Validation
Say goodbye to the days of wading through oceans of messy data. Pydantic validates your data against the model you’ve defined, making sure everything fits like a glove. - JSON Serialization
Pydantic isn’t just about keeping things neat in Python. It also helps you serialize your data into JSON effortlessly. Talk about versatility!
Install Pydantic
Installing Pydantic is a piece of cake.
pip install pydantic
Base Model
Let’s keep it simple with a User model. We’ll create a user instance and have some fun with data validation.
from pydantic import BaseModel
# Define our User model
class User(BaseModel):
name: str
age: int
email: str
# Create a user instance by passing data as parameters
user1 = User(name="John Doe", age=25, email="[email protected]")
# Create a user instance by passing data as a dictionary
user2_data = {"name": "Jane Doe", "age": 28, "email": "[email protected]"}
user2 = User(**user2_data)
# If the data is valid, the user object will be created
print(user1)
print(user2)
With Pydantic, if your data is correct, your User object is good to go and you can access the field.
Custom Validator
This feature is handy when your data requires specific checks or constraints that aren’t covered by the default Pydantic validators. Let’s break down how you can implement custom validation logic in a Pydantic model.
from pydantic import BaseModel, ValidationError, validator
class CustomUser(BaseModel):
name: str
age: int
email: str
@validator("name")
def validate_name(cls, value):
if len(value) < 3:
raise ValueError("Name must be at least 3 characters long")
return value
@validator("age")
def validate_age(cls, value):
if value < 0 or value > 120:
raise ValueError("Age must be between 0 and 120")
return value
@validator("email")
def validate_email(cls, value):
if "@" not in value:
raise ValueError("Invalid email format")
return value
Using those custom validation:
try:
# Valid data
valid_user_data = {"name": "Alice", "age": 30, "email": "[email protected]"}
user = CustomUser(**valid_user_data)
print("User:", user)
# Invalid data (raises ValidationError)
invalid_user_data = {"name": "Bo", "age": 150, "email": "invalid-email"}
invalid_user = CustomUser(**invalid_user_data)
except ValidationError as e:
print("Validation Error:", e.errors())
Thanks.