mypy icon indicating copy to clipboard operation
mypy copied to clipboard

no error on `TypeVar` with explicitly declared variance when the generic is used in another type with a different variance

Open DetachHead opened this issue 1 year ago • 0 comments

# mypy: enable-incomplete-feature=NewGenericSyntax
# mypy: disable-error-code=empty-body

from typing import Generic, TypeVar

class Contravariant[T]:
    def fn(self, value: T) -> None:
        ...

class Foo[T]:
    def fn(self) -> Contravariant[T]: ...

def call_foo_with_string(foo: Foo[object]) -> None:
    foo.fn().fn("")

foo_number = Foo[int]()
call_foo_with_string(foo_number) # correct error: Argument 1 to "call_foo_with_string" has incompatible type "Foo[int]"; expected "Foo[object]"


out_T = TypeVar('out_T', covariant=True)
class Bar(Generic[out_T]):
    def fn(self) -> Contravariant[out_T]: ...

def call_bar_with_string(bar: Bar[object]) -> None:
    bar.fn().fn("")

bar_number = Bar[int]()
call_bar_with_string(bar_number) # no error (incorrect)

playground

in this example, the variance rules are inverted when the generic is passed to another class where it becomes contravariant (as in, the generic must now only be used in an output position)

DetachHead avatar Oct 10 '24 03:10 DetachHead