Search code examples
pythonpycharmpython-typing

proper type hint for __getitem__()


The method __getitem__() for a sequence (such as a list) can return a single item, or a sequence of items. For example, given the function decoration below:

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

Example usage:

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

I believe Union[Product, Generator[Product, None, None]] to be correct, but PyCharm flags this as improper. Am I misusing the typing library, or is this a PyCharm issue?

Thanks!


Solution

  • The correct type hint for __getitem__() is Union[Product, Sequence[Product, None, None]].

    The only place this seems to be documented in the docs is on the 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.

    Further discussion: I was expecting a generator when using a slice with a sequence while being iterated over because they are more memory efficient. But now it is obvious to me that this would result in constantly having to do: l_2 = list(l_1[2:]), which would be annoying.