__getitem__() 的正确类型提示

proper type hint for __getitem__()

序列(例如列表)的方法 __getitem__() 可以 return 单个项目或项目序列。例如,给定以下函数修饰:

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

用法示例:

i1 = 34
for product in products[i1:]:
    print(product.name)

我认为 Union[Product, Generator[Product, None, None]] 是正确的,但 PyCharm 认为这是不正确的。我是在滥用打字库,还是 PyCharm 问题?

谢谢!

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

文档中唯一记录的地方是 data model page which states: "When used as an expression, a slice is a sequence of the same type". Note: a sequence like type (such as List) should also work, see typing

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