pyright icon indicating copy to clipboard operation
pyright copied to clipboard

Pyright fails to bind contravariant generic type in generic function

Open LeeeeT opened this issue 1 year ago • 1 comments

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.

LeeeeT avatar Feb 06 '24 02:02 LeeeeT

Thanks for the bug report. I'm able to repro the problem, and I agree it's a bug. I'll investigate further.

erictraut avatar Feb 06 '24 03:02 erictraut

This is addressed in pyright 1.1.366.

erictraut avatar Jun 05 '24 04:06 erictraut