如何针对错误的泛型类型强制执行 Pydantic 错误引发

问题描述 投票:0回答:1

下面你可以看到我的代码

from pydantic import BaseModel
from typing import TypeVar, Generic

T = TypeVar('T')

class GenericItem(BaseModel, Generic[T]):
    item: T

# Examples of using GenericItem
string_item = GenericItem[str](item="example")
int_item = GenericItem[int](item=42)

# This will raise a validation error because 'item' is expected to be of type 'int'
try:
    invalid_item = GenericItem[int](item="invalid")
except Exception as e:
    print(f"Validation error: {e}")

我想使用通用值

T
并且我有一个该值的字段
item

当我创建

GenericItem[int](item="invalid")
时,它应该会抛出错误,因为输入应该是
int
,但它是一个
str
。然而,没有出现任何错误。

我怎样才能做到这一点,这样在这种情况下它只会接受指定类型的输入

T

python python-3.x pydantic typing
1个回答
0
投票

我认为这是 v1.10.x 中的预期功能。

正如我所评论的,在 V2 之后,效果很好。但在 v1.10x 中,你需要使用

GenericModel

from pydantic.generics import GenericModel  # Import `GenericModel` instead of `BaseModel`
from typing import TypeVar, Generic

T = TypeVar('T')

class GenericItem(GenericModel, Generic[T]):  # use `GenericModel`
    item: T

# Examples of using GenericItem
string_item = GenericItem[str](item="example")
int_item = GenericItem[int](item=42)

# This will raise a validation error because 'item' is expected to be of type 'int'
try:
    invalid_item = GenericItem[int](item="invalid")
except Exception as e:
    print(f"Validation error: {e}")

运行它;你可能有

Validation error: 1 validation error for GenericItem[int]
item
  value is not a valid integer (type=type_error.integer)

参考:https://docs.pydantic.dev/1.10/usage/models/#generic-models

© www.soinside.com 2019 - 2024. All rights reserved.