Check if List is not empty with Pydantic in an elegant way
Question:
Let’s say I have some BaseModel
, and I want to check that it’s options
list is not empty. I can perfectly do it with a validator
:
class Trait(BaseModel):
name: str
options: List[str]
@validator("options")
def options_non_empty(cls, v):
assert len(v) > 0
return v
Are there any other, more elegant, way to do this?
Answers:
In Python, empty lists are falsey, while lists with any number of elements are truthy:
>>> bool([])
False
>>> bool([1,2,3])
True
>>> bool([False])
True
>>> bool([[]])
True
This means that you can simply assert v
or assert Trait.options
to confirm that the list is non-empty.
If you want to use a @validator
:
return v if v else doSomething
Python assumes boolean-ess of an empty list as False
If you don’t want to use a @validator
:
In Pydantic, use conlist
:
from pydantic import BaseModel, conlist
from typing import List
class Trait(BaseModel):
name: str
options: conlist(str, min_length=1)
Use Field
with min_length
:
from typing import List
from pydantic import BaseModel, Field
class Trait(BaseModel):
name: str
options: List[str] = Field(min_length=1)
min_length
is on the string constraints session but still works for lists.
Let’s say I have some BaseModel
, and I want to check that it’s options
list is not empty. I can perfectly do it with a validator
:
class Trait(BaseModel):
name: str
options: List[str]
@validator("options")
def options_non_empty(cls, v):
assert len(v) > 0
return v
Are there any other, more elegant, way to do this?
In Python, empty lists are falsey, while lists with any number of elements are truthy:
>>> bool([])
False
>>> bool([1,2,3])
True
>>> bool([False])
True
>>> bool([[]])
True
This means that you can simply assert v
or assert Trait.options
to confirm that the list is non-empty.
If you want to use a @validator
:
return v if v else doSomething
Python assumes boolean-ess of an empty list as False
If you don’t want to use a @validator
:
In Pydantic, use conlist
:
from pydantic import BaseModel, conlist
from typing import List
class Trait(BaseModel):
name: str
options: conlist(str, min_length=1)
Use Field
with min_length
:
from typing import List
from pydantic import BaseModel, Field
class Trait(BaseModel):
name: str
options: List[str] = Field(min_length=1)
min_length
is on the string constraints session but still works for lists.