为什么 Pydantic 不验证字段分配?

Why doesn't Pydantic validate field assignments?

我想使用 Pydantic 来验证我的对象中的字段,但似乎验证只在我创建实例时发生,但在我稍后修改字段时不会发生。

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 = "me@example.com")   # fails as expected
ms = MyStuff(name = "me")
ms.name = "me@example.com"
print(ms.name)   # prints me@example.com

在上面的示例中,当我在创建 MyStuff 时尝试传递无效值时,Pydantic 会如预期的那样抱怨。

但是当我之后修改字段时,Pydantic 没有抱怨。这是预期的吗,或者在分配字段时如何让 Pydantic 也 运行 验证器?

这是默认行为。要启用字段分配验证,请将 model config 中的 validate_assignment 设置为 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