DEV Community

Cover image for Working with pydantic in Python
≀Paulo Portela
≀Paulo Portela

Posted on

Working with pydantic in Python

Introduction

Pydantic is a data validation and settings management library for Python. It simplifies the process of defining and validating data structures, making it easier to work with complex data in Python applications. In this chapter, we will explore the features of pydantic and how it can be used to create robust and maintainable Python code.

Topics

  • Installing pydantic
  • Defining pydantic models
  • Validating data with pydantic
  • Working with settings using pydantic
  • Customizing pydantic models

Installing pydantic

Before using pydantic in your Python projects, you need to install it using pip, the Python package manager.

pip install pydantic
Enter fullscreen mode Exit fullscreen mode

Defining pydantic models

Pydantic models are defined using Python classes, with each field representing a piece of data in the model. These fields can have data types and validation rules associated with them.

from pydantic import BaseModel

class SensorReading(BaseModel):
    timestamp: float
    value: float
    unit: str = "V"
Enter fullscreen mode Exit fullscreen mode

Validating data with pydantic

Once a pydantic model is defined, you can create instances of the model and validate input data against the model's schema.

reading_data = {"timestamp": 1623456789.0, "value": 3.5, "unit": "V"}
reading = SensorReading(**reading_data)
print(reading)
Enter fullscreen mode Exit fullscreen mode

Output:

SensorReading timestamp=1623456789.0 value=3.5 unit='V'
Enter fullscreen mode Exit fullscreen mode

Working with settings using pydantic

Pydantic can also be used to manage application settings by defining a settings model with default values and validation rules.

from pydantic import BaseSettings

class AppConfig(BaseSettings):
    app_name: str = "MyApp"
    log_level: str = "INFO"

config = AppConfig()
print(config.app_name)
print(config.log_level)
Enter fullscreen mode Exit fullscreen mode

Output:

MyApp
INFO
Enter fullscreen mode Exit fullscreen mode

Customizing pydantic models

Pydantic models can be customized with additional validation rules, custom data types, and methods.

from pydantic import BaseModel, validator

class SensorReading(BaseModel):
    timestamp: float
    value: float
    unit: str = "V"

    @validator("value")
    def value_must_be_positive(cls, v):
        if v < 0:
            raise ValueError("value must be positive")
        return v
Enter fullscreen mode Exit fullscreen mode

Examples

Defining pydantic models

from pydantic import BaseModel

class SensorReading(BaseModel):
    timestamp: float
    value: float
    unit: str = "V"
Enter fullscreen mode Exit fullscreen mode

Validating data with pydantic

reading_data = {"timestamp": 1623456789.0, "value": 3.5, "unit": "V"}
reading = SensorReading(**reading_data)
print(reading)
Enter fullscreen mode Exit fullscreen mode

Output:

SensorReading timestamp=1623456789.0 value=3.5 unit='V'
Enter fullscreen mode Exit fullscreen mode

Working with settings using pydantic

from pydantic import BaseSettings

class AppConfig(BaseSettings):
    app_name: str = "MyApp"
    log_level: str = "INFO"

config = AppConfig()
print(config.app_name)
print(config.log_level)
Enter fullscreen mode Exit fullscreen mode

Output:

MyApp
INFO
Enter fullscreen mode Exit fullscreen mode

Customizing pydantic models

from pydantic import BaseModel, validator

class SensorReading(BaseModel):
    timestamp: float
    value: float
    unit: str = "V"

    @validator("value")
    def value_must_be_positive(cls, v):
        if v < 0:
            raise ValueError("value must be positive")
        return v
Enter fullscreen mode Exit fullscreen mode

Conclusion

Pydantic is a powerful library for data validation and settings management in Python. By defining pydantic models, developers can ensure that data adheres to a specific schema and is validated against predefined rules. With its intuitive syntax and extensive features, pydantic simplifies the process of working with complex data structures, making Python development more efficient and maintainable.

Top comments (1)

Collapse
 
sc0v0ne profile image
sc0v0ne

Pydantic is good !!!