__getitem__() 的正确类型提示

han*_*nap 6 python type-hinting pycharm

序列(例如列表)的方法__getitem__()可以返回单个项目或项目序列。例如,给出下面的函数装饰:

def __getitem__(self, index) -> Union[Product, Generator[Product, None, None]]:
    return super(Products, self).__getitem__(index)
Run Code Online (Sandbox Code Playgroud)

用法示例:

i1 = 34
for product in products[i1:]:
    print(product.name)
Run Code Online (Sandbox Code Playgroud)

我相信Union[Product, Generator[Product, None, None]]这是正确的,但 PyCharm 将此标记为不正确。我是否滥用了类型库,或者这是 PyCharm 问题?

谢谢!

han*_*nap 3

正确的类型提示__getitem__()Union[Product, Sequence[Product, None, None]].

文档中似乎记录的唯一位置是数据模型页面,其中指出:“当用作表达式时,切片是相同类型的序列”。注意:类似序列的类型(例如 List)也应该可以工作,请参阅打字

进一步讨论:在迭代时使用带有序列的切片时,我期望生成器,因为它们的内存效率更高。但现在对我来说很明显,这会导致必须不断地执行:l_2 = list(l_1[2:]),这会很烦人。