← Back to index

generics_self_advanced.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 0
FN: 0
Optional: 0 / 2
1"""
2Tests for advanced or special-case usage of the typing.Self type.
3"""
4
5from typing import assert_type, Self
6
7
8class ParentA:
9 # Test for property that returns Self.
10 @property
11 def prop1(self) -> Self:
12 raise NotImplementedError
14class ChildA(ParentA):
15 ...
18assert_type(ParentA().prop1, ParentA)
19assert_type(ChildA().prop1, ChildA)
22# Test for a child that accesses an attribute within a parent
23# whose type is annotated using Self.
24class ParentB:
25 a: list[Self]
27 @classmethod
28 def method1(cls) -> Self:
29 raise NotImplementedError
31class ChildB(ParentB):
32 b: int = 0
34 def method2(self) -> None:
35 assert_type(self, Self)
36 # Allow type checkers to error here, since Self definitions on
37 # non-final classes are unsound.
38 a = self.a # E?
39 assert_type(a, list[Self])
40 assert_type(a[0], Self)
41 assert_type(self.method1(), Self)
43 @classmethod
44 def method3(cls) -> None:
45 assert_type(cls, type[Self])
46 # Allow type checkers to error here, since Self definitions on
47 # non-final classes are unsound.
48 a = cls.a # E?
49 assert_type(a, list[Self])
50 assert_type(a[0], Self)
51 assert_type(cls.method1(), Self)