You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Pydantic GenericModel的工厂类方法添加类型提示

问题:为Pydantic泛型模型的类方法添加正确的泛型返回类型

我定义了一个带类型参数的Pydantic GenericModel类,代码如下:

from datetime import datetime
from typing import Generic, TypeVar
from pydantic import BaseModel
from pydantic.generics import GenericModel


T = TypeVar("T", bound=BaseModel)


class OcpiResponse(GenericModel, Generic[T]):
    data: T
    status_code: int
    status_message: str
    timestamp: str

    @classmethod
    def success(cls, data: Generic[T]):
        return cls(
            data=data,
            status_code=1000,
            status_message="Success",
            timestamp=datetime.now().isoformat()
        )

需求是为success类方法添加能捕获类型参数的返回类型,使得以下代码中返回类型不匹配时,IDE能给出错误/警告:

class Test1(BaseModel):
    pass


class Test2(BaseModel):
    pass


def test() -> OcpiResponse[Test2]:
    return OcpiResponse.success(Test1())

我尝试过以下方案,但都无法满足需求:

  • Self[T]:报错TypeError: typing.Self is not subscriptable
  • Self:无法捕获类型参数,不会触发类型不匹配警告
  • OcpiResponse[T]:提示Unresolved reference 'OcpiResponse',且无法触发警告
  • cls[T]:提示Unresolved reference 'cls'

解决方案

修改success方法的类型标注,明确绑定泛型参数与返回类型,代码如下:

from datetime import datetime
from typing import Generic, TypeVar, Type
from pydantic import BaseModel
from pydantic.generics import GenericModel


T = TypeVar("T", bound=BaseModel)


class OcpiResponse(GenericModel, Generic[T]):
    data: T
    status_code: int
    status_message: str
    timestamp: str

    @classmethod
    def success(cls: Type["OcpiResponse[T]"], data: T) -> "OcpiResponse[T]":
        return cls(
            data=data,
            status_code=1000,
            status_message="Success",
            timestamp=datetime.now().isoformat()
        )

修改说明

  1. 参数类型修正:将data: Generic[T]改为data: T,T是我们定义的类型变量,代表data的实际类型,Generic[T]并非具体类型,无法正确标注参数。
  2. cls的类型标注:添加cls: Type["OcpiResponse[T]"],告诉类型检查器当前cls是绑定了类型参数T的OcpiResponse类,解决前向引用问题。
  3. 返回类型标注:使用"OcpiResponse[T]"作为返回类型,明确返回的是带有对应类型参数的泛型实例,让类型检查器能够准确推断并校验返回类型。

修改后,运行测试代码时,IDE会因为OcpiResponse.success(Test1())返回OcpiResponse[Test1],但函数声明返回OcpiResponse[Test2]而给出类型不匹配的警告,符合需求。


内容的提问来源于stack exchange,提问作者Robert Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:52:41