来自documentation(见typing.Optional):
Optional[x] 只是 Union[x, None] 的简写
在 Pydantic 中,这意味着该字段变为可选,在初始化模型时不需要传递任何内容,并且该字段将默认为 None(这与函数调用中的可选参数略有不同,如 @987654322 所述@)。
您也不需要明确指定 None 作为默认值。
在这种情况下,它似乎主要是语法糖,但它有助于使模型更具可读性。在更高级的情况下,您可能需要将一个字段显式传递到模型中,即使它可能是 None,正如 Require Optional Fields 部分所建议的那样,在这种情况下,区分就变得必要了。
这始终取决于用例,但您通常会使用相同类型的默认值,或者将字段设为必填。
这是一个更常见的场景:
from pydantic import BaseModel
from typing import Optional
class Post(BaseModel):
# rating is required and must be an integer.
rating: int
# counter is not required and will default to 1 if nothing is passed.
counter: int = 1
# comment is optional and will be coerced into a str.
comment: Optional[str]
# This will work:
post = Post(rating=10)
repr(post)
# 'Post(rating=10, counter=1, comment=None)'
# This will work as well:
post = Post(rating=10, comment="some text")
repr(post)
# "Post(rating=10, counter=1, comment='some text')"
# But this won't work:
post = Post(comment="some text")
# ...
# ValidationError: 1 validation error for Post
# rating
# field required (type=value_error.missing)
# And this won't work either:
post = Post(rating=10, counter=None)
# ...
# ValidationError: 1 validation error for Post1
# counter
# none is not an allowed value (type=type_error.none.not_allowed)