Pydantic防止错误类型的转换



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

然而,我有一个场景,我想避免这种行为,而是收到一个验证错误,如果属性不是预期的类型。请看下面的例子:

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)}")

执行此模块的输出:

created Imposter with {'imposter_prop': 0}
created Child with {'imposter_prop': 0}
created Parent with {'child': Imposter(imposter_prop=0)}
is child: True

正如您所看到的,Pydantic愉快地允许我为应该是Child的属性创建具有Imposter对象的Parent。它通过使用Imposter的属性创建Child来支持这一点。我不希望这种事发生。

我已经看了Pydantic文档,但是没有一个配置选项跳出来作为改变这种行为的候选人。我能做些什么来阻止这种类型转换吗?

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