我如何获得属属的类型检查以与此pydantic示例一起使用?

发布于 2025-01-19 11:11:36 字数 859 浏览 3 评论 0 原文

我正在发现 Pydantic,并且在示例中看到了这一点 (https:// pydantic-docs.helpmanual.io/usage/models/#recursive-models):

from pydantic import BaseModel

class Foo(BaseModel):
    count: int
    size: float = None

我正在使用 VS Code 和 Pylance,到目前为止,我一直忽略Pylance 的类型检查功能,因为我有多个实例,需要能够将 None 设置为类型注释中没有 None 的字段的默认值。

我在 Pydantic 中看到了这一点,Pydantic 与 Pylance 配合得很好,但与所有其他时间一样,我尝试将默认值 None 设置为未用 None 注释的字段,Pylance 用 Expression 类型标记它“None”无法分配给声明的类型问题。

我想,如果它应该在 Pydantic 中工作,但它不适合我,那么一定是我遗漏了一些东西。

我已按照 https://pydantic-docs.helpmanual.io/visual_studio_code/ 设置 VS Code 似乎仍然不起作用。

I'm discovering Pydantic and I see this in an example (https://pydantic-docs.helpmanual.io/usage/models/#recursive-models):

from pydantic import BaseModel

class Foo(BaseModel):
    count: int
    size: float = None

I'm using VS Code and Pylance, and until now, I had been ignoring Pylance's type checking functionality because I have multiple instances where I need to be able to set None as the default to a field that doesn't have None in its type annotation.

I see this in Pydantic, and Pydantic works fine with Pylance, but as is with all the other times I've tried to set a default of None to a field not annotated with None, Pylance flags it with a Expression of type "None" cannot be assigned to declared type problem.

I figure that if it's meant to work in Pydantic, and it doesn't for me, there has to be something I'm missing.

I've set up VS Code as per https://pydantic-docs.helpmanual.io/visual_studio_code/ and it still seems to not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

醉南桥 2025-01-26 11:11:36

接受 None 作为值的字段可以使用 typing.Optional 进行声明:

from pydantic import BaseModel
from typing import Optional

class Foo(BaseModel):
    count: int
    size: Optional[float] = None

请参阅 字段类型,了解有关支持的字段类型的更多信息:

打字。可选

Optional[x] 只是 Union[x, None] 的简写;有关解析和验证的更多详细信息,请参阅下面的 Union 以及 必填字段 了解有关可以接收的必填字段的详细信息None 作为值。

Fields that accept None as value can be declared using typing.Optional:

from pydantic import BaseModel
from typing import Optional

class Foo(BaseModel):
    count: int
    size: Optional[float] = None

See Field Types in the pydantic documentation for more information about the supported field types:

typing.Optional

Optional[x] is simply short hand for Union[x, None]; see Unions below for more detail on parsing and validation and Required Fields for details about required fields that can receive None as a value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文