PyCharm和类型提示警告

时间:2018-12-30 02:49:20

标签: python python-3.x pycharm iterable type-hinting

我在property上定义了以下class

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]” ...

这很令人惊讶,因为:

  • indices被声明为list
  • ravel确保将argwhere的匹配值转换为一维Numpy向量
  • tolist将一维Numpy矢量转换为列表
  • 获得的列表将附加到indices列表中

由于在IDE端对类型提示的处理不正确,这可能是误报,因为List[int]实际上是Iterable ...,因此也是List[List[int]] = List[Iterable]。但是我不能百分百确定。

有关此问题的任何线索吗?如何确保将返回值强制为期望的类型?

1 个答案:

答案 0 :(得分:0)

感谢@mgilson评论,这是我为解决此问题而实施的解决方案:

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