Skip to content

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

Open
@DetachHead

Description

@DetachHead
# 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions