(🐞) No error for incorrect variance on parameter with generic type
Open
Nobody has claimed this yet.
bug
topic-type-variables
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run mypy on the two reproductions in the issue and confirm that the invalid variance uses produce no errors. Trace the generic variance-checking entry point and add a regression test covering both covariant and contravariant cases; done means mypy reports the expected errors without breaking valid variance usage.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100