PyCharm和类型暗示警告

2024-04-25 07:20:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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]。但我不能百分之百肯定。你知道吗

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


Tags: importself列表returnmyasnpproperty