Skip to content

Commit 70d8b3f

Browse files
committed
Check slots assignments on self types
1 parent 16e99de commit 70d8b3f

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

mypy/checker.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3698,6 +3698,9 @@ def check_assignment_to_slots(self, lvalue: Lvalue) -> None:
36983698
return
36993699

37003700
inst = get_proper_type(self.expr_checker.accept(lvalue.expr))
3701+
if isinstance(inst, TypeVarType) and inst.id.is_self():
3702+
# Unwrap self type
3703+
inst = get_proper_type(inst.upper_bound)
37013704
if not isinstance(inst, Instance):
37023705
return
37033706
if inst.type.slots is None:

test-data/unit/check-slots.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,3 +521,19 @@ x = X()
521521
X.a # E: "a" in __slots__ conflicts with class variable access
522522
x.a
523523
[builtins fixtures/tuple.pyi]
524+
525+
[case testSlotsOnSelfType]
526+
from typing_extensions import Self
527+
528+
class X:
529+
__slots__ = ("foo",)
530+
foo: int
531+
532+
def method1(self: Self) -> Self:
533+
self.bar = 0 # E: Trying to assign name "bar" that is not in "__slots__" of type "__main__.X"
534+
return self
535+
536+
def method2(self) -> Self:
537+
self.bar = 0 # E: Trying to assign name "bar" that is not in "__slots__" of type "__main__.X"
538+
return self
539+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)