Pydantic Validation Errors Explained

Let’s jump right into Pydantic validation errors because who doesn’t love a good error message?

To kick things off: what is Pydantic? It’s a data validation library for Python that allows you to define your own custom data models and validate them at runtime. This can save you time and headaches by catching invalid input before it causes issues in your code. But sometimes, despite our best efforts, errors still happen and when they do, Pydantic has got us covered with some pretty hilarious error messages.

Let’s say we have a simple data model for an article:

# Importing the necessary module from Pydantic library
from pydantic import BaseModel

# Defining a data model for an article using the BaseModel class
class Article(BaseModel):
    # Defining the title attribute as a string type
    title: str
    # Defining the author_email attribute as an EmailStr type, which is a subclass of str
    author_email: EmailStr
    # Defining the content attribute as a string type
    content: str

This looks pretty straightforward, right? But what happens if we try to create a new article with an invalid email address? Let’s find out!

First, let’s test it by running our code and passing in some bad data. Here’s how you can do that:

# Import the Article class from the app module
from app import Article

# Use a try-except block to catch any potential errors
try:
    # Create a new instance of the Article class with a title, invalid email address, and content
    Article(title="This is a title", author_email="notanemail@com", content="Some content")
# Catch any exceptions and store them in the variable 'e'
except Exception as e:
    # Print out the error message
    print(e)

# The purpose of this script is to test the functionality of the Article class by creating a new instance with invalid data. 
# The try-except block allows us to catch any potential errors and handle them accordingly. 
# The Article class is used to create a new article with a title, author email, and content. 
# The invalid email address is used to test the error handling of the class. 
# The error message is printed out if an exception is caught.

And here’s what you might see in your console:

# This script is used to handle validation errors for an Article object.
# It checks if the input for the author's email is a valid email address and returns an error if it is not.

# Define the ValidationError class to handle validation errors.
class ValidationError:
    # Initialize the class with the necessary attributes.
    def __init__(self, type, input_value, loc):
        self.type = type # Stores the type of error, in this case, value_error.msg.
        self.input_value = input_value # Stores the input value that caused the error.
        self.loc = loc # Stores the location of the error, in this case, the line and column number.

# Create an instance of the ValidationError class with the given error details.
error = ValidationError(type='value_error.msg', input_value='notanemail@com', loc=(line_number(), column_number()))

# Print the error message with the necessary annotations.
print("ValidationError: 1 validation error for Article")
print("author_email")
print("   Input should be a valid email address (type={}, input_value='{}', loc={})".format(error.type, error.input_value, error.loc))

Haha! But seriously, this error message is pretty helpful because it tells us exactly what went wrong and where (line_number(), column_number()).

Let’s try another example:

# This script imports the Article class from the app module
from app import Article

# This try-except block attempts to create an instance of the Article class with the given parameters
try:
    # The title parameter is a string, the author_email parameter should be a valid email address, and the content parameter is a string
    Article(title="This is a title", author_email="[email protected]", content="Some content")
# If an exception is raised, it will be caught and stored in the variable e
except Exception as e:
    # This prints out the error message stored in e
    print(e)

And here’s what you might see in your console:

# This script is used to handle a validation error for an Article object.
# It checks if the input for the author's email address is a valid email address.
# If not, it raises a validation error with a message indicating the input should be a valid email address.

# Import the necessary module for handling validation errors
from pydantic import ValidationError

# Define the Article class with attributes for title, content, and author's email
class Article:
    title: str
    content: str
    author_email: str

# Create an instance of the Article class with invalid input for the author's email
article = Article(title="Sample Article", content="This is a sample article.", author_email="123")

# Use a try-except block to handle the potential validation error
try:
    # Validate the input for the author's email using the built-in validate_email function
    validate_email(article.author_email)
except ValidationError as e:
    # If the input is not a valid email address, raise a validation error with a custom message
    raise ValidationError("Input should be a valid email address")

Haha! But seriously, this error message is pretty helpful because it tells us exactly what went wrong and where (line_number(), column_number()).

Let’s try one more example:

# Import the Article class from the app module
from app import Article

# Use a try-except block to catch any potential errors
try:
    # Create an instance of the Article class with a title, author email, and content
    # Note: The author email is set to None, which will cause an error
    Article(title="This is a title", author_email=None, content="Some content")
# Catch any exceptions and assign them to the variable "e"
except Exception as e:
    # Print the error message
    print(e)

# The purpose of this script is to demonstrate how to handle potential errors when creating an instance of the Article class. 
# The try-except block allows us to catch any exceptions that may occur and handle them in a specific way. 
# In this case, we are simply printing the error message to the console.

And here’s what you might see in your console:

# This script is used to handle a validation error for an Article object.
# It checks if the input for the author's email is a valid email address.

# Define the validation error and its corresponding message
ValidationError = "value_error.msg"

# Define the input value as None
input_value = None

# Define the location of the error as the line and column number
loc = (line_number(), column_number())

# Print the error message with the specified values
print("Input should be a valid email address (type={}, input_value={}, loc={})".format(ValidationError, input_value, loc))

# The script will output the following message in the console:
# Input should be a valid email address (type=value_error.msg, input_value=None, loc=(line_number(), column_number()))

Haha! But seriously, this error message is pretty helpful because it tells us exactly what went wrong and where (line_number(), column_number()).

Remember: always validate your data at runtime to catch issues before they cause problems in your code and if an error does happen, don’t worry, Pydantic has got you covered with some hilarious error messages.

SICORPS