python-3.xpydantic

How to add constraints to elements in a list for a Pydantic (V2) BaseModel?


I have an object Product made from BaseModel. Its attribute prices is a list of float. I want to make sure that each element in the list must be a positive value. I looked through the input parameters of Field, none of them is for this. The closest one is gt but it is only for float type not for list[float] type.

Could you please show me how to do it? Thanks.

from pydantic import BaseModel, Field


class Product(BaseModel):
    prices: list[float] = Field(
        max_length=3,
        min_length=2,
        gt=0,  # This one is not for list[float].
    )


p1 = Product(**{"prices": [1., -1.]})  # This should raise an error, since -1. < 0.

Solution

  • You can use pydantic.PositiveFloat as the type in your list:

    from pydantic import BaseModel, Field, PositiveFloat
    
    
    class Product(BaseModel):
        prices: list[PositiveFloat] = Field(
            max_length=3,
            min_length=2,
        )
    
    
    p1 = Product(**{"prices": [1., -1.]})
    # Raises 1 validation error for Product
    # prices.1
    #   Input should be greater than 0 [type=greater_than, input_value=-1.0, input_type=float]
    

    See more at Pydantic Docs: Number Types.