Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions mypy/checkmember.py
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,10 @@ def analyze_class_attribute_access(
if isinstance(node.node, TypeInfo):
mx.msg.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, mx.context)

# Refuse class attribute access if slot defined
if info.slots and name in info.slots:
mx.msg.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name), mx.context)

# If a final attribute was declared on `self` in `__init__`, then it
# can't be accessed on the class object.
if node.implicit and isinstance(node.node, Var) and node.node.is_final:
Expand Down
1 change: 1 addition & 0 deletions mypy/message_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage:
MODULE_LEVEL_GETATTRIBUTE: Final = ErrorMessage(
"__getattribute__ is not valid at the module level"
)
CLASS_VAR_CONFLICTS_SLOTS: Final = '"{}" in __slots__ conflicts with class variable access'
NAME_NOT_IN_SLOTS: Final = ErrorMessage(
'Trying to assign name "{}" that is not in "__slots__" of type "{}"'
)
Expand Down
10 changes: 10 additions & 0 deletions test-data/unit/check-slots.test
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,13 @@ class A:
self.b = 2
self.missing = 3
[builtins fixtures/tuple.pyi]

[case testSlotsWithClassVar]
from typing import ClassVar
class X:
__slots__ = ('a',)
a: int
x = X()
X.a # E: "a" in __slots__ conflicts with class variable access
x.a
[builtins fixtures/tuple.pyi]