python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.55k stars 2.84k forks source link

variance inferred oincorrectly when class has both a covariant and contravariant generic and instance attribute is assigned without a type annotation #18147

Open DetachHead opened 1 week ago

DetachHead commented 1 week ago
from typing import Never

class Foo[in_T, out_T]:
    def __init__(self, *, value: out_T):
        a: Foo[Never, object] = self # error (incorrect)
        self.__a = value
        reveal_type(self.__a) # out_T`2

    def asdf(self, value: in_T) -> out_T: ...

class Bar[in_T, out_T]:
    def __init__(self, *, value: out_T):
        a: Bar[Never, object] = self # no error (correct)
        self.__a: out_T = value
        reveal_type(self.__a) # out_T`2

    def asdf(self, value: in_T) -> out_T: ...

playground

(originally raised in #18118 but i messed up the minimal repro)