-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathgenerics_self_advanced.py
More file actions
47 lines (34 loc) · 1.06 KB
/
generics_self_advanced.py
File metadata and controls
47 lines (34 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""
Tests for advanced or special-case usage of the typing.Self type.
"""
from typing import assert_type, Self
class ParentA:
# Test for property that returns Self.
@property
def prop1(self) -> Self:
raise NotImplementedError
class ChildA(ParentA):
...
assert_type(ParentA().prop1, ParentA)
assert_type(ChildA().prop1, ChildA)
# Test for a child that accesses an attribute within a parent
# whose type is annotated using Self.
class ParentB:
a: list[Self]
@classmethod
def method1(cls) -> Self:
raise NotImplementedError
class ChildB(ParentB):
b: int = 0
def method2(self) -> None:
assert_type(self, Self)
assert_type(self.a, list[Self])
assert_type(self.a[0], Self)
assert_type(self.method1(), Self)
@classmethod
def method3(cls) -> None:
assert_type(cls, type[Self])
cls.a # E: Access to generic instance variables via class is ambiguous
assert_type(cls.method1(), Self)
ChildB.a # E: Ambigous access
ParentB.a = [ChildB.method1()] # E: Ambigous write