First off, in V1 we had those ***** type annotations all over our code like a bad case of acne. But now with V2, you can say goodbye to those unsightly blemishes and embrace the beauty of validation errors!
Here’s what it looks like:
# Importing the necessary module for data validation
from pydantic import BaseModel
# Creating a class for our model with type annotations for the attributes
class MyModel(BaseModel):
name: str
age: int
# Defining the constructor method with *args and **kwargs parameters
def __init__(self, *args, **kwargs):
# Calling the constructor method of the parent class
super().__init__(*args, **kwargs)
# Performing additional validation on the age attribute
if self.age < 18:
# Raising a ValueError if the age is less than 18
raise ValueError("You must be at least 18 years old to use this service.")
In V2, we’ve also added support for more complex data structures like lists and dictionaries. No longer do you have to write those ***** type annotations all over your code! Just let Pydantic handle it for you:
# Importing the necessary module
from pydantic import BaseModel
# Creating a class called MyList that inherits from the BaseModel class
class MyList(BaseModel):
# Defining a variable called items with type annotation List[int] and a default value of an empty list
items: List[int] = []
# Defining a constructor method with *args and **kwargs as parameters
def __init__(self, *args, **kwargs):
# Calling the constructor method of the parent class
super().__init__(*args, **kwargs)
# Performing extra validation on the items in the list
for item in self.items:
# Checking if the item is a negative number
if item < 0:
# Raising a ValueError if the item is negative
raise ValueError("All items must be positive numbers.")
In V2 we’ve also added support for nested data structures like dictionaries within lists and vice versa. No longer do you have to write those ***** type annotations all over your code! Just let Pydantic handle it for you:
# Importing the necessary module
from pydantic import BaseModel
# Creating a class that inherits from the BaseModel class
class MyDict(BaseModel):
# Defining a variable "items" with type annotation "List[dict]" and a default value of an empty list
items: List[dict] = []
# Defining a constructor method with *args and **kwargs as parameters
def __init__(self, *args, **kwargs):
# Calling the constructor method of the parent class
super().__init__(*args, **kwargs)
# Performing extra validation on the items
for item in self.items:
# Checking if the key "name" is present in the item and if its length is less than 3
if 'name' not in item or len(item['name']) < 3:
# Raising a ValueError if the condition is not met
raise ValueError("All items must have a name that is at least 3 characters long.")
Say goodbye to those ***** type annotations and hello to validation errors that will make you laugh out loud (or cry, depending on your mood).