Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyCharm和类型提示警告_Python_Python 3.x_Pycharm_Iterable_Type Hinting - Fatal编程技术网

Python PyCharm和类型提示警告

Python PyCharm和类型提示警告,python,python-3.x,pycharm,iterable,type-hinting,Python,Python 3.x,Pycharm,Iterable,Type Hinting,我在类上定义了以下属性: import numpy as np import typing as tp @property def my_property(self) -> tp.List[tp.List[int]]: if not self.can_implement_my_property: return list() # calculations to produce the vector v... indices = list()

我在
上定义了以下
属性

import numpy as np
import typing as tp

@property
def my_property(self) -> tp.List[tp.List[int]]:

    if not self.can_implement_my_property:
        return list()

    # calculations to produce the vector v...

    indices = list()

    for u in np.unique(v):
        indices.append(np.ravel(np.argwhere(v == u)).tolist())

    return sorted(indices, key=lambda x: (-len(x), x[0]))
PyCharm
正在抱怨上面代码段的最后一行,很明显:

应为“List[List[int]”类型,改为“List[Iterable]”

这很令人惊讶,因为:

  • 索引
    声明为
    列表
  • ravel
    确保将
    argwhere
    的匹配值转换为一维
    Numpy
    向量
  • tolist
    将一维
    Numpy
    向量转换为列表
  • 获得的列表将附加到
    索引
    列表中
由于IDE端对类型暗示的错误处理,这可能是误报,因为
List[int]
实际上是一个
Iterable
。。。因此,
List[List[int]]=List[Iterable]
。但我不能百分之百肯定


关于这个问题有什么线索吗?如何确保将返回值强制为预期类型?

多亏了@mgilson comment,以下是我为解决此问题而实施的解决方案:

indices = list()

for u in np.unique(v):
    indices.append(list(it.chain.from_iterable(np.argwhere(v == u))))

return sorted(indices, key=lambda x: (-len(x), x[0]))

这里有一些东西。。。我不清楚
.tolist()
如何返回
List[int]
——我想应该是
List[Any]
,因为numpy数组目前不是
泛型的
(类型系统中也没有任何方法处理维度——你不知道它是
List[int]
还是
List[int]
). 您可以使用
typing.cast
向类型检查器断言
。tolist
实际上返回了一个
列表[int]
。这应该适用于
mypy
(取决于您使用的存根)。我不知道皮查姆。