PyCharm 和类型提示警告
PyCharm and Type Hinting Warning
我在 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
抱怨上面代码段的最后一行,信号:
Expected type 'List[List[int]], got 'List[Iterable]' instead...
这很令人惊讶,因为:
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]))
我在 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
抱怨上面代码段的最后一行,信号:
Expected type 'List[List[int]], got 'List[Iterable]' instead...
这很令人惊讶,因为:
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]))