Skip to content

Commit 5b28b62

Browse files
authored
Check slots assignments on self types (#19332)
Fixes #19331.
1 parent c213db0 commit 5b28b62

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
@@ -3752,6 +3752,9 @@ def check_assignment_to_slots(self, lvalue: Lvalue) -> None:
37523752
return
37533753

37543754
inst = get_proper_type(self.expr_checker.accept(lvalue.expr))
3755+
if isinstance(inst, TypeVarType) and inst.id.is_self():
3756+
# Unwrap self type
3757+
inst = get_proper_type(inst.upper_bound)
37553758
if not isinstance(inst, Instance):
37563759
return
37573760
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
@@ -544,3 +544,19 @@ x = X()
544544
X.a # E: "a" in __slots__ conflicts with class variable access
545545
x.a
546546
[builtins fixtures/tuple.pyi]
547+
548+
[case testSlotsOnSelfType]
549+
from typing_extensions import Self
550+
551+
class X:
552+
__slots__ = ("foo",)
553+
foo: int
554+
555+
def method1(self: Self) -> Self:
556+
self.bar = 0 # E: Trying to assign name "bar" that is not in "__slots__" of type "__main__.X"
557+
return self
558+
559+
def method2(self) -> Self:
560+
self.bar = 0 # E: Trying to assign name "bar" that is not in "__slots__" of type "__main__.X"
561+
return self
562+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)