Skip to content

Commit

Permalink
Add runtime __slots__ attribute to dataclasses (#15649)
Browse files Browse the repository at this point in the history
Closes #15647
  • Loading branch information
sobolevn committed Jul 12, 2023
1 parent 235a3bb commit 4a1a38e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
8 changes: 7 additions & 1 deletion mypy/plugins/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,9 +469,15 @@ def add_slots(
self._cls,
)
return

info.slots = generated_slots

# Now, insert `.__slots__` attribute to class namespace:
slots_type = TupleType(
[self._api.named_type("builtins.str") for _ in generated_slots],
self._api.named_type("builtins.tuple"),
)
add_attribute_to_class(self._api, self._cls, "__slots__", slots_type)

def reset_init_only_vars(self, info: TypeInfo, attributes: list[DataclassAttribute]) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
Expand Down
29 changes: 29 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,35 @@ class Other:
[builtins fixtures/dataclasses.pyi]


[case testDataclassWithSlotsRuntimeAttr]
# flags: --python-version 3.10
from dataclasses import dataclass

@dataclass(slots=True)
class Some:
x: int
y: str
z: bool

reveal_type(Some.__slots__) # N: Revealed type is "Tuple[builtins.str, builtins.str, builtins.str]"

@dataclass(slots=True)
class Other:
x: int
y: str

reveal_type(Other.__slots__) # N: Revealed type is "Tuple[builtins.str, builtins.str]"


@dataclass
class NoSlots:
x: int
y: str

NoSlots.__slots__ # E: "Type[NoSlots]" has no attribute "__slots__"
[builtins fixtures/dataclasses.pyi]


[case testSlotsDefinitionWithTwoPasses1]
# flags: --python-version 3.10
# https://github.com/python/mypy/issues/11821
Expand Down

0 comments on commit 4a1a38e

Please sign in to comment.