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
- 获得的列表将附加到
列表中索引
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
(取决于您使用的存根)。我不知道皮查姆。