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

如何在Python中实现类似C++非类型模板参数的非类型TypeVar

在Python中实现类似C++ template<int N>的类型提示

要实现你想要的基于具体整数值的类型提示效果,核心是用**字面量类型(Literal)**约束类型变量,而非普通TypeVar。以下是具体方案:

核心思路

  • 导入Literal类型,让类型检查器识别具体整数值,而非泛泛的int类型
  • 定义绑定到Literal[int]的TypeVar,确保类型变量只能被具体整数字面量填充
  • 调整类和方法的类型注解,让类型检查器能正确推断实例的参数约束

修改后的代码示例

from typing import TypeVar, Generic, Literal
import numpy as np
from numpy.typing import NDArray, DTypeLike

# 绑定到整数字面量的类型变量
T = TypeVar("T", bound=Literal[int])
V = TypeVar("V", bound=Literal[int])

class Foo(Generic[T, V]):
    def __init__(self, t: T, v: V) -> None:
        self.t, self.v = t, v
    
    def __call__(self, x: NDArray[tuple[T, V], DTypeLike[np.float_]]) -> NDArray[tuple[T, V], DTypeLike[np.float_]]:
        return x

# 使用示例
foo = Foo(3, 2)  # 类型检查器会推断为 Foo[Literal[3], Literal[2]]
y = foo(np.zeros((3, 2)))  # 参数会被提示为 NDArray[tuple[Literal[3], Literal[2]], np.dtype[np.float_]]

关键细节

  • bound=Literal[int]限制T和V只能是具体整数字面量(如3、2),而非int类型本身,完美模拟C++模板中template<int N>的数值参数效果
  • 使用numpy官方的NDArray和DTypeLike类型(来自numpy.typing)能获得更准确的类型提示,需确保numpy版本≥1.21
  • 实例化Foo时,类型检查器会自动捕获传入的具体数值,后续调用__call__方法时会严格校验输入数组的形状

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 06:37:06