Skip to content

Commit

Permalink
Added error for class attribute access with slot (#14125)
Browse files Browse the repository at this point in the history
Fixed #13103  

Adds a check to class attribute access to ensure it isn't a defined
slot.
  • Loading branch information
Harrison McCarty authored Dec 13, 2022
1 parent 42dc1c4 commit 7eef68a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
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]

0 comments on commit 7eef68a

Please sign in to comment.