VSCode 中的 Pydantic Dataclasses Intellisense 错误

Pydantic Dataclasses Intellisense Error in VSCode

我在继承的 pydantic 数据类上收到智能感知错误。我能够在两个操作系统上复制它,一个在 VSCode,另一个在 pycharm.

您可以使用此代码段复制智能感知错误:

from abc import ABC, abstractmethod
from pydantic import BaseModel, dataclasses
from typing import List

# python --version -> Python 3.10.2
# pydantic=1.9.0
# Running on MacOS Monterey 12.3.1


@dataclasses.dataclass(frozen=True, eq=True)
class PersonABC(ABC):
    name: str

    @abstractmethod
    def print_bio(self):
        pass

@dataclasses.dataclass(frozen=True, eq=True)
class Jeff(PersonABC):
    age: int

    def print_bio(self):
        print(f"{self.name}: {self.age}")     # In VScode, self.name is not registered as a known variable:
                                              # `Cannot access member "name" for type "Jeff"
                                              # Member "name" is unknownPylancereportGeneralTypeIssues`

class Family(BaseModel):
    person: List[PersonABC]


jeff = Jeff(name="Jeff Gruenbaum", age=93)
print(Family(person=[jeff]))

错误发生在实现的print_bio函数中。完整的错误在上面的评论中。 有没有办法解决这个问题并重新获得智能感知?

我能够通过从 BaseModel 继承来解决这个问题,而不是使用 pydantic.dataclasses.dataclass。我认为这是 pydantic 数据类或 Pylance 的错误,但使用 BaseModel 是一个可行的解决方案。

from abc import ABC, abstractmethod
from typing import List
from pydantic import BaseModel

# python --version -> Python 3.10.2
# pydantic=1.9.0
# Running on MacOS Monterey 12.3.1


class PersonABC(ABC, BaseModel):
    name: str

    @abstractmethod
    def print_bio(self):
        pass

class Jeff(PersonABC):
    age: int

    def print_bio(self):
        print(f"{self.name}: {self.age}")     # Now the intellisense error does not appear.

class Family(BaseModel):
    person: List[PersonABC]


jeff = Jeff(name="Jeff Gruenbaum", age=93)
print(Family(person=[jeff]))