Skip to content

Commit a8c2345

Browse files
tyrallapre-commit-ci[bot]sobolevn
authored
Report that NamedTuple and dataclass are incompatile instead of crashing. (#18633)
Fixes #18527 The fix is pretty simple. I could not find a situation where combining `NamedTuple` and `dataclass` makes sense, so emitting an error and just not applying the dataclass transformations seems sensible. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: sobolevn <[email protected]>
1 parent 7c0c4b4 commit a8c2345

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

mypy/plugins/dataclasses.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -965,6 +965,9 @@ def dataclass_tag_callback(ctx: ClassDefContext) -> None:
965965

966966
def dataclass_class_maker_callback(ctx: ClassDefContext) -> bool:
967967
"""Hooks into the class typechecking process to add support for dataclasses."""
968+
if any(i.is_named_tuple for i in ctx.cls.info.mro):
969+
ctx.api.fail("A NamedTuple cannot be a dataclass", ctx=ctx.cls.info)
970+
return True
968971
transformer = DataclassTransformer(
969972
ctx.cls, ctx.reason, _get_transform_spec(ctx.reason), ctx.api
970973
)

test-data/unit/check-dataclasses.test

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2576,3 +2576,20 @@ reveal_type(m.b) # N: Revealed type is "builtins.int"
25762576
m.a = 1 # E: Cannot assign to final attribute "a"
25772577
m.b = 2 # E: Cannot assign to final attribute "b"
25782578
[builtins fixtures/tuple.pyi]
2579+
2580+
[case testNoCrashForDataclassNamedTupleCombination]
2581+
# flags: --python-version 3.13
2582+
from dataclasses import dataclass
2583+
from typing import NamedTuple
2584+
2585+
@dataclass
2586+
class A(NamedTuple): # E: A NamedTuple cannot be a dataclass
2587+
i: int
2588+
2589+
class B1(NamedTuple):
2590+
i: int
2591+
@dataclass
2592+
class B2(B1): # E: A NamedTuple cannot be a dataclass
2593+
pass
2594+
2595+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)