Open
Description
# 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)
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)