Friday 29 October 2021

Pydantic: Apply validator on every item of a collection (set, list, dict etc.,)

By passing the argument 'each_item=True' to the validator decorator, we can validate every item in the collection.

 

Let’s see it with an example.

 

validator_demo_5.py

from pydantic import BaseModel, ValidationError, validator
from typing import List

class Test(BaseModel):
    even_numbers: List[int]

    @validator('even_numbers', each_item=True)
    def evenNumValidator(cls, value):
        if(value % 2 != 0):
            raise ValueError('number must be even')
        return value

try:
    t1 = Test(even_numbers = [2, 4, 6])
    print(t1)

    t2 = Test(even_numbers = [2, 4, 5, 6, 7])
    print(t2)
except ValidationError as e:
    print(e.json())

 

Output

even_numbers=[2, 4, 6]
[
  {
    "loc": [
      "even_numbers",
      2
    ],
    "msg": "number must be even",
    "type": "value_error"
  },
  {
    "loc": [
      "even_numbers",
      4
    ],
    "msg": "number must be even",
    "type": "value_error"
  }
]

 

On validation failure, it return the failed position element from the list.

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment