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

Contravariant TypeVars don't work in dataclasses #4421

Closed
LeeeeT opened this issue Jan 8, 2023 · 2 comments
Closed

Contravariant TypeVars don't work in dataclasses #4421

LeeeeT opened this issue Jan 8, 2023 · 2 comments
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 8, 2023

Describe the bug
I'm trying to create a generic dataclass with a contravariant type variable. But I'm getting an error when instantiating the class.

To Reproduce
Run pyright for the following code:

from typing import TypeVar, Generic
from dataclasses import dataclass

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

@dataclass
class MyDataclass(Generic[T_contra]):
    ...

MyDataclass[int]()  # error here
file.py:10:1 - error: Could not bind method "__new__" because "Type[MyDataclass[int]]" is not assignable to parameter "cls"
    Type "MyDataclass[int]" cannot be assigned to type "MyDataclass[T_contra@MyDataclass]"
      "MyDataclass[int]" is incompatible with "MyDataclass[T_contra@MyDataclass]"
        TypeVar "T_contra@MyDataclass" is contravariant
          "object*" is incompatible with "int" (reportGeneralTypeIssues)

Expected behavior
No errors.

Additional context
pyright: 1.1.287

@erictraut
Copy link
Collaborator

Thanks for the bug report. This isn't limited to just a dataclass. It occurs with any generic class that defines a __new__ method with a cls: type[Self] parameter.

from typing import Self, TypeVar, Generic

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

class MyClass(Generic[T_contra]):
    def __new__(cls: type[Self]) -> Self:
        ...

MyClass[int]() # Error

This will be fixed in the next release.

erictraut pushed a commit that referenced this issue Jan 8, 2023
…ass used a contravariant type variable and defined a `__new__` method that uses `cls: type[Self]` as a parameter. This addresses #4421.
@erictraut erictraut added bug Something isn't working addressed in next version Issue is fixed and will appear in next published version labels Jan 8, 2023
@erictraut
Copy link
Collaborator

This is addressed in pyright 1.1.288, 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