pythonpython-3.xpydantic

Can't define variable in pydantic init function


I want to define a BaseDomain model that inherits from pydantic BaseModel like below

class BaseDomain(BaseModel):

    def __init__(self, **kwargs):
        self.__exceptions = []

    def add_error(self, exception: GeneralException):
        self.__exceptions.append(exception)

but I get this error when I use Product model that inherits from BaseDomain

ValueError: "Product" object has no field "_BaseDomain__exceptions"

Solution

  • Because you have overidden pydantic's init method that is executed when a class that inherits from BaseModel is created. you should call super()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.__exceptions = []
    

    EDIT

    It seems that pydantic throws that error because it validates __exceptions as an input and throws an error because it isn't defined in the classes annotations

    Try this:

    from typing import List, Any
    
    class BaseDomain(BaseModel):
        __exceptions:List[Any] = []
    
        def __init__(self, **kwargs):
            super().__init__(**kwargs)