← 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 / 0
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 assert_type(self.a, list[Self])
37 assert_type(self.a[0], Self)
38 assert_type(self.method1(), Self)
40 @classmethod
41 def method3(cls) -> None:
42 assert_type(cls, type[Self])
43 assert_type(cls.a, list[Self])
44 assert_type(cls.a[0], Self)
45 assert_type(cls.method1(), Self)