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:
[]
empty list with no sublists is valid[["a", "b"], ["c", "d", "e"]
is valid because each sub-list is of at least length 2The following are not valid:
[[]]
an empty sub-list is not valid[["a"], ["b", "c"]
one of the sub-lists has a length less than two which is invalidHow do I do this in Pydantic? I don't think I can nest conlist
? Can I use typing.Annotated
to accomplish this?
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)