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 for incorrect variance on parameter with generic type #13232

Open
KotlinIsland opened this issue Jul 25, 2022 · 0 comments
Open
Labels
bug mypy got something wrong topic-type-variables

Comments

@KotlinIsland
Copy link
Contributor

from typing import TypeVar, Generic

T_in = TypeVar("T_in", contravariant=True)
T_out = TypeVar("T_out", covariant=True)

class AOut(Generic[T_out]): ...
class AIn(Generic[T_in]): ...

class BOut(Generic[T_out]):
    def f(self, a_out: AOut[T_out]) -> None: ...  # no error
    
class BIn(Generic[T_in]):
    def f(self, a_out: AIn[T_in]) -> None: ...  # no error

Mypy in real life

from typing import TypeVar, Generic, Callable

T_in = TypeVar("T_in", contravariant=True)
T_out = TypeVar("T_out", covariant=True)

class AOut(Generic[T_out]):
    T: T_out
    def f(self, fn: Callable[[], T_out]) -> None:
        self.t = fn()
    
    def dump(self) -> T_out:
        return self.t
class AIn(Generic[T_in]):
    t: T_in
    def load(self, t: T_in) -> None:
        self.t = t
    def f(self, fn: Callable[[T_in], object]) -> None:
        fn(self.t)
    

o1: AOut[int]
o: AOut[object] = o1

o.f(lambda: "")
o1.dump() + 1  # runtime error

i1: AIn[object]
i: AIn[int] = i1

i1.load("")
i.f(lambda x: x + 1)  # runtime error

related: #734, #8191

@KotlinIsland KotlinIsland added the bug mypy got something wrong label Jul 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-type-variables
Projects
None yet
Development

No branches or pull requests

2 participants