Search code examples
pythonclassinheritancepydantic

Pydantic AttributeError: '' object has no attribute '__fields_set__'


from pydantic import BaseModel

class A(BaseModel):
    date = ''

class B(A):
    person: float

    def __init__(self):
        self.person = 0
    
B()

tried to initiate class B but raised error AttributeError: 'B' object has no attribute '__fields_set__', why is it?


Solution

  • It's because you override the __init__ and do not call super there so Pydantic cannot do it's magic with setting proper fields.

    With pydantic it's rare you need to implement your __init__ most cases can be solved different way:

    from pydantic import BaseModel
    
    class A(BaseModel):
        date = ""
    
    class B(A):
        person: float = 0
    
    B()