Pydantic 防止错误类型的转换

tom*_*umb 7 python-3.x pydantic

当属性的类型不是预期的类型时,Pydantic 似乎会执行自动类型转换。我相信这就是为什么(方便地)可以通过原始 int 值来分配类的 int 枚举属性的值。

但是,我有一个场景,我想避免这种行为,如果属性不属于预期类型,则会收到验证错误。请参见以下示例:

from pydantic import BaseModel
from typing import List

class Common(BaseModel):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        print(f"created {self.__class__.__name__} with {kwargs}")

class Child(Common):
    child_prop: int = None

class Parent(Common):
    child: Child

class Imposter(Common):
    imposter_prop: int

parent = Parent(
    child=Imposter(imposter_prop=0)
)
print(f"is child: {isinstance(parent.child, Child)}")
Run Code Online (Sandbox Code Playgroud)

执行该模块的输出:

created Imposter with {'imposter_prop': 0}
created Child with {'imposter_prop': 0}
created Parent with {'child': Imposter(imposter_prop=0)}
is child: True
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,Pydantic 很高兴地允许我为应该是的属性创建Parent一个对象。它通过使用 的属性创建一个来支持这一点。我不希望这种事发生。ImposterChildChildImposter

我浏览了 Pydantic 文档,但没有一个配置选项让我想到可以改变这种行为。我可以采取什么措施来阻止这种类型转换尝试?

sha*_*all 4

如果您正在使用具有内置类型的东西并且想要防止强制转换,您可以使用 pydantic strict types。鉴于您是自定义类型,我相信您可能需要validate(cls, v) @classmethod在自定义类型中显式定义您自己的等。它们提供了自定义数据类型验证的示例isinstance,包括您想要使用的用法。