Pydantic model does not validate on assignment with reproducable code

孤者浪人 提交于 2021-01-28 11:18:46

问题


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?


回答1:


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, 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)


来源:https://stackoverflow.com/questions/65213809/pydantic-model-does-not-validate-on-assignment-with-reproducable-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!