0

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?

Gnut
  • 541
  • 1
  • 5
  • 19

1 Answers1

2

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.

Hernán Alarcón
  • 3,494
  • 14
  • 16
  • 1
    Thank you. I solved my problem with a metaclass that copies all the annotations from the parent class, almost exactly like the code in this answer: https://stackoverflow.com/questions/67699451/make-every-fields-as-optional-with-pydantic. So I believe the root problem is that the child classes in Python don't inherit annotations from the parent classes as I initially thought. – Gnut Mar 13 '22 at 02:39