Skip to content

Commit 88422ea

Browse files
committed
Change the spec for class access of Self variables
1 parent dece44f commit 88422ea

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

conformance/tests/generics_self_advanced.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ def method2(self) -> None:
4040
@classmethod
4141
def method3(cls) -> None:
4242
assert_type(cls, type[Self])
43-
assert_type(cls.a, list[Self])
44-
assert_type(cls.a[0], Self)
43+
cls.a # E: Access to generic instance variables via class is ambiguous
4544
assert_type(cls.method1(), Self)
45+
46+
ClassB.a # E: Ambigous access
47+
ClassB.a = ClassB.method1() # E: Ambigous write

docs/spec/generics.rst

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2393,6 +2393,22 @@ containing a ``Self`` type as a ``property`` that returns that type:
23932393
def ordinal_value(self) -> str:
23942394
return str(self.value)
23952395

2396+
2397+
Accessing a variable through the class object that has a type annotation where
2398+
the annotation contains an occurrence of Self is not allowed, because Self can
2399+
be different depending on the class in the inheritance hierarchy:
2400+
2401+
::
2402+
2403+
class C:
2404+
others: list[Self]
2405+
2406+
class D(C): ...
2407+
2408+
C.others = [C()]
2409+
print(D.others) # This is not list[Self], but list[C]
2410+
2411+
23962412
Use in Generic Classes
23972413
^^^^^^^^^^^^^^^^^^^^^^
23982414

0 commit comments

Comments
 (0)