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

如何创建固定第三个类型参数的SimpleGenerator生成器类型别名?

如何创建泛型类型别名简化Generator[T1, T2, None]的使用

你可以通过正确定义泛型类型别名来实现需求,以下是可行的写法:

正确实现方式

Python 3.10+(使用TypeAlias标注)

from typing import Generator, TypeVar, TypeAlias

# 定义泛型类型变量
T1 = TypeVar("T1")
T2 = TypeVar("T2")

# 创建类型别名,绑定泛型参数
SimpleGenerator: TypeAlias = Generator[T1, T2, None]

# 使用类型别名
def my_generator() -> SimpleGenerator[int, str]:
    received_str = yield "请传入一个字符串"
    yield int(received_str)

Python 3.9及以下版本

from typing import Generator, TypeVar

T1 = TypeVar("T1")
T2 = TypeVar("T2")

# 直接定义泛型类型别名
SimpleGenerator = Generator[T1, T2, None]

def my_generator() -> SimpleGenerator[int, str]:
    received_str = yield "请传入一个字符串"
    yield int(received_str)

为什么你的两种尝试失败

  1. 直接赋值的写法不符合语法:

    • 你重复定义了T1(错误地把T2也写成T1),属于低级错误。
    • 泛型类型别名不能用SimpleGenerator['T1', 'T2'] = ...这种下标式写法,正确方式是让类型别名绑定TypeVar,通过类型参数推导实现泛型。
  2. 继承Generator类的方式不适用:

    • Python生成器函数返回的是原生Generator实例,并非你自定义的SimpleGenerator类的实例。类型检查器会严格校验返回类型的一致性,自定义类和原生Generator属于不同类型,因此会报错。

补充说明

如果你的场景是Generator[T, None, None](不需要发送值、也没有返回值),确实可以用Iterable[T]替代,这是更简洁的写法。但如果需要保留“可接收特定类型值”的类型约束,就需要使用上述的泛型类型别名方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:48:09