0

I am receiving an intellisense error on an inherited pydantic dataclass. I was able to replicate this on two operating systems, one in VSCode, the other in pycharm.

You can replicate the intellisense error with this snippet:

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]))

The error takes place in the implemented print_bio function. The full error is in the comments above. Is there a way to resolve this and gain back the intellisense?

Jeff Gruenbaum
  • 364
  • 6
  • 21
  • I don't know, but maybe this approach could help https://stackoverflow.com/a/69344698/202168 – Anentropic Apr 27 '22 at 15:16
  • @Anentropic Thanks for the response. I think that is a separate issue, but good to note. I believe I found a way to make the intellisense work, but am still kind of wondering why it doesn't work in the way described above. – Jeff Gruenbaum Apr 27 '22 at 16:41

1 Answers1

0

I was able to resolve this by inheriting from BaseModel, instead of using pydantic.dataclasses.dataclass. I believe this is a bug with pydantic dataclasses or with Pylance, but using the BaseModel is a workable solution.

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]))
Jeff Gruenbaum
  • 364
  • 6
  • 21