8

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 = "[email protected]")   # fails as expected
ms = MyStuff(name = "me")
ms.name = "[email protected]"
print(ms.name)   # prints [email protected]

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?

1 Answer 1

16

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
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any disadventage setting validate_assignment = True? I wonder why it is default False.
@AntonioRomeroOca i think it's due to the overhead of running the validation every time there is a change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.