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

如何创建可关联类型与正数的Annotated类型别名Array?

正确创建关联类型与长度的Array类型

要实现你想要的Array[T, N](关联元素类型T和长度N的注解类型),核心是把Array定义为泛型类型别名——只有泛型类型别名才支持下标操作([类型, 长度])。以下是两种可行方案:

方案一:Python 3.12+ 原生泛型类型别名(推荐)

Python 3.12开始支持用type关键字直接定义泛型类型别名,写法简洁直观:

from typing import Annotated, TypeVar

# 定义类型变量:T表示元素类型,N表示长度(约束为int类型)
T = TypeVar("T")
N = TypeVar("N", bound=int)

# 定义泛型类型别名Array,接受两个参数并返回Annotated类型
type Array[T, N] = Annotated[tuple[T, ...], N]

# 使用示例
class MyIp:
    ip: Array[float, 4]  # 等价于Annotated[tuple[float, ...], 4]

方案二:兼容Python 3.11及以下版本

如果需要兼容旧版本Python,可以通过Generic类和__class_getitem__方法模拟泛型下标行为:

from typing import Annotated, TypeVar, Generic

T = TypeVar("T")
N = TypeVar("N", bound=int)

class Array(Generic[T, N]):
    @classmethod
    def __class_getitem__(cls, args):
        # 解析下标传入的元素类型和长度参数
        elem_type, length = args
        # 返回对应的Annotated类型
        return Annotated[tuple[elem_type, ...], length]

# 使用示例
class MyIp:
    ip: Array[float, 4]  # 同样等价于Annotated[tuple[float, ...], 4]

错误原因说明

你之前的写法type Array = Annotated[tuple[T, ...], int]只是普通类型别名,并非泛型类型别名,所以无法通过Array[int, 4]下标调用,这就是报错TypeError: Only generic type aliases are subscriptable的原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:07:05