Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor and Pydantic

I want to create a Pydantic class with a constructor that does some math on inputs and set the object variables accordingly:

class PleaseCoorperate(BaseModel):
    self0: str
    next0: str

    def __init__(self, page: int, total: int, size: int):
        # Do some math here and later set the values
        self.self0 = ""
        self.next0 = ""
    

But when I try to actually use that class page = PleaseCoorperate(0, 1, 50) I get this error:

main_test.py:16: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
main.py:46: in __init__
    self.self0 = ""
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

>   ???
E   AttributeError: __fields_set__

What is happening here? Can I not use constructors on a Pydantic class?

like image 366
Jenia Ivanov Avatar asked Mar 28 '26 11:03

Jenia Ivanov


1 Answers

You are not invoking the BaseModel constructor, and thus, you are skipping all the pydantic magic that turns class variables into attributes. This:

class PleaseCoorperate(BaseModel):
    self0: str
    next0: str

    def __init__(self, page: int, total: int, size: int):
        # Do some math here and later set the values
        self0 = ""
        next0 = ""
        super().__init__(self0=self0, next0=next0)

should do the trick. However, may I suggest a better option that doesn't override the much excellent default constructor from pydantic with a class method:

class PleaseCoorperate(BaseModel):
    self0: str
    next0: str

    @classmethod
    def custom_init(cls, page: int, total: int, size: int):
        # Do some math here and later set the values
        self0 = ""
        next0 = ""
        return cls(self0=self0, next0=next0)

x = PleaseCoorperate.custom_init(10, 10, 10)
like image 136
amiasato Avatar answered Mar 30 '26 01:03

amiasato