【问题标题】:Numpy type hints in Python (PEP 484)Python 中的 Numpy 类型提示 (PEP 484)
【发布时间】:2019-03-21 05:18:06
【问题描述】:

我想将类型提示添加到将 numpy 数组作为输入并返回字符串的方法。这个 numpy 数组包含浮点数,所以我尝试了:

import numpy as np
def foo(array: np.ndarray[np.float64]) -> str:

但由于TypeError: 'type' object is not subscriptable,它不起作用。

我找到了this,但无法关注讨论!

【问题讨论】:

标签: python numpy pep


【解决方案1】:

查看nptyping。它为 numpy 数组提供类型提示。

在你的情况下,你最终会得到:

from nptyping import NDArray, Float64

def foo(array: NDArray[Float64]) -> str:
    ...

您也可以检查您的实例:

import numpy as np
from nptyping import NDArray, Float64

arr = np.array([[1.0, 2.0],
                [3.0, 4.0],
                [5.0, 6.0]])

isinstance(arr, NDArray[(3, 2), Float64])  # True.

# Or if you don't want to check the dimensions and their sizes:
isinstance(arr, NDArray[Float64])  # Also True.

【讨论】:

  • 项目状态?
  • 它还活着。不过最近没有任何功能请求或错误报告。
  • 如果还可以看到ndarray 方法(例如argmaxshape、..
  • 在这个项目中支持/连接到 mypy 会很棒,也就是说,如果我写 arr: NDArray[(3, 1), Any] = np.array([[1.0, 2.0], [3.0, 4.0]]) 我会通过 mypy 得到类型错误。
  • 同样,PyCharm 无法将 NDArray 连接到 np.ndarray
猜你喜欢
  • 2018-03-01
  • 2023-03-31
  • 2019-10-07
  • 2018-11-05
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 2016-10-26
相关资源
最近更新 更多