我正在发现 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.
发布评论
评论(1)
接受
None
作为值的字段可以使用typing.Optional
进行声明:请参阅 字段类型,了解有关支持的字段类型的更多信息:
Fields that accept
None
as value can be declared usingtyping.Optional
:See Field Types in the pydantic documentation for more information about the supported field types: