Skip to content Skip to sidebar Skip to footer

Pydantic Does Not Validate When Assigning A Number To A String

When assigning an incorrect attribute to a Pydantic model field, no validation error occurs. from pydantic import BaseModel class pyUser(BaseModel): username: str class C

Solution 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


classpyUser(BaseModel):
    username: StrictStr

    classConfig:
        validate_all = True
        validate_assignment = True


person = pyUser(username=1234)  # ValidationError `str type expected`print(person.username)

Post a Comment for "Pydantic Does Not Validate When Assigning A Number To A String"