简体   繁体   English

NumPy ndarray dtype 的类型提示?

[英]Type hint for NumPy ndarray dtype?

I would like a function to include a type hint for NumPy ndarray 's alongside with its dtype .我想一个功能包括NumPy的一种暗示ndarray “与以S一起dtype

With lists, for example, one could do the following...例如,对于列表,您可以执行以下操作...

def foo(bar: List[int]):
   ...

...in order to give a type hint that bar has to be list consisting of int 's. ...为了给出类型提示, bar必须是由int组成的list

Unfortunately, this syntax throws exceptions for NumPy ndarray :不幸的是,这种语法会引发 NumPy ndarray异常:

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

> np.ndarray[np.bool]) (...) TypeError: 'type' object is not subscriptable

Is it possible to give dtype -specific type hints for np.ndarray ?是否有可能给dtype的特异类型提示np.ndarray

You could check out nptyping :您可以查看nptyping

from nptyping import NDArray, Bool

def foo(bar: NDArray[Bool]):
   ...

Or you could just use strings for type hints:或者你可以只使用字符串作为类型提示:

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

Check out data-science-types package.查看 数据科学类型包。

pip install data-science-types

MyPy now has access to Numpy, Pandas, and Matplotlib stubs. MyPy 现在可以访问 Numpy、Pandas 和 Matplotlib 存根。 Allows scenarios like:允许以下场景:

# 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")

Use mypy like normal.像平常一样使用 mypy。

$ mypy program.py

Usage with function-parameters与函数参数一起使用

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

To the best of my knowledge it's not possible yet to specify dtype in numpy array type hints in function signatures.据我所知,目前还不可能在函数签名的 numpy 数组类型提示中指定dtype It is planned to be implemented at some point in the future.计划在未来的某个时间点实施。 See numpy GitHub issue #7370 and numpy-stubs GitHub for more details on the current development status.有关当前开发状态​​的更多详细信息,请参阅numpy GitHub 问题 #7370numpy-stubs GitHub

One informal solution for type documentation is the following:类型文档的一种非正式解决方案如下:

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)])))

We've been using this at my company and made a MyPy checker that actually checks that the shapes work out (which we should release at some point).我们一直在我的公司使用它,并制作了一个 MyPy 检查器来实际检查形状是否有效(我们应该在某个时候发布)。

Only thing is it doesn't make PyCharm happy (ie you still get the nasty warning lines):唯一的事情是它不会让 PyC​​harm 高兴(即你仍然会收到令人讨厌的警告线):

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM