具有数组的函数的PyCharm getitem警告 [英] PyCharm getitem warning for functions with arrays

查看:6126
本文介绍了具有数组的函数的PyCharm getitem警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从PyCharm收到代码检查警告。我理解逻辑,但我不清楚修复它的适当方法。假设我有以下示例函数:

I'm getting code inspection warnings from PyCharm. I understand the logic, but I'm not clear on the appropriate way to fix it. Say I have the following example function:

def get_ydata(xdata):
    ydata = xdata ** 2
    for i in range(len(ydata)):
        print ydata[i]
return ydata

我收到2条警告:

>> Expected type 'Sized', got 'int' instead (at line 3)
>> Class 'int' does not define '__getitem__', so the '[]' operator cannot be used on its instances (at line 4)

该函数的目的当然是解析一个numpy数组的xdata。但PyCharm不知道,所以没有任何进一步的指示假设xdata(因此也是ydata)是一个整数。

The purpose of the function is of course to parse a numpy array of xdata. But PyCharm doesn't know that, so without any further indication assumes that xdata (and therefore also ydata) is an integer.

解决此警告的适当方法是什么?我应该注意,添加类型检查行将修复警告。这是最佳解决方案吗?例如:

What is the appropriate way to address this warning? I should note that adding a type checking line will fix the warning. Is that the optimal solution? For example:

if not type(ydata) is np.ndarray:
    ydata = np.array(ydata)

最后,添加Sphinx文档字符串信息似乎对警告没有任何影响。 (当xdata指定为str时,警告仍会看到'int')。同样迭代y直接导致以下错误:

Lastly, adding Sphinx docstring information does not seem to have any effect on the warnings. (warning still sees 'int' when xdata is specified as str). Also iterating over y directly results in the following error:

for y in ydata:
...
>> Expected 'collections.Iterable', got 'int' instead


推荐答案

Pycharm的类型提示功能可能是使用。

Pycharm has type hinting features that may be of use.

例如,在这种情况下,以下代码会使错误消失:

For example in this case, the following code makes the errors go away:

import numpy as np

def get_ydata(xdata):
    ydata = xdata ** 2  # type: np.ndarray
    for i in range(len(ydata)):
        print(ydata[i])
    return ydata

这篇关于具有数组的函数的PyCharm getitem警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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