When assigning an incorrect attribute to a Pydantic model field, no validation error occurs.
from pydantic import BaseModel
class pyUser(BaseModel):
username: str
class Config:
validate_all = True
validate_assignment = True
person = 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
andDecimal
are coerced usingstr(v)
You can use the StrictStr
, StrictInt
, StrictFloat
, and StrictBool
types to prevent coercion from compatible types.
from pydantic import BaseModel, StrictStr
class pyUser(BaseModel):
username: StrictStr
class Config:
validate_all = True
validate_assignment = True
person = pyUser(username=1234) # ValidationError `str type expected`
print(person.username)
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.