Python

How to Parse Objects in Pydantic

Navigating the complexities of data validation and parsing in Python is made simpler with Pydantic. As a versatile tool, Pydantic allows you to define the data models and validate the incoming data against these models. In this exploration, we’ll uncover how to utilize Pydantic to parse the objects effectively, ensuring data integrity and accuracy.

Example: Parsing and Validating the Data Using Pydantic Model in Python

In this example, we will explore how to define a Pydantic model, describe its attributes and data types, handle the input validation, and parse the input data using the defined model. This illustrative example highlights how Pydantic streamlines the often-complex task of ensuring the data integrity and consistency in various Python applications.

To start with the example, make sure that you have Pydantic already installed. In this illustration, we install Pydantic with “email”.

pip install pydantic[email]

This command installs Pydantic with the [email] extra included. The [email] extra enables the additional features related to email validation, including the “EmailStr” type that we will use in our code example. By installing Pydantic with the [email] extra, we ensure that the “EmailStr” type is available for use in your Pydantic models.

We can start working on the program once the required packages are effectively installed.

The code starts by importing the necessary classes from the Pydantic module.

from pydantic import BaseModel, EmailStr

This import statement brings in the necessary classes from the Pydantic library. We import the “BaseModel” class, the foundation for creating Pydantic models. It provides features for data validation, parsing, and more. Then, we have the “EmailStr” class that represents an email address and is used for email validation. Pydantic’s “EmailStr” type ensures that the provided string is a valid email address format.

We can create and work with Pydantic models that enforce the data validation rules and help parse the structured data according to the defined model’s structure by importing these classes.

Now, we define a Pydantic model with some specified attributes. By defining this model, we’re setting up a structure that can be used to validate and parse the data, conforming to the specified attributes and their types. This structure can be beneficial for processing and validating the input data such as when receiving the data from a user input form.

class Person(BaseModel):

  name: str

  age: int

  email: EmailStr

We define a new Pydantic model called “Person” in this code block. The model is inherited from “BaseModel” which is the base class for all Pydantic models.

Then, we specify some attributes of this model. The “name”, “age”, and “email” are attributed definitions within the “Person” model. The “name” is expected to be a string (str), the “age” is expected to be an integer (int), the “email” is expected to be a valid email address, and “EmailStr” enforces this validation.

After that, we create a dictionary that contains the sample input data for the “Person” model that we defined earlier.

person_data = {

  "name": "Albert",

  "age": 26,

  "email": "[email protected]"

}

In this dictionary that we provided, the “name”: “Albert” indicates that the person’s name is “Albert”. The name attribute is expected to be a string (str) based on the model definition. Then, the “age: 26” specifies the person’s age as 26. According to the model definition, the age attribute is required to be an integer (int). Lastly, the “email”: “[email protected]” provides the person’s email address as “[email protected]“. The email attribute is expected to be a valid email address due to using the “EmailStr” type in the model definition.

In the next part of the program, we specify a “try-except” block which attempts to create a “Person” object from the “person_data” dictionary using the “Person” model and then print out the input data and the parsed person if successful. If an exception occurs during this process, the error message is stated.

try:

  person = Person(**person_data)

  print("Input data:", person_data)

  print("Parsed person:", person)

except Exception as e:

  print("Error:", e)

In the code, the “try” block is used to wrap the code that may potentially raise an exception. If an exception happens within this block, the accompanying “except” block will catch it.

Inside the “try” block, we use the “person = Person(**person_data)” to attempt to create a “Person” object by unpacking the “person_data” dictionary and passing its values as keyword arguments to the “Person” model’s constructor.

If the “Person” object is successfully created, this line “print(“Input data:”, person_data)” prints the original input data dictionary. Also, we specify the “print(“Parsed person:”, person)” statement which prints the parsed person object that includes the validated and converted values.

If any exception occurs within the try block, this “except Exception as e” except block is triggered. Since the exception is the foundation class for all exceptions, it captures any exception that may arise. The “print(“Error:”, e)” within the except block outputs the error message that is linked with the recorded exception.

In short, if the “person_data” dictionary matches the expected types and validations that are defined in the “Person” model, the “Person” object will be successfully created. In that case, the script prints both the input data (person_data) and the parsed “Person” object.

However, an exception is raised if there’s an issue with the “person_data” dictionary such as incorrect data types or invalid email format. The “except” block then catches the exception and prints an error message describing the issue.

The complete code for observation is as follows:

from pydantic import BaseModel, EmailStr

class Person(BaseModel):
    name: str
    age: int
    email: EmailStr

# Sample input data
person_data = {
    "name": "Albert",
    "age": 26,
    "email": "[email protected]"
}

# Parse the input data using the User model
try:
    person = Person(**person_data)
    print("Input data:", person_data)
    print("Parsed user:", person)
except Exception as e:
    print("Error:", e)

The output obtained by executing this program is provided in the following:

Conclusion

This article demonstrates how Pydantic simplifies the data handling and validation in Python applications. Through the provided example, we explored the power of Pydantic for data validation and parsing. By defining a simple “Person” model with some attributes, we ensure that the incoming data is stuck to a specific structure and meets the validation requirements. Using the “try” and “except” mechanism, we attempted to create a “Person” instance from a sample data. If the data matches the model’s criteria, we print both the input data and the parsed “Person” object. However, if any issues arise, we catch and display the error.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.