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)}")
执行此模块的输出:
created Imposter with {'imposter_prop': 0}
created Child with {'imposter_prop': 0}
created Parent with {'child': Imposter(imposter_prop=0)}
is child: True
正如你所看到的,Pydantic 很高兴地允许我为应该是的属性创建一个Parent
带有对象的对象。它通过使用. 我不希望这种情况发生。Imposter
Child
Child
Imposter
我已经查看了 Pydantic 文档,但没有一个配置选项会突然出现在我身上,作为改变这种行为的候选者。有什么办法可以防止这种类型转换的尝试吗?
解决方案
如果您正在使用带有内置类型的东西并且想要防止强制,您可以使用 pydantic strict types。鉴于您是自定义类型,我相信您可能需要在自定义类型中明确定义自己的validate(cls, v) @classmethod
etc。它们提供了自定义数据类型验证的示例,包括isinstance
您想要使用的用法。
推荐阅读
- python - 正则表达式匹配捕获组 n 次
- angular - 在角度导入中,“导入”语句在哪里以及如何查找库文件?
- r - 将字符串转换为日期 R 西班牙语
- powershell - GetDate 负 30 分钟并以 UTC 显示
- wordpress - WordPress过滤器停止渲染站点
- powerbi - 根据切片器选择更新的动态度量
- mysql - 如何修复 create-react-app 项目中的“获取”代理错误?
- xcode - 无法将本地存储库推送到 GitHub(返回错误 403)
- c++ - 我的服务器中的分段错误(valgrind 日志)
- python - Python:如何在python的数据框中有条件地从列中删除字母?