When assigning an incorrect attribute to a Pydantic model field, no validation error occurs.
from pydantic import BaseModelclass pyUser(BaseModel):username: strclass Config:validate_all = Truevalidate_assignment = Trueperson = pyUser(username=1234)
person.username
>>>1234
try_again = pyUser()pydantic.error_wrappers.ValidationError:
[ErrorWrapper(exc=MissingError(), loc=('username',))]
<class '__main__.pyUser'>
How can I get pydantic to validate on assignment?
It is expected behaviour according to the documentation:
str
strings are accepted as-is, int
, float
and Decimal
are coerced using str(v)
You can use the StrictStr
, StrictInt
, StrictFloat
, and StrictBool
types to prevent coercion from compatible types.
from pydantic import BaseModel, StrictStrclass pyUser(BaseModel):username: StrictStrclass Config:validate_all = Truevalidate_assignment = Trueperson = pyUser(username=1234) # ValidationError `str type expected`
print(person.username)