检查pydantic中的输入数据类型
是否有一种方法可以在Pydantic中检查输入变量的数据类型,例如:
class ModelParameters(BaseModel):
str_val: str
int_val: int
wrong_val: int
test = ModelParameters(**dict({
"str_val":"test",
"int_val":1,
"wrong_val":1.2}))
它应该为forgation_val
丢弃错误。
Is there a way to check the datatypes of the input variables natively in pydantic, like:
class ModelParameters(BaseModel):
str_val: str
int_val: int
wrong_val: int
test = ModelParameters(**dict({
"str_val":"test",
"int_val":1,
"wrong_val":1.2}))
Which should throw an error for wrong_val
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
v2.0编辑:
随着 2.0版的发布,Pydantic的行为发生了变化。 现在给出的示例将为
forgation_val
提出错误。与下面公开的pydantic 1.x相比,v2.x也不会将int类似
123
放入“ 123”
str中,如果属性类型为str
。对于pydantic 1.x (原始答案)
Pydantic进行了一些隐式转换,尤其是在INT,STR或Float等原始类型上。讨论了这种行为背后的原因在这里。
因此,确实,有了这样的课程:
您可以绝对实例化这样的对象:
,但是您 do 可以选择执行类型检查。您需要做的是要使用
strictstr
,strictfloat
和strictInt
作为STR,float和int的类型纯种替代品。您会在pydantic.types
中找到它们。在您的情况下:现在,如果您尝试相同的实例化,您会发现到处都有验证错误,就像您期望的那样:
v2.0 Edit:
Pydantic's behaviour has changed with the release of version 2.0. Now the example given will raise an error for
wrong_val
, as expected.Compared to pydantic 1.x as exposed below, v2.x also doesn't parse an int like
123
into a"123"
str anymore if the attribute type isstr
.For pydantic 1.x (original answer)
Pydantic does a handful of implicit conversion, particularly on primitive types like int, str, or float. The reason behind this behaviour is discussed here.
So indeed, with a class like this:
You can absolutely instantiate an object like that:
But you do have the option to enforce type checking. What you need to do, is to use
StrictStr
,StrictFloat
andStrictInt
as a type-hint replacement for str, float and int. You'll find them inpydantic.types
. In your case:Now, if you try the same instantiation, you'll see validation errors all around the place, like you'd expect: