PyCharm 和类型提示警告



我在class上定义了以下property

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抱怨上面代码段的最后一行,信号:

预期类型为"列表[列表[int]],改为"列表[可迭代]"...

这是非常令人惊讶的,因为:

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

由于 IDE 端对类型提示的错误处理,这可能是误报,因为List[int]实际上是一个Iterable......因此List[List[int]] = List[Iterable].但我不能100%确定。

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

感谢@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]))

最新更新