Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
DetachHead opened this issue Oct 10, 2024 · 0 comments
Labels
bug mypy got something wrong

Comments

@DetachHead
Copy link
Contributor

DetachHead commented Oct 10, 2024

# 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 DetachHead added the bug mypy got something wrong label Oct 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

1 participant