Skip to content

Commit

Permalink
Report that NamedTuple and dataclass are incompatile instead of c…
Browse files Browse the repository at this point in the history
…rashing. (#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]>
  • Loading branch information
3 people authored Feb 8, 2025
1 parent 7c0c4b4 commit a8c2345
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,9 @@ def dataclass_tag_callback(ctx: ClassDefContext) -> None:

def dataclass_class_maker_callback(ctx: ClassDefContext) -> bool:
"""Hooks into the class typechecking process to add support for dataclasses."""
if any(i.is_named_tuple for i in ctx.cls.info.mro):
ctx.api.fail("A NamedTuple cannot be a dataclass", ctx=ctx.cls.info)
return True
transformer = DataclassTransformer(
ctx.cls, ctx.reason, _get_transform_spec(ctx.reason), ctx.api
)
Expand Down
17 changes: 17 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -2576,3 +2576,20 @@ reveal_type(m.b) # N: Revealed type is "builtins.int"
m.a = 1 # E: Cannot assign to final attribute "a"
m.b = 2 # E: Cannot assign to final attribute "b"
[builtins fixtures/tuple.pyi]

[case testNoCrashForDataclassNamedTupleCombination]
# flags: --python-version 3.13
from dataclasses import dataclass
from typing import NamedTuple

@dataclass
class A(NamedTuple): # E: A NamedTuple cannot be a dataclass
i: int

class B1(NamedTuple):
i: int
@dataclass
class B2(B1): # E: A NamedTuple cannot be a dataclass
pass

[builtins fixtures/tuple.pyi]

0 comments on commit a8c2345

Please sign in to comment.