Skip to content

Check slots assignments on self types #19332

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
3 changes: 3 additions & 0 deletions mypy/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3698,6 +3698,9 @@ def check_assignment_to_slots(self, lvalue: Lvalue) -> None:
return

inst = get_proper_type(self.expr_checker.accept(lvalue.expr))
if isinstance(inst, TypeVarType) and inst.id.is_self():
# Unwrap self type
inst = get_proper_type(inst.upper_bound)
if not isinstance(inst, Instance):
return
if inst.type.slots is None:
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-slots.test
Original file line number Diff line number Diff line change
Expand Up @@ -521,3 +521,19 @@ x = X()
X.a # E: "a" in __slots__ conflicts with class variable access
x.a
[builtins fixtures/tuple.pyi]

[case testSlotsOnSelfType]
from typing_extensions import Self

class X:
__slots__ = ("foo",)
foo: int

def method1(self: Self) -> Self:
self.bar = 0 # E: Trying to assign name "bar" that is not in "__slots__" of type "__main__.X"
return self

def method2(self) -> Self:
self.bar = 0 # E: Trying to assign name "bar" that is not in "__slots__" of type "__main__.X"
return self
[builtins fixtures/tuple.pyi]