Search code examples
pythonpydantic

Using Pydantic Field to specify constrains of a List of String?


I try to specify constrains of a list of string field, where the list should have at least 1 item and maximum 10 items, and the string item should have maximum 10 length.

I can implement it with constr and conlist. Now I want to use pydantic.Field to implement the same feature. But seems not work.

Attached the sample code:

from pydantic import (
    BaseModel,
    Field,
    conlist,
    constr,
)

# Using constr, conlist 
class FooListRequestModel(BaseModel):
    name: conlist(item_type=constr(max_length=10), min_length=1, max_length=10)
    age: int

# Using pydantic.Field
class FooListRequestModel2(BaseModel):
    name: list[str] = Field(..., min_items=1, max_items=10, max_length=10)
    age: int


if __name__ == "__main__":
    # Success validate
    fooList = FooListRequestModel(
        name=["01234567890123456789", "01234567890123456789"], age=20
    )
    print(fooList)

    # Failed to validate
    fooList2 = FooListRequestModel2(
        name=["01234567890123456789", "01234567890123456789"], age=20
    )
    print(fooList2)

Solution

  • The max_length restriction only applies to a field, where the entry is a single string. It does not apply for each item in a list. Thus you need to define an alias for the length restricted string. See the following example:

    from typing import Annotated
    from pydantic import BaseModel, Field
    
    
    MaxLengthStr = Annotated[str, Field(max_length=10)]
    
    # Using pydantic.Field
    class FooListRequestModel2(BaseModel):
        name: list[MaxLengthStr] = Field(..., min_items=1, max_items=10)
        age: int
    
    
    fooList2 = FooListRequestModel2(
        name=["01234567890123456789", "01234567890123456789"], age=20
    )
    print(fooList2)
    

    Which raises:

    ValidationError: 2 validation errors for FooListRequestModel2
    name.0
      String should have at most 10 characters [type=string_too_long, input_value='01234567890123456789', input_type=str]
        For further information visit https://errors.pydantic.dev/2.5/v/string_too_long
    name.1
      String should have at most 10 characters [type=string_too_long, input_value='01234567890123456789', input_type=str]
        For further information visit https://errors.pydantic.dev/2.5/v/string_too_long
    

    I hope this helps!