'How to make Pydantic recognize attributes from non-model parent class?
I have a normal Python class:
class NormalClass:
a: str
b: bool
I don't want NormalClass to inherit from pydantic.BaseModel class, but I still want another class with the same attributes as NormalClass and it being a Pydantic model. So here's what I try:
class ModelClass(BaseModel, NormalClass):
pass
Unfortunately, when I try to use this ModelClass to validate server response in FastAPI, I always get {}. What happens here?
Solution 1:[1]
I believe that you cannot expect to inherit the features of a pydantic model (including fields) from a class that is not a pydantic model.
a and b in NormalClass are class attributes. Although the fields of a pydantic model are usually defined as class attributes, that does not mean that any class attribute is automatically a field. NormalClass is not a pydantic model because it does not inherit from BaseModel. ModelClass has no fields because it does not define any fields by itself and has not inherited any fields from a pydantic model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hernán Alarcón |
