17370845950

如何为带尺寸注解的数组类型创建别名

本文介绍一种通过自定义 `__class_getitem__` 实现类型别名 `array[t, n]` 的技巧,使其在类型提示中等价于 `annotated[t, n]`,适用于文档化和静态类型检查场景,但需注意其运行时行为限制。

在 Python 类型系统中,直接使用 type Array = Annotated[tuple[T, ...], int] 会报错,因为 Annotated 不支持在类型别名中以泛型方式参数化(TypeError: Only generic type aliases are subscriptable)。根本原因在于:类型别名(type 语句)仅支持泛型类型构造器(如 list[T]、dict[K, V]),而 Annotated 本身不是泛型类型,其参数必须在运行时静态确定,无法延迟绑定类型变量 T 和整数字面量 N

不过,若目标仅为提升代码可读性与类型提示的表达力(例如标注“长度为 4 的浮点数数组”),可借助类的 __class_getitem__ 魔术方法实现轻量级伪泛型别名:

from typing import Annotated, TypeVar, Tuple

T = TypeVar("T")

class Array:
    def __class_getitem__(cls, params):
        if not isinstance(params, tuple) or len(params) != 2:
            raise TypeError("Array requires exactly two arguments: Array[dtype, size]")
        dtype, size = params
        # 返回 Annotated[dtype, size],供类型检查器识别
        return Annotated[dtype, size]

# 使用示例
class MyIp:
    ip: Array[float, 4]  # 等价于 Annotated[float, 4]
    ports: Array[int, 2]  # 等价于 Annotated[int, 2]

优势

  • 语法简洁直观,Array[float, 4] 比 Annotated[float, 4] 更具语义;
  • 兼容主流类型检查器(如 mypy、pyright),能正确解析并校验类型注解;
  • 无需引入第三方库,纯标准库方案。

⚠️ 关键限制(务必注意)

  • Array[float, 4] 在类定义时立即求值,MyIp.__annotations__['ip'] 实际存储的是 Annotated[float, 4],而非 Array[float, 4];
  • typing.get_type_hints(MyIp) 默认会剥离 Annotated 元数据,返回 {'ip': float} —— 若需保留尺寸信息,须显式传入 include_extras=True:
    from typing import get_type_hints
    hints = get_type_hints(MyIp, include_extras=True)
    # → {'ip': typing.Annotated[float, 4]}
  • 此方案不提供运行时数组长度验证(如 len(ip) == 4),纯属类型层面约定,实际数据仍需手动校验。

? 进阶建议
若需更强的运行时保障,可结合 typing_extensions.TypedDict(固定键名)、numpy.typing.NDArray(数值计算场景)或 Pydantic v2 的 Annotated + Field(..., min_length=4) 实现结构化约束。但对于轻量级类型文档需求,Array 类方案已足够清晰、低侵入且符合 PEP 563/593 规范。

总之,这是一种务实的“类型即文档”实践——用最小代价换取最大可读性,但须始终清醒区分:类型提示 ≠ 运行时契约