Jea*_*vFR 4 python typing option-type pydantic fastapi
目前,我正在学习Python和Fastapi,但我不知道打字的用途。可选的。
class Post(BaseModel):
# default value
rating: int = None
# typing.Optional
rating: Optional[int] = None
Run Code Online (Sandbox Code Playgroud)
两者都有效。我不明白有什么区别。
从文档(参见typing.Optional):
Optional[x]只是简写Union[x, None]
在 Pydantic 中,这意味着指定字段值变得可选。换句话说,初始化模型时不需要传递字段和值,该值将默认为(这与此处None
描述的函数调用中的可选参数略有不同)。
也没有必要明确指定None为默认值。
在这种情况下,它似乎主要是语法糖,但它有助于使模型更具可读性。在更高级的情况下,可能需要要求将字段显式传递到模型中,即使该值可能是,如“必需的可选字段”None部分中所建议的,在这种情况下,区分就变得必要了。
它始终取决于用例,但使用相同类型的默认值或将字段设为必填并不罕见。
这是一个更常见的场景:
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]
Run Code Online (Sandbox Code Playgroud)
# 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20743 次 |
| 最近记录: |