Skip to content

Commit 4a1a38e

Browse files
authored
Add runtime __slots__ attribute to dataclasses (#15649)
Closes #15647
1 parent 235a3bb commit 4a1a38e

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

mypy/plugins/dataclasses.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -469,9 +469,15 @@ def add_slots(
469469
self._cls,
470470
)
471471
return
472-
473472
info.slots = generated_slots
474473

474+
# Now, insert `.__slots__` attribute to class namespace:
475+
slots_type = TupleType(
476+
[self._api.named_type("builtins.str") for _ in generated_slots],
477+
self._api.named_type("builtins.tuple"),
478+
)
479+
add_attribute_to_class(self._api, self._cls, "__slots__", slots_type)
480+
475481
def reset_init_only_vars(self, info: TypeInfo, attributes: list[DataclassAttribute]) -> None:
476482
"""Remove init-only vars from the class and reset init var declarations."""
477483
for attr in attributes:

test-data/unit/check-dataclasses.test

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1547,6 +1547,35 @@ class Other:
15471547
[builtins fixtures/dataclasses.pyi]
15481548

15491549

1550+
[case testDataclassWithSlotsRuntimeAttr]
1551+
# flags: --python-version 3.10
1552+
from dataclasses import dataclass
1553+
1554+
@dataclass(slots=True)
1555+
class Some:
1556+
x: int
1557+
y: str
1558+
z: bool
1559+
1560+
reveal_type(Some.__slots__) # N: Revealed type is "Tuple[builtins.str, builtins.str, builtins.str]"
1561+
1562+
@dataclass(slots=True)
1563+
class Other:
1564+
x: int
1565+
y: str
1566+
1567+
reveal_type(Other.__slots__) # N: Revealed type is "Tuple[builtins.str, builtins.str]"
1568+
1569+
1570+
@dataclass
1571+
class NoSlots:
1572+
x: int
1573+
y: str
1574+
1575+
NoSlots.__slots__ # E: "Type[NoSlots]" has no attribute "__slots__"
1576+
[builtins fixtures/dataclasses.pyi]
1577+
1578+
15501579
[case testSlotsDefinitionWithTwoPasses1]
15511580
# flags: --python-version 3.10
15521581
# https://github.com/python/mypy/issues/11821

0 commit comments

Comments
 (0)