-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathgenerics_syntax_scoping.py
More file actions
125 lines (74 loc) · 2.2 KB
/
generics_syntax_scoping.py
File metadata and controls
125 lines (74 loc) · 2.2 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""
Tests the scoping rules for type parameter syntax introduced in PEP 695.
"""
# Specification: https://peps.python.org/pep-0695/#type-parameter-scopes
from typing import Callable, Mapping, Sequence, TypeVar, assert_type
# > A compiler error or runtime exception is generated if the definition
# > of an earlier type parameter references a later type parameter even
# > if the name is defined in an outer scope.
class ClassA[S, T: Sequence[S]]: # E
...
class ClassB[S: Sequence[T], T]: # E
...
class Foo[T]:
...
class BaseClassC[T]:
def __init_subclass__(cls, param: type[Foo[T]]) -> None:
...
class ClassC[T](BaseClassC[T], param=Foo[T]): # OK
...
print(T) # E: Runtime error: 'T' is not defined
def decorator1[
T, **P, R
](x: type[Foo[T]]) -> Callable[[Callable[P, R]], Callable[P, R]]:
raise NotImplementedError
@decorator1(Foo[T]) # E: Runtime error: 'T' is not defined
class ClassD[T]:
...
type Alias1[K, V] = Mapping[K, V] | Sequence[K]
S: int = int(0)
def outer1[S](x: str):
S: str = x
T: int = 1
def outer2[T]():
def inner1():
nonlocal S # OK
assert_type(S, str)
# nonlocal T # Syntax error
def inner2():
global S # OK
assert_type(S, int)
class Outer1:
class Private:
pass
class Inner[T](Private, Sequence[T]): # OK
pass
def method1[T](self, a: Inner[T]) -> Inner[T]: # OK
return a
def decorator2[**P, R](x: int) -> Callable[[Callable[P, R]], Callable[P, R]]:
raise NotImplementedError
T = int(0)
@decorator2(T) # OK
class ClassE[T](Sequence[T]):
T = int(1)
def method1[T](self): # E
...
def method2[T](self, x=T): # E
...
def method3[T](self, x: T): # E
...
T = int(0)
def f(a: int, b: str, c: complex):
class Outer2[T]:
T = a
assert_type(T, int)
class Inner1:
T = b
assert_type(T, str)
def inner_method(self):
assert_type(T, TypeVar)
def outer_method(self):
T = c
assert_type(T, complex)
def inner_func():
assert_type(T, complex)