pyright
pyright copied to clipboard
Pyright fails to bind contravariant generic type in generic function
Pyright is unable to infer the type of bound type variable in generic function under certain conditions.
from collections.abc import Callable
from typing import TypeVar, Generic
T = TypeVar('T', contravariant=True)
class C(Generic[T]):
pass
def f[A](c: Callable[[A], None], v: A):
pass
def g[A](c: C[A]):
pass
def h(c: C[int]):
f(g, c)
file.py:16:10 - error: Argument of type "C[int]" cannot be assigned to parameter "v" of type "A@f" in function "f"
"C[int]" is incompatible with "C[A@g]"
Type parameter "T@C" is contravariant, but "int" is not a supertype of "A@g"
"object*" is incompatible with "int"
A@g
should be bound to int
, A@f
should be bound to C[int]
and no errors should be produced.
The bug is somehow related to the fact that T
is contravariant. If I make it covariant or invariant, it does work fine.
Thanks for the bug report. I'm able to repro the problem, and I agree it's a bug. I'll investigate further.
This is addressed in pyright 1.1.366.