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

如何用PEP 646的TypeVarTuples实现接受类的可变泛型?

使用TypeVarTuples实现多类参数的类型标注

你想要用PEP 646的TypeVarTuples实现类似Type[C]接受类本身作为参数的功能,同时让函数接收多个类参数,返回对应类型的元组。原代码里qux的类型标注语法不对,修正后的写法如下:

from typing import TypeVar, TypeVarTuple, Unpack

T = TypeVar("T")
Ts = TypeVarTuple("Ts")

def foo(a: T) -> T:
    ...
def bar(a: type[T]) -> T:
    ...
def baz(*a: *Ts) -> tuple[*Ts]:
    ...

a = foo(int)  # 类型为type[int]
b = bar(int)  # 类型为int
c = baz(int, str)  # 类型为tuple[type[int], type[str]]

# 正确的qux函数标注
def qux(*a: Unpack[tuple[type[*Ts]]]) -> tuple[*Ts]: 
    ...
d = qux(int, str)  # 类型推断为tuple[int, str]

关键说明

  • Unpack[tuple[type[*Ts]]]的作用是把TypeVarTuple Ts里的每个类型T都包装成type[T],然后作为可变参数的类型,这样函数就能接受int、str这类类对象作为输入。
  • 返回值tuple[*Ts]直接展开Ts中的类型,得到对应实例类型组成的元组,正好符合你想要的tuple[int, str]结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:53:19