NumPy ndarray dtype的类型提示?

dan*_*451 7 python numpy type-hinting python-3.6

我想要一个函数在NumPy ndarray的旁边加上类型提示dtype

例如,使用列表,可以执行以下操作...

def foo(bar: List[int]):
   ...
Run Code Online (Sandbox Code Playgroud)

...以给出bar必须list由组成的类型提示int

不幸的是,此语法抛出NumPy异常ndarray

def foo(bar: np.ndarray[np.bool]):
   ...

> np.ndarray[np.bool]) (...) TypeError: 'type' object is not subscriptable
Run Code Online (Sandbox Code Playgroud)

是否可以提供dtype特定于类型的提示np.ndarray

kev*_*und 16

查看数据科学类型包。

pip install data-science-types
Run Code Online (Sandbox Code Playgroud)

MyPy 现在可以访问 Numpy、Pandas 和 Matplotlib 存根。允许以下场景:

# program.py

import numpy as np
import pandas as pd

arr1: np.ndarray[np.int64] = np.array([3, 7, 39, -3])  # OK
arr2: np.ndarray[np.int32] = np.array([3, 7, 39, -3])  # Type error

df: pd.DataFrame = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) # OK
df1: pd.DataFrame = pd.Series([1,2,3]) # error: Incompatible types in assignment (expression has type "Series[int]", variable has type "DataFrame")
Run Code Online (Sandbox Code Playgroud)

像平常一样使用 mypy。

$ mypy program.py
Run Code Online (Sandbox Code Playgroud)

与函数参数一起使用

def f(df: pd.DataFrame):
    return df.head()

if __name__ == "__main__":
    x = pd.DataFrame({'col1': [1, 2, 3, 4, 5, 6]})
    print(f(x))

$ mypy program.py
> Success: no issues found in 1 source file
Run Code Online (Sandbox Code Playgroud)

  • 来自 data-science-types github: ⚠️ 这个项目已基本停止开发 ⚠️ pandas 团队和 numpy 团队都在将类型存根集成到他们的代码库中,我们看不到与他们竞争的意义。 (7认同)

Pet*_*ter 10

类型文档的一种非正式解决方案如下:

from typing import TypeVar, Generic, Tuple, Union, Optional
import numpy as np

Shape = TypeVar("Shape")
DType = TypeVar("DType")


class Array(np.ndarray, Generic[Shape, DType]):
    """
    Use this to type-annotate numpy arrays, e.g.

        def transform_image(image: Array['H,W,3', np.uint8], ...):
            ...

    """
    pass


def func(arr: Array['N,2', int]):
    return arr*2


print(func(arr = np.array([(1, 2), (3, 4)])))

Run Code Online (Sandbox Code Playgroud)

我们一直在我的公司使用它,并制作了一个 MyPy 检查器来实际检查形状是否有效(我们应该在某个时候发布)。

唯一的问题是它不会让 PyC​​harm 高兴(即你仍然会收到令人讨厌的警告线):

在此输入图像描述


R H*_*R H 9

您可以查看nptyping

from nptyping import Array

def foo(bar: Array[np.bool]):
   ...
Run Code Online (Sandbox Code Playgroud)

或者您可以只使用字符串作为类型提示:

def foo(bar: 'np.ndarray[np.bool]'):
   ...
Run Code Online (Sandbox Code Playgroud)

  • 请注意,从 1.20 开始,现在可以通过“numpy.typing.NDArray”访问,而不是外部包:https://numpy.org/devdocs/reference/typing.html (12认同)
  • 它用作文档,并没有真正做太多事情(除非您出于某种原因开始使用检查来解析它们)。一些编辑器(例如 PyCharm)足够聪明,可以看看它们是否能够理解文本类型提示。有时,除了使用文本类型提示之外,您别无选择。例如,当暗示方法的参数与包含该方法的类具有相同类型时。 (3认同)

Xuk*_*rao 5

据我所知,尚无法dtype在numpy数组类型提示中指定函数签名。计划在将来的某个时候实施。有关当前开发状态​​的更多详细信息,请参见numpy GitHub第7370期numpy-stubs GitHub