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

Python中动态混合泛型类型返回值的类型提示实现方法

解决混合泛型Command元组的类型推导问题

要实现支持混合泛型类型的process函数,让语言服务器能正确推导返回元组中每个元素的类型,需要用到Python的可变长度类型变量元组(TypeVarTuple)和类型展开(Unpack)特性,具体修改如下:

修改后的代码

from typing import Generic, Tuple, TypeVarTuple, Unpack

T = TypeVar("T")

class Command(Generic[T]):
    def __init__(self, value: T):
        self.value = value

# 定义可变长度的类型变量元组,用于捕获输入元组中每个Command的泛型类型
Ts = TypeVarTuple('Ts')

def process(commands: Tuple[Command[Unpack[Ts]], ...]) -> Tuple[Unpack[Ts]]:
    return tuple(cmd.value for cmd in commands)

a = Command[int](1)
b = Command[str]("foobar")
c = Command[int](2)
a_, b_, c_ = process((a, b, c))
# 此时语言服务器会正确识别:a_为int,b_为str,c_为int

关键说明

  1. TypeVarTuple:用来定义一组可变长度的类型变量,能匹配输入元组中每个Command对象的不同泛型类型(比如这里的int、str、int)。
  2. Unpack:在函数参数和返回值中展开Ts,让输入的Tuple[Command[T1], Command[T2], ...]对应返回的Tuple[T1, T2, ...],实现类型的一一映射。

兼容旧版本Python

如果使用Python 3.9及以下版本,需要先安装typing_extensions库:

pip install typing_extensions

再修改导入语句:

from typing_extensions import TypeVarTuple, Unpack
from typing import Generic, Tuple, TypeVar

内容的提问来源于stack exchange,提问作者Wietse de Vries

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:00:58