简体   繁体   English

VS Code 中的 Pydantic 自动补全

[英]Pydantic autocompletion in VS Code

When i use pydantic in VS Code, the code snippet shows User(**data: Any) .当我在 VS Code 中使用 pydantic 时,代码片段显示User(**data: Any) Is there any way for VS Code to show correct documentation? VS Code 有什么方法可以显示正确的文档吗? like User(name: str, email: str)喜欢User(name: str, email: str)

在此处输入图像描述

As of today, the problem persists, both for pydantic's BaseModel classes, as well as the pydantic version of @dataclass decorator.到今天为止,对于 pydantic 的BaseModel类以及@dataclass装饰器的 pydantic 版本,问题仍然存在。

In case of BaseModel , add the following piece of code to your imports:如果是BaseModel ,请将以下代码添加到您的导入中:

from typing import TYPE_CHECKING
from pydantic import BaseModel


if TYPE_CHECKING:
    from dataclasses import dataclass as _basemodel_decorator
else:
    _basemodel_decorator = lambda x: x

Then, decorate all classes as follows:然后,按如下方式装饰所有类:

@_basemodel_decorator
class MyClass(BaseModel):
    foo: int
    bar: str

Alternatively, if you are using pydantic's version of the dataclass decorator boilerplate code is simpler:或者,如果您使用dataclass版本的数据类装饰器样板代码更简单:

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from dataclasses import dataclass
else:
    from pydantic.dataclasses import dataclass

Then continue as usual:然后像往常一样继续:

@dataclass
class MyClass2:
    foo: int
    bar: str

Result:结果: 构造函数参数的提示显示在 VS Code 中

More info:更多信息:

Make sure that you've selected a python interpreter, that has pydantic installed.确保您选择了安装了 pydantic 的 python 解释器。

VS code python extension will give you ability of syntax highlighting, as well as loading an interpreter. VS 代码 python 扩展将为您提供语法突出显示以及加载解释器的能力。

In right down corner of VS code you will find python interpreter selection在 VS 代码的右下角,您会找到 python 解释器选择
(in my case 3.9.12 version) (在我的情况下是 3.9.12 版本)
在此处输入图像描述

Working example:工作示例:
工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM