3.10. Pydantic#

3.10.1. Simplify Data Validation with Pydantic#

Dataclasses require manual implementation of validation.

On the other hand, Pydantic offers built-in validation that automatically validates data and provides informative error messages. This makes Pydantic particularly useful when working with data from external sources.

from pydantic import BaseModel


class Dog(BaseModel):
    names: str
    age: int


dog = Dog(names="Bim", age="ten")
---------------------------------------------------------------------------

ValidationError                           Traceback (most recent call last)

Cell In[3], line 9

      5     names: str

      6     age: int

----> 9 dog = Dog(names="Bim", age="ten")



File ~/book/venv/lib/python3.11/site-packages/pydantic/main.py:164, in BaseModel.__init__(__pydantic_self__, **data)

    162 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks

    163 __tracebackhide__ = True

--> 164 __pydantic_self__.__pydantic_validator__.validate_python(data, self_instance=__pydantic_self__)



ValidationError: 1 validation error for Dog

age

  Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='ten', input_type=str]

    For further information visit https://errors.pydantic.dev/2.5/v/int_parsing

3.10.2. Use Pydantic’s Field Class to Validate Numbers and Dates#

Hide code cell content
!pip install pydantic

In addition to checking the type, you may also want to check if numbers and dates match specific constraints. Pydantic’s Field class provides keyword arguments that make this easy.

from pydantic import BaseModel, Field
from datetime import date


class Song(BaseModel):
    title: str
    artist: str
    duration: float = Field(gt=0.0)  # greater than 0
    release_date: date = Field(lt=date.today())  # before today
    beats_per_minute: int = Field(multiple_of=5)  # multiple of 5


song1 = Song(
    title="Believer",
    artist="Imagine Dragons",
    duration=0,
    release_date=date(2024, 6, 1),
    beats_per_minute=125,
)
ValidationError: 2 validation errors for Song
duration
  Input should be greater than 0 [type=greater_than, input_value=0, input_type=int]
    For further information visit https://errors.pydantic.dev/2.5/v/greater_than
release_date
  Input should be less than 2024-05-10 [type=less_than, input_value=datetime.date(2024, 6, 1), input_type=date]
    For further information visit https://errors.pydantic.dev/2.5/v/less_than

Learn more about Pydantic’s numeric constraints.