Nicolas Acosta
Nicolas Acosta

Reputation: 807

Pydantic autocompletion in VS Code

When i use pydantic in VS Code, the code snippet shows User(**data: Any). Is there any way for VS Code to show correct documentation? like User(name: str, email: str)

enter image description here

Upvotes: 14

Views: 3929

Answers (2)

Robert Mielewczyk
Robert Mielewczyk

Reputation: 91

Make sure that you've selected a python interpreter, that has pydantic installed.

VS code python extension will give you ability of syntax highlighting, as well as loading an interpreter.

In right down corner of VS code you will find python interpreter selection
(in my case 3.9.12 version)
enter image description here

Working example:
Working example

Upvotes: 1

amka66
amka66

Reputation: 823

As of today, the problem persists, both for pydantic's BaseModel classes, as well as the pydantic version of @dataclass decorator.

In case of BaseModel, add the following piece of code to your imports:

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:

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: hints for the constructor parameters are showing in VS Code

More info:

Upvotes: 3

Related Questions