小编Jor*_*mez的帖子

如何输入提示通用 numpy 数组?

有什么方法可以将 Numpy 数组键入为通用数组吗?

我目前正在使用 Numpy 1.23.5 和 Python 3.10,并且无法输入以下示例的提示。

import numpy as np
import numpy.typing as npt


E = TypeVar("E") # Should be bounded to a numpy type

def double_arr(arr: npt.NDArray[E]) -> npt.NDArray[E]:
    return arr * 2

Run Code Online (Sandbox Code Playgroud)

我的期望是什么

arr = np.array([1, 2, 3], dtype=np.int8)
double_arr(arr) # npt.NDAarray[np.int8]

arr = np.array([1, 2.3, 3], dtype=np.float32)
double_arr(arr) # npt.NDAarray[np.float32]
Run Code Online (Sandbox Code Playgroud)

但我最终遇到以下错误

arr: npt.NDArray[E]
                ^^^
Could not specialize type "NDArray[ScalarType@NDArray]"
  Type "E@double_arr" cannot be assigned to type "generic"
    "object*" is incompatible with "generic"
Run Code Online (Sandbox Code Playgroud)

如果我将 E …

python numpy type-hinting mypy python-typing

1
推荐指数
1
解决办法
3331
查看次数

标签 统计

mypy ×1

numpy ×1

python ×1

python-typing ×1

type-hinting ×1