Why do I get "AttributeError: __fields_set__" when subclassing a Pydantic BaseModel?
Full error message
I have this project where my base class and my sub-classes implement pydantic.BaseModel:
from pydantic import BaseModel
from typing import List
from dataclasses import dataclass
@dataclass
class User(BaseModel):
id: int
@dataclass
class FavoriteCar(User):
car_names: List[str]
car = FavoriteCar(id=1, car_names=["Acura"])
print(f"{car.id} {car.car_names[0]}")
But this error appears:
self.__fields_set__.add(name)
E AttributeError: __fields_set__
Does someone mind explaining what is going on? The reason why I want to use pydantic is because I need a way to quickly convert Python objects to dict (or JSON) and back.Solutionsource: stackoverflow \u2197
You need to decide whether to inherit from pydantic.BaseModel, or whether to use the @dataclass decorator (either from dataclasses, or from pydantic.dataclasses). Either is fine, but you cannot use both, according to the documentation (bold face added by myself): If you don't want to use pydantic's BaseModel you can instead get the same data validation on standard dataclasses
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/e8e118ada754be86cf510bc2ba74c8bbe72496381d1ce88b3e713175d83a983bhash \u00b7 e8e118ada754be86cf510bc2ba74c8bbe72496381d1ce88b3e713175d83a983b