Search code examples
pythonvalidationjsonschemapython-dataclassespydantic

A way to set field validation attribute in pydantic


I have the following pydentic dataclass

@dataclass
class LocationPolygon:
    type: int
    coordinates: list[list[list[float]]]

this is taken from a json schema where the most inner array has maxItems=2, minItems=2.
I couldn't find a way to set a validation for this in pydantic.
setting this in the field is working only on the outer level of the list.

@dataclass
class LocationPolygon:
    type: int
    coordinates: list[list[list[float]]] = Field(maxItems=2, minItems=2)

using @validator and updating the field attribute doesn't help either as the value was already set and basic validations were already made:

@validator('coordinates')
    def coordinates_come_in_pair(cls, values, field):
        field.sub_fields[0].sub_fields[0].field_info.min_items = 2
        field.sub_fields[0].sub_fields[0].field_info.max_items = 2

I thought about using root_validator with pre=True, but there are only the raw values there.

Is there a way to tweak the field validation attributes or use pydantic basic rules to make that validation?


Solution

  • You can use conlist function to create nested constrained list:

    from pydantic import conlist
    from pydantic.dataclasses import dataclass
    
    
    @dataclass
    class LocationPolygon:
        type: int
        coordinates: list[list[conlist(float, min_length=2, max_length=2)]]