Pydantic: Like Python Dataclass But Also Data Validation

Halis Manaz
3 min readOct 30, 2022

--

What Is Pydantic?

Pydantic is a data validation and settings management library for Python. Pydantic uses type annotations while doing their task. If you are familiar with type hints (also you should write clean code) in Python, you can easily use Pydantic because Pydantic enforces type hints at run time.

Why Pydantic?

Pydantic offers almost all the features of the dataclass, as well as a lot of cool features. It is also straightforward to use and the syntax structure is quite simple. Pydantic can create and customize your data model or use an existing base model. In the same way, you can use data validation methods in the library but also you can create more complex data validation conditions. Even you can combine these data validation conditions for more powerful validation.

Installation

You can install Pydantic by using pip commands

!pip install pydantic
# For if you want also email validation option you shoul use
!pip install pydantic[email]
# For if you want also dot enviroment file support
!pip install pydantic[dotenv]
# Also you can install both additional feature at the same time with
!pip install pydantic[email,dotenv]

Usage

Let’s create a simple user data model with inheriting base model. All you have to do is enter the parameter's name in the data model, then put a colon and enter the parameter type. You can even use data types such as list, set, etc., and you can use Optional for variables where it is not mandatory to add. Also, you can default parameter value by using an equal sign. You can see which field types are supported at Pydantic from here

Create a test user with the user data model

Pydantic also understands the data and converts the data to the desired parameter type. For example, in the favorite_numbers list, there is number one in string format. But Pydantic converts to string format to integer

Data Validation

Constrained Types

You can use constrained types of variables to validate your data. You can think of a constrained variable as a particular type of default python data variable. Let’s validate the age parameter using conint constrained parameter. Our condition for the age parameter is user's age should be greater than 18 and lower than 99.

You can use this link to see more restrained functions

Custom Validator

If you create a more complex and advanced validation method, you can create your custom validator with parameters. Thanks to custom validation, your data model will be more flexible than only constrained types provides. Even you can validate more than one variable at the same time to check whether their format is correct or not. Additionally, you can combine custom validator and constrained types to create a more powerful data model. Let’s create a validation condition which is user password length should be greater than eight characters and the password must include at least one punctuation mark, one uppercase letter, and one lowercase letter.

By using a validator decorator, you can start to create your custom validation. Write the variable which is wanted to validate inside the decorator and after create a function that has cls and value as parameters. After that, you can write your validation conditions, and when the parameter format is not correct for your validation condition you can raise ValueError with your custom error message to inform the end user

Convert Pydantic Model To Other Data Type

Dictionary

You can convert your Pydantic data model to a dictionary format by using the model.dict() method. While doing this, you can set only specific parameters with include or exclude parameters. Also, you can convert directly by using dict(model). Additionally, you can use your Pydantic values like dictionary values without converting the dictionary

JSON

In the same way, JSON format is also available for converting Pydantic models. Also, exclude and include parameters are also available in json method. Additionally, Pydantic models could be copied from another variable to use different purposes.

Summary

Pydantic is a great library for dealing with data especially if you have to validate your data. You can use the Pydantic library with API. Even it has a synergy with the FastAPI library. Thanks to Pydantic you can use fewer dictionaries, handle data while getting or sending and also be sure that your data is in the correct format always.

If You Miss Previous Article

Thanks For Reading, Follow Me For More

--

--

Halis Manaz

Hi, I am Halis. I am interested in Python, data analysis, and machine learning. I share what I learned, what I found interesting, and my portfolio projects