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