Skip to content

Commit 7eef68a

Browse files
author
Harrison McCarty
authored
Added error for class attribute access with slot (#14125)
Fixed #13103 Adds a check to class attribute access to ensure it isn't a defined slot.
1 parent 42dc1c4 commit 7eef68a

File tree

3 files changed

+15
-0
lines changed

3 files changed

+15
-0
lines changed

mypy/checkmember.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,10 @@ def analyze_class_attribute_access(
912912
if isinstance(node.node, TypeInfo):
913913
mx.msg.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, mx.context)
914914

915+
# Refuse class attribute access if slot defined
916+
if info.slots and name in info.slots:
917+
mx.msg.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name), mx.context)
918+
915919
# If a final attribute was declared on `self` in `__init__`, then it
916920
# can't be accessed on the class object.
917921
if node.implicit and isinstance(node.node, Var) and node.node.is_final:

mypy/message_registry.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,7 @@ def with_additional_msg(self, info: str) -> ErrorMessage:
137137
MODULE_LEVEL_GETATTRIBUTE: Final = ErrorMessage(
138138
"__getattribute__ is not valid at the module level"
139139
)
140+
CLASS_VAR_CONFLICTS_SLOTS: Final = '"{}" in __slots__ conflicts with class variable access'
140141
NAME_NOT_IN_SLOTS: Final = ErrorMessage(
141142
'Trying to assign name "{}" that is not in "__slots__" of type "{}"'
142143
)

test-data/unit/check-slots.test

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,3 +517,13 @@ class A:
517517
self.b = 2
518518
self.missing = 3
519519
[builtins fixtures/tuple.pyi]
520+
521+
[case testSlotsWithClassVar]
522+
from typing import ClassVar
523+
class X:
524+
__slots__ = ('a',)
525+
a: int
526+
x = X()
527+
X.a # E: "a" in __slots__ conflicts with class variable access
528+
x.a
529+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)