Skip to content

Emit a diagnostic on NamedTuple classes decorated with @dataclass #2515

@AlexWaygood

Description

@AlexWaygood

If a user does this, it indicates that they're confused, because attempting to create an instance of a class like this always fails at runtime:

from dataclasses import dataclass
from typing import NamedTuple

@dataclass
class Foo(NamedTuple):
    x: int
    y: str

# Both of these calls fail with `AttributeError: can't set attribute`
Foo(42, "y")
Foo(x=42, y="y")

We don't model the semantics here correctly right now (we don't synthesize any of the NamedTuple generated methods on this class at all -- we think, for instance, that this class inherits its __new__ method from tuple). But we don't need to model the semantics correctly if we detect that this is an error (which it is) and emit an appropriate diagnostic.

We added a TODO for this in the code in astral-sh/ruff@3e02994, but I don't think we added any tests for it.

Metadata

Metadata

Assignees

Labels

dataclassesIssues relating to dataclasses and dataclass_transformnamedtuplesruntime semanticsAccurate modeling of how Python's semantics work at runtimetyping semanticstyping-module features, spec compliance, etc

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions