Search code examples
pythonpython-3.xmodelpydantic

con't define variable in pydantic init function


i want to define a Base model that inherits from pydantic BaseModel like bellow

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)