Skip to content

Variance bug on TypeVar with value restriction #11379

@JelleZijlstra

Description

@JelleZijlstra
from typing import TypeVar, Union, Generic

T1 = TypeVar("T1", int, str, covariant=True)
T2 = TypeVar("T2", int, str)

class X1(Generic[T1]):
    def f(self) -> T1: ...
class X2(Generic[T2]):
    def f(self) -> T2: ...

def f1(x: X1[int]) -> None: ...
def f2(x: X2[int]) -> None: ...

f1(X1[int]())
f1(X1[bool]())

f2(X2[int]())
f2(X2[bool]())

https://mypy-play.net/?mypy=latest&python=3.10&gist=5a4f16dd13bd4b18a7c2323ba464f627

Mypy allows this without errors, but pyright shows an error on the last line and I think it's right: T2 is invariant, so we shouldn't allow bool there:

Argument of type "X2[bool]" cannot be assigned to parameter "x" of type "X2[int]" in function "f2"
  TypeVar "T2@X2" is invariant
    "bool" is incompatible with "int"

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions