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?
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With