pythonpydantic

Pydantic nestled list type with sub-list minimum length


I want to create a Pydantic class wrapping a list with string sub-lists that have to be at least of length two.

For example, the following are valid:

The following are not valid:

How do I do this in Pydantic? I don't think I can nest conlist? Can I use typing.Annotated to accomplish this?


Solution

  • You can use the annotated_types package to accomplish this, as discussed in the Pydantic Documentation.

    from typing import Annotated
    
    from annotated_types import MinLen
    import pydantic
    
    
    class SubListModel(pydantic.BaseModel):
        my_list: list[Annotated[list[str], MinLen(2)]]
    
    
    # Valid cases
    valid_empty = SubListModel(my_list=[])  # Empty list
    valid_lists = SubListModel(my_list=[["a", "b"], ["c", "d", "e"]])
    
    # Invalid cases - these will raise ValidationError
    try:
        invalid_empty_sublist = SubListModel(my_list=[[]])  # Will fail
    except pydantic.ValidationError as e:
        print("Empty sublist error:", e)
    
    try:
        invalid_short_sublist = SubListModel(my_list=[["a"], ["b", "c"]])  # Will fail
    except pydantic.ValidationError as e:
        print("Short sublist error:", e)