[英]Type hint for NumPy ndarray dtype?
我想一个功能包括NumPy的一种暗示ndarray
“与以S一起dtype
。
例如,对于列表,您可以执行以下操作...
def foo(bar: List[int]):
...
...为了给出类型提示, bar
必须是由int
组成的list
。
不幸的是,这种语法会引发 NumPy ndarray
异常:
def foo(bar: np.ndarray[np.bool]):
...
> np.ndarray[np.bool]) (...) TypeError: 'type' object is not subscriptable
是否有可能给dtype
的特异类型提示np.ndarray
?
您可以查看nptyping :
from nptyping import NDArray, Bool
def foo(bar: NDArray[Bool]):
...
或者你可以只使用字符串作为类型提示:
def foo(bar: 'np.ndarray[np.bool]'):
...
查看 数据科学类型包。
pip install data-science-types
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")
像平常一样使用 mypy。
$ mypy program.py
与函数参数一起使用
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
据我所知,目前还不可能在函数签名的 numpy 数组类型提示中指定dtype
。 计划在未来的某个时间点实施。 有关当前开发状态的更多详细信息,请参阅numpy GitHub 问题 #7370和numpy-stubs GitHub 。
类型文档的一种非正式解决方案如下:
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)])))
我们一直在我的公司使用它,并制作了一个 MyPy 检查器来实际检查形状是否有效(我们应该在某个时候发布)。
唯一的事情是它不会让 PyCharm 高兴(即你仍然会收到令人讨厌的警告线):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.