Skip to content

Commit ce01710

Browse files
committed
Fix types of inherited attributes in generic dataclasses
Fixes #12633.
1 parent 07ea0f6 commit ce01710

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

mypy/plugins/dataclasses.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,8 @@ def deserialize(
101101
def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None:
102102
"""Expands type vars in the context of a subtype when an attribute is inherited
103103
from a generic super type."""
104-
if not isinstance(self.type, TypeVarType):
105-
return
106-
107-
self.type = map_type_from_supertype(self.type, sub_type, self.info)
104+
if self.type is not None:
105+
self.type = map_type_from_supertype(self.type, sub_type, self.info)
108106

109107

110108
class DataclassTransformer:

test-data/unit/check-dataclasses.test

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1568,3 +1568,35 @@ class B:
15681568
class Derived(A, B):
15691569
pass
15701570
[builtins fixtures/dataclasses.pyi]
1571+
1572+
[case testDataclassGenericInheritance2]
1573+
# flags: --python-version 3.7
1574+
from dataclasses import dataclass
1575+
from typing import Any, Callable, Generic, TypeVar, List
1576+
1577+
T = TypeVar("T")
1578+
S = TypeVar("S")
1579+
1580+
@dataclass
1581+
class Parent(Generic[T]):
1582+
f: Callable[[T], Any]
1583+
1584+
@dataclass
1585+
class Child(Parent[T]): ...
1586+
1587+
class A: ...
1588+
def func(obj: A) -> bool: ...
1589+
1590+
reveal_type(Child[A](func).f) # N: Revealed type is "def (__main__.A) -> Any"
1591+
1592+
@dataclass
1593+
class Parent2(Generic[T]):
1594+
a: List[T]
1595+
1596+
@dataclass
1597+
class Child2(Generic[T, S], Parent2[S]):
1598+
b: List[T]
1599+
1600+
reveal_type(Child2([A()], [1]).a) # N: Revealed type is "builtins.list[__main__.A]"
1601+
reveal_type(Child2[int, A]([A()], [1]).b) # N: Revealed type is "builtins.list[builtins.int]"
1602+
[builtins fixtures/dataclasses.pyi]

0 commit comments

Comments
 (0)