Pydantic 继承泛型类

Sye*_*fri 9 python generics pydantic

我是 python 和 pydantic 的新手,有打字稿背景。我想知道你是否可以继承泛型类?

在打字稿中,代码如下

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'
}
Run Code Online (Sandbox Code Playgroud)

我一直在尝试的是类似的事情

#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")
Run Code Online (Sandbox Code Playgroud)

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

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

jki*_*ead 12

泛型在 Python 中有点奇怪,问题是ExtendsGenericField它本身没有声明为泛型。要解决这个问题,只需添加Generic[T]以下内容的超类ExtendsGenericField

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")
Run Code Online (Sandbox Code Playgroud)