Skip to content

Commit cb2c07b

Browse files
AlexWaygoodJukkaL
authored andcommitted
Fix crash on type alias definition inside dataclass declaration (#12792)
Skip processing a type alias node and generate an error. Fixes #12544.
1 parent 3cd1e2c commit cb2c07b

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

mypy/plugins/dataclasses.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from mypy.nodes import (
77
ARG_OPT, ARG_NAMED, ARG_NAMED_OPT, ARG_POS, ARG_STAR, ARG_STAR2, MDEF,
8-
Argument, AssignmentStmt, CallExpr, Context, Expression, JsonDict,
8+
Argument, AssignmentStmt, CallExpr, TypeAlias, Context, Expression, JsonDict,
99
NameExpr, RefExpr, SymbolTableNode, TempNode, TypeInfo, Var, TypeVarExpr,
1010
PlaceholderNode
1111
)
@@ -333,6 +333,20 @@ def collect_attributes(self) -> Optional[List[DataclassAttribute]]:
333333

334334
node = sym.node
335335
assert not isinstance(node, PlaceholderNode)
336+
337+
if isinstance(node, TypeAlias):
338+
ctx.api.fail(
339+
(
340+
'Type aliases inside dataclass definitions '
341+
'are not supported at runtime'
342+
),
343+
node
344+
)
345+
# Skip processing this node. This doesn't match the runtime behaviour,
346+
# but the only alternative would be to modify the SymbolTable,
347+
# and it's a little hairy to do that in a plugin.
348+
continue
349+
336350
assert isinstance(node, Var)
337351

338352
# x: ClassVar[int] is ignored by dataclasses.

test-data/unit/check-dataclasses.test

+28
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,34 @@ Application.COUNTER = 1
526526

527527
[builtins fixtures/dataclasses.pyi]
528528

529+
[case testTypeAliasInDataclassDoesNotCrash]
530+
# flags: --python-version 3.7
531+
from dataclasses import dataclass
532+
from typing import Callable
533+
from typing_extensions import TypeAlias
534+
535+
@dataclass
536+
class Foo:
537+
x: int
538+
539+
@dataclass
540+
class One:
541+
S: TypeAlias = Foo # E: Type aliases inside dataclass definitions are not supported at runtime
542+
543+
a = One()
544+
reveal_type(a.S) # N: Revealed type is "def (x: builtins.int) -> __main__.Foo"
545+
a.S() # E: Missing positional argument "x" in call to "Foo"
546+
reveal_type(a.S(5)) # N: Revealed type is "__main__.Foo"
547+
548+
@dataclass
549+
class Two:
550+
S: TypeAlias = Callable[[int], str] # E: Type aliases inside dataclass definitions are not supported at runtime
551+
552+
c = Two()
553+
x = c.S # E: Member "S" is not assignable
554+
reveal_type(x) # N: Revealed type is "Any"
555+
[builtins fixtures/dataclasses.pyi]
556+
529557
[case testDataclassOrdering]
530558
# flags: --python-version 3.7
531559
from dataclasses import dataclass

0 commit comments

Comments
 (0)