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

如何将现有TypeVar转换为Python 3.12类型参数语法?

问题:将TypeVar声明转换为Python 3.12新类型参数语法?

现有如下TypeVar声明:

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

def make_redis_client(c: ReadableContainer, cache_factory: Type[T], db: BffRedisDB) -> T:
    return cache_factory(redis=redis.Redis(host=c[BffEnvData].get_redis_connection_url(), port=c[BffEnvData].get_redis_connection_port(), db=db.value, decode_responses=False))

参考Python 3.12新语法示例:

type HashableSequence[T: Hashable] = Sequence[T]  # TypeVar with bound

我尝试了以下写法:

type CacheFactory[T] = Type[T] # 第一次尝试
type T[T: RedisCache] # 第二次尝试

第一次尝试出现错误:PEP 695 type aliases are not yet supportedMypyvalid-type

这是否意味着Mypy暂不支持Python 3.12的类型参数语法?


正确的Python 3.12写法

对于函数的类型参数,Python 3.12的PEP 695语法无需单独定义TypeVar,直接在函数签名里声明带约束的类型参数即可。你的make_redis_client函数可改写为:

def make_redis_client[T: RedisCache](c: ReadableContainer, cache_factory: Type[T], db: BffRedisDB) -> T:
    return cache_factory(redis=redis.Redis(host=c[BffEnvData].get_redis_connection_url(), port=c[BffEnvData].get_redis_connection_port(), db=db.value, decode_responses=False))

这里直接在函数名后用[T: RedisCache]声明类型参数T并指定约束为RedisCache,替代了原有的TypeVar定义。

关于Mypy的错误说明

你遇到的PEP 695 type aliases are not yet supported错误,确实说明当前版本的Mypy对PEP 695的类型别名语法支持不完善,但这不代表它完全不支持Python 3.12的类型参数语法:

  • 函数内联的PEP 695类型参数声明(即上述示例的写法),在Mypy 1.5及以上版本已经支持。
  • 但PEP 695的type别名语法(比如你尝试的type CacheFactory[T] = Type[T]),Mypy的支持仍在开发中,暂时无法识别,因此会抛出错误。

若要使用Python 3.12新语法,优先采用函数内联的类型参数声明方式,避免使用PEP 695的类型别名写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:37:45