From 88422ea1b6553a88264d6b5d26e671c4a6abd4f6 Mon Sep 17 00:00:00 2001 From: Dave Halter Date: Thu, 8 Jan 2026 22:22:10 +0100 Subject: [PATCH] Change the spec for class access of Self variables --- conformance/tests/generics_self_advanced.py | 6 ++++-- docs/spec/generics.rst | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/conformance/tests/generics_self_advanced.py b/conformance/tests/generics_self_advanced.py index ab389081..4e17a7ae 100644 --- a/conformance/tests/generics_self_advanced.py +++ b/conformance/tests/generics_self_advanced.py @@ -40,6 +40,8 @@ def method2(self) -> None: @classmethod def method3(cls) -> None: assert_type(cls, type[Self]) - assert_type(cls.a, list[Self]) - assert_type(cls.a[0], Self) + cls.a # E: Access to generic instance variables via class is ambiguous assert_type(cls.method1(), Self) + +ClassB.a # E: Ambigous access +ClassB.a = ClassB.method1() # E: Ambigous write diff --git a/docs/spec/generics.rst b/docs/spec/generics.rst index ff1396a2..57b01a46 100644 --- a/docs/spec/generics.rst +++ b/docs/spec/generics.rst @@ -2393,6 +2393,22 @@ containing a ``Self`` type as a ``property`` that returns that type: def ordinal_value(self) -> str: return str(self.value) + +Accessing a variable through the class object that has a type annotation where +the annotation contains an occurrence of Self is not allowed, because Self can +be different depending on the class in the inheritance hierarchy: + +:: + + class C: + others: list[Self] + + class D(C): ... + + C.others = [C()] + print(D.others) # This is not list[Self], but list[C] + + Use in Generic Classes ^^^^^^^^^^^^^^^^^^^^^^