2Tests the scoping rules for type parameter syntax introduced in PEP 695.
5# Specification: https://peps.python.org/pep-0695/#type-parameter-scopes
7from typing import Callable, Mapping, Sequence, TypeVar, assert_type
9# > A compiler error or runtime exception is generated if the definition
10# > of an earlier type parameter references a later type parameter even
11# > if the name is defined in an outer scope.
14class ClassA[S, T: Sequence[S]]: # E
[invalid-type-variable-bound] TypeVar upper bound cannot be generic
18class ClassB[S: Sequence[T], T]: # E
[invalid-type-variable-bound] TypeVar upper bound cannot be generic
27 def __init_subclass__(cls, param: type[Foo[T]]) -> None:
31class ClassC[T](BaseClassC[T], param=Foo[T]): # OK
35print(T) # E: Runtime error: 'T' is not defined
[unresolved-reference] Name `T` used when not defined
40](x: type[Foo[T]]) -> Callable[[Callable[P, R]], Callable[P, R]]:
41 raise NotImplementedError
44@decorator1(Foo[T]) # E: Runtime error: 'T' is not defined
[unresolved-reference] Name `T` used when not defined
49type Alias1[K, V] = Mapping[K, V] | Sequence[K]
63 # nonlocal T # Syntax error
74 class Inner[T](Private, Sequence[T]): # OK
77 def method1[T](self, a: Inner[T]) -> Inner[T]: # OK
81def decorator2[**P, R](x: int) -> Callable[[Callable[P, R]], Callable[P, R]]:
82 raise NotImplementedError
89class ClassE[T](Sequence[T]):
92 def method1[T](self): # E
Expected a ty diagnostic for this line
95 def method2[T](self, x=T): # E
Expected a ty diagnostic for this line
98 def method3[T](self, x: T): # E
Expected a ty diagnostic for this line
Unexpected error
[type-assertion-failure] Type `str` does not match asserted type `Literal[""]`
115 def inner_method(self):
116 assert_type(T, TypeVar)
118 def outer_method(self):
121 assert_type(T, complex)
Unexpected error
[type-assertion-failure] Type `int | float | complex` does not match asserted type `complex`
124 assert_type(T, complex)
Unexpected error
[type-assertion-failure] Type `int | float | complex` does not match asserted type `complex`