diff --git a/mypy/plugins/dataclasses.py b/mypy/plugins/dataclasses.py index a511e714ac6b4..09341bc453c23 100644 --- a/mypy/plugins/dataclasses.py +++ b/mypy/plugins/dataclasses.py @@ -599,6 +599,10 @@ def collect_attributes(self) -> list[DataclassAttribute] | None: # This might be a property / field name clash. # We will issue an error later. continue + if isinstance(node, TypeInfo): + # The declared type is shadowed by a class created from a call like + # `x: Foo = namedtuple('Foo', [...])`, so there is no dataclass field here. + continue assert isinstance(node, Var), node diff --git a/test-data/unit/check-dataclasses.test b/test-data/unit/check-dataclasses.test index f43ac255373e6..1a81750e3e01f 100644 --- a/test-data/unit/check-dataclasses.test +++ b/test-data/unit/check-dataclasses.test @@ -2746,6 +2746,19 @@ class B2(B1): # E: A NamedTuple cannot be a dataclass [builtins fixtures/tuple.pyi] +[case testNoCrashForDataclassFieldAssignedFunctionalNamedTuple] +from collections import namedtuple +from dataclasses import dataclass + +@dataclass +class C: + p: "Point" = namedtuple("Point", ["x", "y"]) # E: First argument to namedtuple() should be "p", not "Point" + +@dataclass +class D: + Point: "Point" = namedtuple("Point", ["x", "y"]) +[builtins fixtures/tuple.pyi] + [case testDataclassesTypeGuard] import dataclasses