Skip to content

Commit

Permalink
[PEP 695] Fix covariance of frozen dataclasses (#17783)
Browse files Browse the repository at this point in the history
Fix this conformance test:
```
@DataClass(frozen=True)
class ShouldBeCovariant4[T]:
    x: T

vo4_1: ShouldBeCovariant4[float] = ShouldBeCovariant4[int](1)  # OK
vo4_2: ShouldBeCovariant4[int] = ShouldBeCovariant4[float](1)  # E
```
Link:

https://github.com/python/typing/blob/main/conformance/tests/generics_variance_inference.py#L66
  • Loading branch information
JukkaL authored Sep 18, 2024
1 parent fce14a0 commit 9d7a042
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -2004,7 +2004,8 @@ def infer_variance(info: TypeInfo, i: int) -> bool:
tvar = info.defn.type_vars[i]
self_type = fill_typevars(info)
for member in all_non_object_members(info):
if member in ("__init__", "__new__"):
# __mypy-replace is an implementation detail of the dataclass plugin
if member in ("__init__", "__new__", "__mypy-replace"):
continue

if isinstance(self_type, TupleType):
Expand Down
19 changes: 19 additions & 0 deletions test-data/unit/check-python312.test
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,25 @@ if int():
if int():
f = e

[case testPEP695InferVarianceInFrozenDataclass]
# flags: --enable-incomplete-feature=NewGenericSyntax
from dataclasses import dataclass

@dataclass(frozen=True)
class Covariant[T]:
x: T

cov1: Covariant[float] = Covariant[int](1)
cov2: Covariant[int] = Covariant[float](1) # E: Incompatible types in assignment (expression has type "Covariant[float]", variable has type "Covariant[int]")

@dataclass(frozen=True)
class Invariant[T]:
x: list[T]

inv1: Invariant[float] = Invariant[int]([1]) # E: Incompatible types in assignment (expression has type "Invariant[int]", variable has type "Invariant[float]")
inv2: Invariant[int] = Invariant[float]([1]) # E: Incompatible types in assignment (expression has type "Invariant[float]", variable has type "Invariant[int]")
[builtins fixtures/tuple.pyi]

[case testPEP695InferVarianceCalculateOnDemand]
# flags: --enable-incomplete-feature=NewGenericSyntax

Expand Down

0 comments on commit 9d7a042

Please sign in to comment.