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, validator
class 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 = "me@example.com") # fails as expected
ms = MyStuff(name = "me")
ms.name = "me@example.com"
print(ms.name) # prints me@example.com
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?
This is the default behavior. To enable validation on field assignment, set validate_assignment
in the model config to true:
class MyStuff(BaseModel):
name: str
@validator("name")
def ascii(cls, v):
assert v.isalpha() and v.isascii(), "must be ASCII letters only"
return v
class Config:
validate_assignment = True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.