我正在尝试验证具有“可选”字段的对象,因为它们可能存在也可能不存在。但是当它们存在时,这些字段应该符合特定的类型定义(而不是无)。
在下面的示例中,“size”字段是可选的,但允许 None。我希望“大小”字段是可选的,但如果存在,它应该是一个浮点数。
from pydantic import BaseModel
class Foo(BaseModel):
count: int
size: float = None # how to make this an optional float?
>>> Foo(count=5)
Foo(count=5, size=None) # GOOD - "size" is not present, value of None is OK
>>> Foo(count=5, size=None)
Foo(count=5, size=None) # BAD - if field "size" is present, it should be a float
# BONUS
>>> Foo(count=5)
Foo(count=5) # BEST - "size" is not present, it is not required to be present, so we don't care about about validating it all. We are using Foo.json(exclude_unset=True) handles this for us which is fine.