Mypy: Definition of "__iter__" in "ItemsView" is incompatible with definition "Sequence"

Created on 29 Nov 2018  路  2Comments  路  Source: python/mypy

Hi there !

Trying to annotate a class inheriting from both a sequence and an items view will raise an error, although I believe both definitions are compatible in the following case:

from typing import *

K = TypeVar('K')
V = TypeVar('V')

class OrderedItemsView(Generic[K, V], ItemsView[K, V], Sequence[Tuple[K, V]]):
  def __iter__(self) -> Iterator[Tuple[K, V]]:
    return iter([])

This example raises:

test.py:7: error: Definition of "__iter__" in base class "ItemsView" is incompatible with definition in base class "Sequence"

although, for the two base classes, I believe __iter__ to be defined as Iterator[Tuple[K, V]].

bug false-positive priority-0-high

Most helpful comment

Confirmed on master. Here's a more self-contained repro:

from typing import TypeVar, Generic, Tuple

K = TypeVar('K')
V = TypeVar('V')
T = TypeVar('T')

class ItemsView(Generic[K, V]):
    def __iter__(self) -> Tuple[K, V]: ...

class Sequence(Generic[T]):
    def __iter__(self) -> T: ...

class OrderedItemsView(ItemsView[K, V], Sequence[Tuple[K, V]]):
    def __iter__(self) -> Tuple[K, V]: ...

Gives me .../iv2.py:13: error: Definition of "__iter__" in base class "ItemsView" is incompatible with definition in base class "Sequence".

Interestingly, the method that produces this error (check_compatibility in checker.py) has a "# TODO: What if some classes are generic?".

All 2 comments

Confirmed on master. Here's a more self-contained repro:

from typing import TypeVar, Generic, Tuple

K = TypeVar('K')
V = TypeVar('V')
T = TypeVar('T')

class ItemsView(Generic[K, V]):
    def __iter__(self) -> Tuple[K, V]: ...

class Sequence(Generic[T]):
    def __iter__(self) -> T: ...

class OrderedItemsView(ItemsView[K, V], Sequence[Tuple[K, V]]):
    def __iter__(self) -> Tuple[K, V]: ...

Gives me .../iv2.py:13: error: Definition of "__iter__" in base class "ItemsView" is incompatible with definition in base class "Sequence".

Interestingly, the method that produces this error (check_compatibility in checker.py) has a "# TODO: What if some classes are generic?".

I think this is important to fix, otherwise multiple inheritance of generic classes is problematic.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JukkaL picture JukkaL  路  41Comments

dmoisset picture dmoisset  路  49Comments

datnamer picture datnamer  路  49Comments

glyph picture glyph  路  26Comments

snakescott picture snakescott  路  27Comments