简体   繁体   English

以优雅的方式使用 Pydantic 检查 List 是否为空

[英]Check if List is not empty with Pydantic in an elegant way

Let's say I have some BaseModel , and I want to check that it's options list is not empty.假设我有一些BaseModel ,我想检查它的options列表是否为空。 I can perfectly do it with a validator :我可以用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?还有其他更优雅的方法吗?

If you want to use a @validator :如果你想使用@validator

return v if v else doSomething

Python assumes boolean-ess of an empty list as False Python 将空列表的布尔值假定为 False

If you don't want to use a @validator :如果您不想使用@validator

In Pydantic, use conlist :在 Pydantic 中,使用conlist

from pydantic import BaseModel, conlist
from typing import List

class Trait(BaseModel):
    name: str
    options: conlist(str, min_items=1)

In Python, empty lists are falsey, while lists with any number of elements are truthy:在 Python 中,空列表是假的,而具有任意数量元素的列表是真:

>>> 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.这意味着您可以简单地assert vassert Trait.options来确认列表是非空的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM