Working with pydantic in Python
Tags: python, beginners, programming
Published: 2024-03-01 23:27:10

# 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.

```bash
pip install pydantic
```

# 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.

```python
from pydantic import BaseModel

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

# 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.

```python
reading_data = {"timestamp": 1623456789.0, "value": 3.5, "unit": "V"}
reading = SensorReading(**reading_data)
print(reading)
```

Output:

```
SensorReading timestamp=1623456789.0 value=3.5 unit='V'
```

# 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.

```python
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)
```

Output:

```
MyApp
INFO
```

# Customizing pydantic models

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

```python
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
```

# Examples

## Defining pydantic models

```python
from pydantic import BaseModel

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

# Validating data with pydantic

```python
reading_data = {"timestamp": 1623456789.0, "value": 3.5, "unit": "V"}
reading = SensorReading(**reading_data)
print(reading)
```

Output:

```
SensorReading timestamp=1623456789.0 value=3.5 unit='V'
```

## Working with settings using pydantic

```python
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)
```

Output:

```
MyApp
INFO
```

## Customizing pydantic models

```python
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
```

# 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.