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

Invariant class is incompatible with its base class in contravariant context #4517

Closed
LeeeeT opened this issue Jan 24, 2023 · 2 comments
Closed
Labels
addressed in next version Issue is fixed and will appear in next published version bug Something isn't working

Comments

@LeeeeT
Copy link

LeeeeT commented Jan 24, 2023

The following code gives me an error:

from typing import TypeVar, Generic

T = TypeVar("T")
T_contra = TypeVar("T_contra", contravariant=True)

class Contra(Generic[T_contra]): ...

class Foo(Generic[T]): ...

class Bar(Foo[T]): ...

v: Contra[Bar[int]] = Contra[Foo[int]]()  # error here
test.py:12:23 - error: Expression of type "Contra[Foo[int]]" cannot be assigned to declared type "Contra[Bar[int]]"
    "Contra[Foo[int]]" is incompatible with "Contra[Bar[int]]"
      TypeVar "T_contra@Contra" is contravariant
        "Bar[int]" is incompatible with "Foo[int]"
          TypeVar "T@Foo" is invariant
            Type "int" cannot be assigned to type "T@Bar"

Pyright says that Bar[int] is incompatible with Foo[int], which is obviously incorrect. If I extract Bar[int] and Foo[int] from Contra pyright actually allows assigning Bar[int] to Foo[int]:

v: Foo[int] = Bar[int]()  # no errors

So I think something is going wrong specifically in contravariant context which makes pyright unable to bind int to T@Bar.

Additional context
pyright 1.1.290

@erictraut erictraut added the bug Something isn't working label Jan 24, 2023
erictraut pushed a commit that referenced this issue Jan 24, 2023
…s with an invariant type parameter is used in specialized form as a type argument for a class with a contravariant type parameter. This addresses #4517.
@erictraut
Copy link
Collaborator

Thanks for the bug report. This will be fixed in the next release.

@erictraut erictraut added the addressed in next version Issue is fixed and will appear in next published version label Jan 24, 2023
@erictraut
Copy link
Collaborator

This is included in pyright 1.1.291, which I just published. It will also be included in a future release of pylance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
addressed in next version Issue is fixed and will appear in next published version bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants