Skip to content

Commit 9d7a042

Browse files
authored
[PEP 695] Fix covariance of frozen dataclasses (#17783)
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
1 parent fce14a0 commit 9d7a042

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

mypy/subtypes.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2004,7 +2004,8 @@ def infer_variance(info: TypeInfo, i: int) -> bool:
20042004
tvar = info.defn.type_vars[i]
20052005
self_type = fill_typevars(info)
20062006
for member in all_non_object_members(info):
2007-
if member in ("__init__", "__new__"):
2007+
# __mypy-replace is an implementation detail of the dataclass plugin
2008+
if member in ("__init__", "__new__", "__mypy-replace"):
20082009
continue
20092010

20102011
if isinstance(self_type, TupleType):

test-data/unit/check-python312.test

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,25 @@ if int():
249249
if int():
250250
f = e
251251

252+
[case testPEP695InferVarianceInFrozenDataclass]
253+
# flags: --enable-incomplete-feature=NewGenericSyntax
254+
from dataclasses import dataclass
255+
256+
@dataclass(frozen=True)
257+
class Covariant[T]:
258+
x: T
259+
260+
cov1: Covariant[float] = Covariant[int](1)
261+
cov2: Covariant[int] = Covariant[float](1) # E: Incompatible types in assignment (expression has type "Covariant[float]", variable has type "Covariant[int]")
262+
263+
@dataclass(frozen=True)
264+
class Invariant[T]:
265+
x: list[T]
266+
267+
inv1: Invariant[float] = Invariant[int]([1]) # E: Incompatible types in assignment (expression has type "Invariant[int]", variable has type "Invariant[float]")
268+
inv2: Invariant[int] = Invariant[float]([1]) # E: Incompatible types in assignment (expression has type "Invariant[float]", variable has type "Invariant[int]")
269+
[builtins fixtures/tuple.pyi]
270+
252271
[case testPEP695InferVarianceCalculateOnDemand]
253272
# flags: --enable-incomplete-feature=NewGenericSyntax
254273

0 commit comments

Comments
 (0)