I want to use Pydantic to validate fields in my object, but it seems like validation only happens when I create an instance, but not when I later modify fields.
from pydantic import BaseModel, validatorclass MyStuff(BaseModel):name: str@validator("name")def ascii(cls, v):assert v.isalpha() and v.isascii(), "must be ASCII letters only"return v# ms = MyStuff(name = "[email protected]") # fails as expected
ms = MyStuff(name = "me")
ms.name = "[email protected]"
print(ms.name) # prints [email protected]
In the above example, Pydantic complains when I try to pass an invalid value when creating MyStuff
, as expected.
But when I modify the field afterwards, Pydantic does not complain. Is this expected, or how can I have Pydantic also run the validator when assigning a field?