Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite method on Pydantic instance

There are many solutions available to overwrite methods on instances. But for an object of the pydantic BaseModel this seems to be problematic. This is a simple example:

from pydantic import BaseModel

class Dog(BaseModel):
    def bark(self):
        print("WOOF")

def new_bark():
    print("WoOoOoF!!")

Running the method:

>>> boby = Dog()
>>> boby.bark()
WOOF

Overwriting the method:

>>> boby.bark = new_bark
>>> boby.bark()
ValueError: "Dog" object has no field "bark"

The expected result would be a printed # WoOoOoF!!. If Dog does not inherit pydantics BaseModel you get the expected result.

Is this even possible?

like image 668
Joost Döbken Avatar asked Aug 09 '26 06:08

Joost Döbken


1 Answers

I think the issue is somehow related with pydantic's __setattr__ method. It is some how different than normal objects. In this link, people deal with (not same but similar) issue. https://github.com/samuelcolvin/pydantic/issues/655

I don't know the internal details of pydantic or the cause of the issue, but I think this code would solve your problem:

>>> object.__setattr__(boby, "bark", new_bark)
>>> boby.bark()
WoOoOoF!!
like image 105
armamut Avatar answered Aug 10 '26 21:08

armamut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!