mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Invariance not enforced for class-scoped TypeVar used in base class expression

Open erictraut opened this issue 3 years ago • 0 comments

Mypy does not detect the case where a covariant or contravariant class (i.e. a class that is parameterized by a class-scoped covariant or contravariant TypeVar) derives from an invariant class. This creates a type correctness hole as shown in the following code sample.

from typing import TypeVar

T = TypeVar("T", covariant=True)

class MyList(list[T]): pass

def append_float(y: MyList[float]):
    y.append(1.0)

x: MyList[int] = MyList([1, 2, 3])
append_float(x)

Pyright likewise did not previously catch this case. I just added the check here.

erictraut avatar Sep 23 '22 03:09 erictraut