Sobes.tech
Junior — Middle

What is the role of a validator when using Pydantic for data processing?

sobes.tech AI

Answer from AI

In Pydantic, a validator is a method that checks and transforms data during model creation. Validators ensure data correctness, can modify values, or raise errors if data does not meet criteria. This helps guarantee that the model object always contains valid and expected data.

Example of a validator in Pydantic:

from pydantic import BaseModel, validator

class User(BaseModel):
    name: str
    age: int

    @validator('age')
    def age_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Age must be positive')
        return v

Here, the validator checks that age is positive and raises an error if not.