Pydantic 继承泛型 class

Pydantic inherit generic class

python 的新手和 pydantic,我来自 typescript 背景。我想知道您是否可以继承泛型 class?

在打字稿中,代码如下

interface GenericInterface<T> {
  value: T
}

interface ExtendsGeneric<T> extends GenericInterface<T> {
  // inherit value from GenericInterface
  otherValue: string
}

const thing: ExtendsGeneric<Number> = {
  value: 1,
  otherValue: 'string'
}

我一直在尝试的是

#python3.9
from pydantic.generics import GenericModel
from typing import TypeVar
from typing import Generic

T = TypeVar("T", int, str)

class GenericField(GenericModel, Generic[T]):
    value: T

class ExtendsGenericField(GenericField[T]):
    otherValue: str

ExtendsGenericField[int](value=1, otherValue="other value")

我得到 TypeError: Too many parameters for ExtendsGenericField; actual 1, expected 0 的错误。 这种检查是因为在 Pydantic docs 中它明确指出“为了声明一个通用模型......使用 TypeVar 实例作为注释,你将要替换它们......” 简单的解决方法是ExtendsGeneric 继承自 GenericModel 并在其自己的 class 定义中包含 value,但我试图重用 classes.

是否可以从泛型 class 继承值?

泛型在 Python 中有点奇怪,问题是 ExtendsGenericField 本身没有声明为泛型。要解决,只需将 Generic[T] 添加为 ExtendsGenericField 的超级 class:

from pydantic.generics import GenericModel
from typing import TypeVar
from typing import Generic

T = TypeVar("T", int, str)

class GenericField(GenericModel, Generic[T]):
    value: T

class ExtendsGenericField(GenericField[T], Generic[T]):
    otherValue: str

ExtendsGenericField[int](value=1, otherValue="other value")