Python中的Numpy类型提示(PEP 484) [英] Numpy type hints in Python (PEP 484)

查看:240
本文介绍了Python中的Numpy类型提示(PEP 484)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to add type hints to a method that takes a numpy array as an input, and returns a string. This numpy array contains floats so I tried:

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

但是由于TypeError: 'type' object is not subscriptable而无法使用.

我发现了,但是无法按照讨论进行!

I found this but could not follow the discussions!

推荐答案

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

Check out nptyping. It offers type hints for numpy arrays.

以您的情况而言,您最终会得到:

In your case, you would end up with:

import numpy as np
from nptyping import Array

def foo(array: Array[np.float64]) -> str:
    ...

您也可以检查实例:

arr = np.array([[1.0, 2.0],
                [3.0, 4.0],
                [5.0, 6.0]])
isinstance(arr, Array[np.float64, 3, 2])  # True

这篇关于Python中的Numpy类型提示(PEP 484)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆