Pydantic & Data Class

Introduction

  • Pydantic is the most widely used data validation library for Python.

  • Dataclass module provides a decorator and functions for automatically adding generated, such as __init__() and __repr__() to user-defined classes.

from typing import Annotated
from pydantic import Field, field_validator, model_validator
from pydantic.dataclasses import dataclass
import dataclasses

# order -> Enable object comparison 
# frozen -> the field be immutable
@dataclass(frozen=True, order=True)
class User:
    # disable the ordering from id
    id: int= dataclasses.field(compare=False)
    # Set the custom type, integer must be larger than 0
    mark: Annotated[int, Field(gt=0)] = dataclasses.field(compare=True)
    # Set the custom validation of the field
    even_number:int
    @field_validator('even_number', mode='after')  
    @classmethod
    def is_even(cls, value: int) -> int:
        if value % 2 == 1:
            raise ValueError(f'{value} is not an even number')
        return value  
    # Set the default value
    name: str = 'John Doe'
    # For the mutable type, such as list, 
    students: list[str] = dataclasses.field(default_factory=lambda: [])
    # custom validate the whole data model
    @model_validator(mode='after')
    def checkStudents(self):
        if len(self.students)  == 0:
            raise ValueError('Students list is empty')
        return self
# Inherit
@dataclass(frozen=True)
class Teacher(User):
    subject:str = 'english'
    
mathTeacher = Teacher(
    id=1, 
    mark=2, 
    subject='math', even_number=2, students=['peter','john']
)
englishTeacher = Teacher(
    id=2,
    mark=1, 
    subject='english', 
    even_number=2, 
    students=['peter','john']
)

# Error due to frozen
# user.mark = 2
# True, because the mark is higher
print(mathTeacher > englishTeacher)
# convert to dict
print(dataclasses.asdict(mathTeacher))

Last updated

Was this helpful?