Debian Codegraph @

test-data/unit/check-typeform.test

raw
1 -- TypeForm Type
2
3 [case testRecognizesUnparameterizedTypeFormInAnnotation]
4 from typing_extensions import TypeForm
5 typx: TypeForm = str
6 reveal_type(typx) # N: Revealed type is "TypeForm[Any]"
7 [builtins fixtures/primitives.pyi]
8 [typing fixtures/typing-full.pyi]
9
10 [case testRecognizesParameterizedTypeFormInAnnotation]
11 from typing_extensions import TypeForm
12 typx: TypeForm[str] = str
13 reveal_type(typx) # N: Revealed type is "TypeForm[builtins.str]"
14 [builtins fixtures/primitives.pyi]
15 [typing fixtures/typing-full.pyi]
16
17
18 -- Type Expression Location: Assignment
19
20 [case testCanAssignTypeExpressionToTypeFormVariable]
21 from typing_extensions import TypeForm
22 typx: TypeForm[str] = str
23 [builtins fixtures/primitives.pyi]
24 [typing fixtures/typing-full.pyi]
25
26 [case testCanAssignTypeExpressionToUnionTypeFormVariable]
27 from typing_extensions import TypeForm
28 typx: TypeForm[str | None] = str | None
29 [builtins fixtures/primitives.pyi]
30 [typing fixtures/typing-full.pyi]
31
32 [case testCannotAssignTypeExpressionToTypeFormVariableWithIncompatibleItemType]
33 from typing_extensions import TypeForm
34 typx: TypeForm[str] = int # E: Incompatible types in assignment (expression has type "TypeForm[int]", variable has type "TypeForm[str]")
35 [builtins fixtures/primitives.pyi]
36 [typing fixtures/typing-full.pyi]
37
38 [case testCanAssignValueExpressionToTypeFormVariableIfValueIsATypeForm1]
39 from typing_extensions import TypeForm
40 typx1: TypeForm = str
41 typx2: TypeForm = typx1 # looks like a type expression: name
42 [builtins fixtures/primitives.pyi]
43 [typing fixtures/typing-full.pyi]
44
45 [case testCanAssignValueExpressionToTypeFormVariableIfValueIsATypeForm2]
46 from typing_extensions import TypeForm
47 def identity_tf(x: TypeForm) -> TypeForm:
48 return x
49 typx1: TypeForm = str
50 typx2: TypeForm = identity_tf(typx1) # does not look like a type expression
51 [builtins fixtures/primitives.pyi]
52 [typing fixtures/typing-full.pyi]
53
54 [case testCannotAssignValueExpressionToTypeFormVariableIfValueIsNotATypeForm]
55 from typing_extensions import TypeForm
56 val: int = 42
57 typx: TypeForm = val # E: Incompatible types in assignment (expression has type "int", variable has type "TypeForm[Any]")
58 [builtins fixtures/primitives.pyi]
59 [typing fixtures/typing-full.pyi]
60
61 [case testCanAssignNoneTypeExpressionToTypeFormVariable]
62 from typing_extensions import TypeForm
63 typx: TypeForm = None
64 reveal_type(typx) # N: Revealed type is "TypeForm[Any]"
65 [builtins fixtures/primitives.pyi]
66 [typing fixtures/typing-full.pyi]
67
68 [case testCanAssignTypeExpressionToTypeFormVariableDeclaredEarlier]
69 from typing import Type, TypeForm
70 typ: Type
71 typ = int | None # E: Incompatible types in assignment (expression has type "object", variable has type "type[Any]")
72 typx: TypeForm
73 typx = int | None
74 [builtins fixtures/primitives.pyi]
75 [typing fixtures/typing-full.pyi]
76
77 [case testCanAssignTypeExpressionWithStringAnnotationToTypeFormVariable]
78 from typing_extensions import TypeForm
79 typx: TypeForm[str | None] = 'str | None'
80 [builtins fixtures/primitives.pyi]
81 [typing fixtures/typing-full.pyi]
82
83
84 -- Type Expression Location: Function Parameter
85
86 [case testCanPassTypeExpressionToTypeFormParameterInFunction]
87 from typing_extensions import TypeForm
88 def is_type(typx: TypeForm) -> bool:
89 return isinstance(typx, type)
90 is_type(int | None)
91 [builtins fixtures/primitives.pyi]
92 [typing fixtures/typing-full.pyi]
93
94 [case testCannotPassTypeExpressionToTypeParameter]
95 def is_type(typ: type) -> bool:
96 return isinstance(typ, type)
97 is_type(int | None) # E: Argument 1 to "is_type" has incompatible type "object"; expected "type"
98 [builtins fixtures/primitives.pyi]
99 [typing fixtures/typing-full.pyi]
100
101 [case testCanPassTypeExpressionToTypeFormParameterInMethod]
102 from typing_extensions import TypeForm
103 class C:
104 def is_type(self, typx: TypeForm) -> bool:
105 return isinstance(typx, type)
106 C().is_type(int | None)
107 [builtins fixtures/primitives.pyi]
108 [typing fixtures/typing-full.pyi]
109
110 [case testCanPassTypeExpressionToTypeFormParameterInOverload]
111 from typing import overload, TypeForm
112 @overload
113 def is_type(typx: TypeForm) -> bool: ...
114 @overload
115 def is_type(typx: type) -> bool: ...
116 def is_type(typx):
117 return isinstance(typx, type)
118 is_type(int | None)
119 [builtins fixtures/primitives.pyi]
120 [typing fixtures/typing-full.pyi]
121
122 [case testCanPassTypeExpressionToTypeFormParameterInDecorator]
123 from typing import Callable, TypeForm, TypeVar
124 P = TypeVar('P')
125 R = TypeVar('R')
126 def expects_type(typx: TypeForm) -> Callable[[Callable[[P], R]], Callable[[P], R]]:
127 def wrap(func: Callable[[P], R]) -> Callable[[P], R]:
128 func.expected_type = typx # type: ignore[attr-defined]
129 return func
130 return wrap
131 @expects_type(int | None)
132 def sum_ints(x: int | None) -> int:
133 return (x or 0)
134 [builtins fixtures/primitives.pyi]
135 [typing fixtures/typing-full.pyi]
136
137 [case testCanPassTypeExpressionToTypeFormVarargsParameter]
138 from typing import Callable, ParamSpec, TypeForm, TypeVar
139 P = ParamSpec('P')
140 R = TypeVar('R')
141 def expects_types(*typxs: TypeForm) -> Callable[[Callable[P, R]], Callable[P, R]]:
142 def wrap(func: Callable[P, R]) -> Callable[P, R]:
143 func.expected_types = typxs # type: ignore[attr-defined]
144 return func
145 return wrap
146 @expects_types(int | None, int)
147 def sum_ints(x: int | None, y: int) -> tuple[int, int]:
148 return ((x or 0), y)
149 [builtins fixtures/primitives.pyi]
150 [typing fixtures/typing-full.pyi]
151
152 [case testCanPassTypeExpressionWithStringAnnotationToTypeFormParameter]
153 from typing_extensions import TypeForm
154 def is_type(typx: TypeForm) -> bool:
155 return isinstance(typx, type)
156 is_type('int | None')
157 [builtins fixtures/primitives.pyi]
158 [typing fixtures/typing-full.pyi]
159
160
161 -- Type Expression Location: Return Statement
162
163 [case testCanReturnTypeExpressionInFunctionWithTypeFormReturnType]
164 from typing_extensions import TypeForm
165 def maybe_int_type() -> TypeForm:
166 return int | None
167 reveal_type(maybe_int_type()) # N: Revealed type is "TypeForm[Any]"
168 [builtins fixtures/primitives.pyi]
169 [typing fixtures/typing-full.pyi]
170
171 [case testCanReturnTypeExpressionWithStringAnnotationInFunctionWithTypeFormReturnType]
172 from typing_extensions import TypeForm
173 def maybe_int_type() -> TypeForm:
174 return 'int | None'
175 reveal_type(maybe_int_type()) # N: Revealed type is "TypeForm[Any]"
176 [builtins fixtures/primitives.pyi]
177 [typing fixtures/typing-full.pyi]
178
179
180 -- Type Expression Location: Other
181
182 -- In particular ensure that ExpressionChecker.try_parse_as_type_expression() in
183 -- the TypeChecker pass is able to parse types correctly even though it doesn't
184 -- have the same rich context as SemanticAnalyzer.try_parse_as_type_expression().
185
186 [case testTypeExpressionWithoutStringAnnotationRecognizedInOtherSyntacticLocations]
187 from typing import Dict, List, TypeForm
188 list_of_typx: List[TypeForm] = [int | str]
189 dict_with_typx_keys: Dict[TypeForm, int] = {
190 int | str: 1,
191 str | None: 2,
192 }
193 dict_with_typx_keys[int | str] + 1
194 [builtins fixtures/primitives.pyi]
195 [typing fixtures/typing-full.pyi]
196
197 [case testTypeExpressionWithStringAnnotationNotRecognizedInOtherSyntacticLocations]
198 from typing import Dict, List, TypeForm
199 list_of_typx: List[TypeForm] = ['int | str'] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
200 # E: List item 0 has incompatible type "str"; expected "TypeForm[Any]"
201 dict_with_typx_keys: Dict[TypeForm, int] = {
202 'int | str': 1, # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
203 # E: Dict entry 0 has incompatible type "str": "int"; expected "TypeForm[Any]": "int"
204 'str | None': 2, # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
205 # E: Dict entry 1 has incompatible type "str": "int"; expected "TypeForm[Any]": "int"
206 }
207 dict_with_typx_keys['int | str'] += 1 # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
208 # E: Invalid index type "str" for "dict[TypeForm[Any], int]"; expected type "TypeForm[Any]"
209 [builtins fixtures/dict.pyi]
210 [typing fixtures/typing-full.pyi]
211
212 [case testValueExpressionWithStringInTypeFormContextEmitsConservativeWarning]
213 from typing import Any, Dict, List, TypeForm
214 types: Dict[str, TypeForm] = {'any': Any}
215 # Ensure warning can be ignored if does not apply.
216 list_of_typx1: List[TypeForm] = [types['any']] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.
217 list_of_typx2: List[TypeForm] = [types['any']] # type: ignore[maybe-unrecognized-str-typeform]
218 # Ensure warning can be fixed using the suggested fix in the warning message.
219 list_of_typx3: List[TypeForm] = ['Any'] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
220 # E: List item 0 has incompatible type "str"; expected "TypeForm[Any]"
221 list_of_typx4: List[TypeForm] = [TypeForm('Any')]
222 [builtins fixtures/dict.pyi]
223 [typing fixtures/typing-full.pyi]
224
225 [case testSelfRecognizedInOtherSyntacticLocations]
226 from typing import List, Self, TypeForm
227 class C:
228 def foo(self) -> None:
229 list_of_typx1: List[TypeForm] = [Self]
230 typx1: TypeForm = Self
231 typx2: TypeForm = 'Self'
232 list_of_typx2: List[TypeForm] = [Self] # E: List item 0 has incompatible type "int"; expected "TypeForm[Any]"
233 typx3: TypeForm = Self # E: Incompatible types in assignment (expression has type "int", variable has type "TypeForm[Any]")
234 typx4: TypeForm = 'Self' # E: Incompatible types in assignment (expression has type "str", variable has type "TypeForm[Any]")
235 [builtins fixtures/primitives.pyi]
236 [typing fixtures/typing-full.pyi]
237
238 [case testNameOrDottedNameRecognizedInOtherSyntacticLocations]
239 import typing
240 from typing import List, TypeForm
241 list_of_typx: List[TypeForm] = [List | typing.Optional[str]]
242 typx: TypeForm = List | typing.Optional[str]
243 [builtins fixtures/primitives.pyi]
244 [typing fixtures/typing-full.pyi]
245
246 [case testInvalidNameOrDottedNameRecognizedInOtherSyntacticLocations]
247 from typing import List, TypeForm
248 list_of_typx1: List[TypeForm] = [NoSuchType] # E: Name "NoSuchType" is not defined
249 list_of_typx2: List[TypeForm] = [no_such_module.NoSuchType] # E: Name "no_such_module" is not defined
250 typx1: TypeForm = NoSuchType # E: Name "NoSuchType" is not defined
251 typx2: TypeForm = no_such_module.NoSuchType # E: Name "no_such_module" is not defined
252 [builtins fixtures/primitives.pyi]
253 [typing fixtures/typing-full.pyi]
254
255
256 -- Type Expression Context: Union[TypeForm, <non-TypeForm>]
257
258 [case testAcceptsTypeFormLiteralAssignedToUnionOfTypeFormAndNonStr]
259 from typing_extensions import TypeForm
260 typx_or_int1: TypeForm[int | None] | int = int | None # No error; interpret as TypeForm
261 typx_or_int2: TypeForm[int | None] | int = str | None # E: Incompatible types in assignment (expression has type "object", variable has type "TypeForm[int | None] | int")
262 typx_or_int3: TypeForm[int | None] | int = 1
263 typx_or_int4: TypeForm[int | None] | int = object() # E: Incompatible types in assignment (expression has type "object", variable has type "TypeForm[int | None] | int")
264 [builtins fixtures/primitives.pyi]
265 [typing fixtures/typing-full.pyi]
266
267 [case testAcceptsTypeFormLiteralAssignedToUnionOfTypeFormAndStr]
268 from typing_extensions import TypeForm
269 typx_or_str1: TypeForm[int | None] | str = 'int | None'
270 typx_or_str2: TypeForm[int | None] | str = 'str | None' # No error; interpret as str
271 typx_or_str3: TypeForm[int | None] | str = 'hello'
272 typx_or_str4: TypeForm[int | None] | str = object() # E: Incompatible types in assignment (expression has type "object", variable has type "TypeForm[int | None] | str")
273 [builtins fixtures/primitives.pyi]
274 [typing fixtures/typing-full.pyi]
275
276 [case testValueExpressionWithStringInTypeFormUnionContextEmitsConservativeWarning1]
277 from typing import List, TypeForm
278 list_of_typx1: List[TypeForm[int | None] | str] = ['int | None'] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.
279 list_of_typx2: List[TypeForm[int | None] | str] = ['str | None'] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.
280 [builtins fixtures/primitives.pyi]
281 [typing fixtures/typing-full.pyi]
282
283 [case testValueExpressionWithStringInTypeFormUnionContextEmitsConservativeWarning2]
284 from typing import List, TypeForm
285 list_of_typx3: List[TypeForm[int | None] | int] = ['int | None'] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
286 # E: List item 0 has incompatible type "str"; expected "TypeForm[int | None] | int"
287 list_of_typx4: List[TypeForm[str | None] | int] = ['str | None'] # E: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize. \
288 # E: List item 0 has incompatible type "str"; expected "TypeForm[str | None] | int"
289 [builtins fixtures/primitives.pyi]
290 [typing fixtures/typing-full.pyi]
291
292
293 -- Assignability (is_subtype)
294
295 [case testTypeFormToTypeFormAssignability]
296 # - TypeForm[T1] is assignable to TypeForm[T2] iff T1 is assignable to T2.
297 # - In particular TypeForm[Any] is assignable to TypeForm[Any].
298 from typing_extensions import TypeForm
299 INT_OR_STR_TF: TypeForm[int | str] = int | str
300 INT_TF: TypeForm[int] = int
301 STR_TF: TypeForm[str] = str
302 OBJECT_TF: TypeForm[object] = object
303 ANY_TF: TypeForm = object
304 reveal_type(ANY_TF) # N: Revealed type is "TypeForm[Any]"
305 typx1: TypeForm[int | str] = INT_OR_STR_TF
306 typx2: TypeForm[int | str] = INT_TF
307 typx3: TypeForm[int | str] = STR_TF
308 typx4: TypeForm[int | str] = OBJECT_TF # E: Incompatible types in assignment (expression has type "TypeForm[object]", variable has type "TypeForm[int | str]")
309 typx5: TypeForm[int | str] = ANY_TF # no error
310 typx6: TypeForm[int] = INT_OR_STR_TF # E: Incompatible types in assignment (expression has type "TypeForm[int | str]", variable has type "TypeForm[int]")
311 typx7: TypeForm[int] = INT_TF
312 typx8: TypeForm[int] = STR_TF # E: Incompatible types in assignment (expression has type "TypeForm[str]", variable has type "TypeForm[int]")
313 typx9: TypeForm[int] = OBJECT_TF # E: Incompatible types in assignment (expression has type "TypeForm[object]", variable has type "TypeForm[int]")
314 typx10: TypeForm[int] = ANY_TF # no error
315 [builtins fixtures/primitives.pyi]
316 [typing fixtures/typing-full.pyi]
317
318 [case testTypeToTypeFormAssignability]
319 # - Type[C] is assignable to TypeForm[T] iff C is assignable to T.
320 # - In particular Type[Any] is assignable to TypeForm[Any].
321 from typing import Type, TypeForm
322 INT_T: Type[int] = int
323 STR_T: Type[str] = str
324 OBJECT_T: Type[object] = object
325 ANY_T: Type = object
326 reveal_type(ANY_T) # N: Revealed type is "type[Any]"
327 typx1: TypeForm[int | str] = INT_T
328 typx2: TypeForm[int | str] = STR_T
329 typx3: TypeForm[int | str] = OBJECT_T # E: Incompatible types in assignment (expression has type "type[object]", variable has type "TypeForm[int | str]")
330 typx4: TypeForm[int | str] = ANY_T # no error
331 typx5: TypeForm[int] = INT_T
332 typx6: TypeForm[int] = STR_T # E: Incompatible types in assignment (expression has type "type[str]", variable has type "TypeForm[int]")
333 typx7: TypeForm[int] = OBJECT_T # E: Incompatible types in assignment (expression has type "type[object]", variable has type "TypeForm[int]")
334 typx8: TypeForm[int] = ANY_T # no error
335 [builtins fixtures/primitives.pyi]
336 [typing fixtures/typing-full.pyi]
337
338 [case testTypeFormToTypeAssignability]
339 # - TypeForm[T] is NOT assignable to Type[C].
340 # - In particular TypeForm[Any] is NOT assignable to Type[Any].
341 from typing import Type, TypeForm
342 INT_OR_STR_TF: TypeForm[int | str] = int | str
343 INT_TF: TypeForm[int] = int
344 STR_TF: TypeForm[str] = str
345 OBJECT_TF: TypeForm[object] = object
346 ANY_TF: TypeForm = object
347 reveal_type(ANY_TF) # N: Revealed type is "TypeForm[Any]"
348 typ1: Type[int] = INT_OR_STR_TF # E: Incompatible types in assignment (expression has type "TypeForm[int | str]", variable has type "type[int]")
349 typ2: Type[int] = INT_TF # E: Incompatible types in assignment (expression has type "TypeForm[int]", variable has type "type[int]")
350 typ3: Type[int] = STR_TF # E: Incompatible types in assignment (expression has type "TypeForm[str]", variable has type "type[int]")
351 typ4: Type[int] = OBJECT_TF # E: Incompatible types in assignment (expression has type "TypeForm[object]", variable has type "type[int]")
352 typ5: Type[int] = ANY_TF # E: Incompatible types in assignment (expression has type "TypeForm[Any]", variable has type "type[int]")
353 typ6: Type[object] = INT_OR_STR_TF # E: Incompatible types in assignment (expression has type "TypeForm[int | str]", variable has type "type[object]")
354 typ7: Type[object] = INT_TF # E: Incompatible types in assignment (expression has type "TypeForm[int]", variable has type "type[object]")
355 typ8: Type[object] = STR_TF # E: Incompatible types in assignment (expression has type "TypeForm[str]", variable has type "type[object]")
356 typ9: Type[object] = OBJECT_TF # E: Incompatible types in assignment (expression has type "TypeForm[object]", variable has type "type[object]")
357 typ10: Type[object] = ANY_TF # E: Incompatible types in assignment (expression has type "TypeForm[Any]", variable has type "type[object]")
358 [builtins fixtures/primitives.pyi]
359 [typing fixtures/typing-full.pyi]
360
361 # NOTE: This test doesn't involve TypeForm at all, but is still illustrative
362 # when compared with similarly structured TypeForm-related tests above.
363 [case testTypeToTypeAssignability]
364 # - Type[C1] is assignable to Type[C2] iff C1 is assignable to C2.
365 # - In particular Type[Any] is assignable to Type[Any].
366 from typing import Type
367 INT_T: Type[int] = int
368 STR_T: Type[str] = str
369 OBJECT_T: Type[object] = object
370 ANY_T: Type = object
371 reveal_type(ANY_T) # N: Revealed type is "type[Any]"
372 typ1: Type[int] = INT_T
373 typ2: Type[int] = STR_T # E: Incompatible types in assignment (expression has type "type[str]", variable has type "type[int]")
374 typ3: Type[int] = OBJECT_T # E: Incompatible types in assignment (expression has type "type[object]", variable has type "type[int]")
375 typ4: Type[int] = ANY_T # no error
376 typ5: Type[object] = INT_T
377 typ6: Type[object] = STR_T
378 typ7: Type[object] = OBJECT_T
379 typ8: Type[object] = ANY_T # no error
380 [builtins fixtures/primitives.pyi]
381 [typing fixtures/typing-full.pyi]
382
383 [case testTypeFormToObjectAssignability]
384 # - TypeForm[T] is assignable to object and Any.
385 from typing import Any, TypeForm
386 INT_TF: TypeForm[int] = int
387 OBJECT_TF: TypeForm[object] = object
388 ANY_TF: TypeForm = object
389 reveal_type(ANY_TF) # N: Revealed type is "TypeForm[Any]"
390 obj1: object = INT_TF
391 obj2: object = OBJECT_TF
392 obj3: object = ANY_TF
393 any1: Any = INT_TF
394 any2: Any = OBJECT_TF
395 any3: Any = ANY_TF
396 [builtins fixtures/primitives.pyi]
397 [typing fixtures/typing-full.pyi]
398
399
400 -- Join (join_types)
401
402 [case testTypeFormToTypeFormJoin]
403 # - TypeForm[T1] join TypeForm[T2] == TypeForm[T1 join T2]
404 from typing_extensions import TypeForm
405 class AB:
406 pass
407 class A(AB):
408 pass
409 class B(AB):
410 pass
411 A_TF: TypeForm[A] = A
412 B_TF: TypeForm[B] = B
413 reveal_type([A_TF, B_TF][0]) # N: Revealed type is "TypeForm[__main__.AB]"
414 [builtins fixtures/primitives.pyi]
415 [typing fixtures/typing-full.pyi]
416
417 [case testTypeToTypeFormJoin]
418 # - TypeForm[T1] join Type[T2] == TypeForm[T1 join T2]
419 from typing import Type, TypeForm
420 class AB:
421 pass
422 class A(AB):
423 pass
424 class B(AB):
425 pass
426 A_T: Type[A] = A
427 B_TF: TypeForm[B] = B
428 reveal_type([A_T, B_TF][0]) # N: Revealed type is "TypeForm[__main__.AB]"
429 [builtins fixtures/primitives.pyi]
430 [typing fixtures/typing-full.pyi]
431
432 [case testTypeFormToTypeJoin]
433 # - TypeForm[T1] join Type[T2] == TypeForm[T1 join T2]
434 from typing import Type, TypeForm
435 class AB:
436 pass
437 class A(AB):
438 pass
439 class B(AB):
440 pass
441 A_TF: TypeForm[A] = A
442 B_T: Type[B] = B
443 reveal_type([A_TF, B_T][0]) # N: Revealed type is "TypeForm[__main__.AB]"
444 [builtins fixtures/primitives.pyi]
445 [typing fixtures/typing-full.pyi]
446
447 # NOTE: This test doesn't involve TypeForm at all, but is still illustrative
448 # when compared with similarly structured TypeForm-related tests above.
449 [case testTypeToTypeJoin]
450 # - Type[T1] join Type[T2] == Type[T1 join T2]
451 from typing import Type, TypeForm
452 class AB:
453 pass
454 class A(AB):
455 pass
456 class B(AB):
457 pass
458 A_T: Type[A] = A
459 B_T: Type[B] = B
460 reveal_type([A_T, B_T][0]) # N: Revealed type is "type[__main__.AB]"
461 [builtins fixtures/primitives.pyi]
462 [typing fixtures/typing-full.pyi]
463
464
465 -- Meet (meet_types)
466
467 [case testTypeFormToTypeFormMeet]
468 # - TypeForm[T1] meet TypeForm[T2] == TypeForm[T1 meet T2]
469 from typing import Callable, TypeForm, TypeVar
470 class AB:
471 pass
472 class A(AB):
473 pass
474 class B(AB):
475 pass
476 class C(AB):
477 pass
478 T = TypeVar('T')
479 def f(x: Callable[[T, T], None]) -> T: pass # type: ignore[empty-body]
480 def g(x: TypeForm[A | B], y: TypeForm[B | C]) -> None: pass
481 reveal_type(f(g)) # N: Revealed type is "TypeForm[__main__.B]"
482 [builtins fixtures/primitives.pyi]
483 [typing fixtures/typing-full.pyi]
484
485 [case testTypeToTypeFormMeet]
486 # - TypeForm[T1] meet Type[T2] == Type[T1 meet T2]
487 from typing import Callable, Type, TypeForm, TypeVar
488 class AB:
489 pass
490 class A(AB):
491 pass
492 class B(AB):
493 pass
494 class C(AB):
495 pass
496 T = TypeVar('T')
497 def f(x: Callable[[T, T], None]) -> T: pass # type: ignore[empty-body]
498 def g(x: Type[B], y: TypeForm[B | C]) -> None: pass
499 reveal_type(f(g)) # N: Revealed type is "type[__main__.B]"
500 [builtins fixtures/primitives.pyi]
501 [typing fixtures/typing-full.pyi]
502
503 [case testTypeFormToTypeMeet]
504 # - TypeForm[T1] meet Type[T2] == Type[T1 meet T2]
505 from typing import Callable, Type, TypeForm, TypeVar
506 class AB:
507 pass
508 class A(AB):
509 pass
510 class B(AB):
511 pass
512 class C(AB):
513 pass
514 T = TypeVar('T')
515 def f(x: Callable[[T, T], None]) -> T: pass # type: ignore[empty-body]
516 def g(x: TypeForm[A | B], y: Type[B]) -> None: pass
517 reveal_type(f(g)) # N: Revealed type is "type[__main__.B]"
518 [builtins fixtures/primitives.pyi]
519 [typing fixtures/typing-full.pyi]
520
521 # NOTE: This test doesn't involve TypeForm at all, but is still illustrative
522 # when compared with similarly structured TypeForm-related tests above.
523 [case testTypeToTypeMeet]
524 # - Type[T1] meet Type[T2] == Type[T1 meet T2]
525 from typing import Callable, Type, TypedDict, TypeForm, TypeVar
526 class AB(TypedDict):
527 a: str
528 b: str
529 class BC(TypedDict):
530 b: str
531 c: str
532 T = TypeVar('T')
533 def f(x: Callable[[T, T], None]) -> T: pass # type: ignore[empty-body]
534 def g(x: Type[AB], y: Type[BC]) -> None: pass
535 reveal_type(f(g)) # N: Revealed type is "type[TypedDict({'b': builtins.str, 'c': builtins.str, 'a': builtins.str})]"
536 [builtins fixtures/primitives.pyi]
537 [typing fixtures/typing-full.pyi]
538
539
540 -- TypeForm(...) Expression
541
542 [case testTypeFormExpression]
543 from typing_extensions import TypeForm
544 tf1 = TypeForm(int | str)
545 reveal_type(tf1) # N: Revealed type is "TypeForm[builtins.int | builtins.str]"
546 tf2 = TypeForm('int | str')
547 reveal_type(tf2) # N: Revealed type is "TypeForm[builtins.int | builtins.str]"
548 tf3: TypeForm = TypeForm(int | str)
549 reveal_type(tf3) # N: Revealed type is "TypeForm[Any]"
550 tf4: TypeForm = TypeForm(1) # E: Invalid type: try using Literal[1] instead?
551 tf5: TypeForm = TypeForm(int) | TypeForm(str) # E: Incompatible types in assignment (expression has type "object", variable has type "TypeForm[Any]")
552 tf6: TypeForm = TypeForm(TypeForm(int) | TypeForm(str)) # E: TypeForm argument is not a type
553 [builtins fixtures/primitives.pyi]
554 [typing fixtures/typing-full.pyi]
555
556
557 -- isinstance
558
559 [case testTypeFormAndTypeIsinstance]
560 from typing_extensions import TypeForm
561 typx: TypeForm[str] = str
562 if isinstance(typx, type):
563 reveal_type(typx) # N: Revealed type is "type[builtins.str]"
564 else:
565 reveal_type(typx) # N: Revealed type is "TypeForm[builtins.str]"
566 [builtins fixtures/primitives.pyi]
567 [typing fixtures/typing-full.pyi]
568
569
570 -- Type Variables
571
572 [case testLinkTypeFormToTypeFormWithTypeVariable]
573 from typing_extensions import TypeForm, TypeVar
574 T = TypeVar('T')
575 def as_typeform(typx: TypeForm[T]) -> TypeForm[T]:
576 return typx
577 reveal_type(as_typeform(int | str)) # N: Revealed type is "TypeForm[builtins.int | builtins.str]"
578 [builtins fixtures/primitives.pyi]
579 [typing fixtures/typing-full.pyi]
580
581 [case testLinkTypeFormToTypeWithTypeVariable]
582 from typing import Type, TypeForm, TypeVar
583 T = TypeVar('T')
584 def as_type(typx: TypeForm[T]) -> Type[T] | None:
585 if isinstance(typx, type):
586 return typx
587 else:
588 return None
589 reveal_type(as_type(int | str)) # N: Revealed type is "type[builtins.int] | type[builtins.str] | None"
590 reveal_type(as_type(int)) # N: Revealed type is "type[builtins.int] | None"
591 [builtins fixtures/primitives.pyi]
592 [typing fixtures/typing-full.pyi]
593
594 [case testLinkTypeFormToInstanceWithTypeVariable]
595 from typing_extensions import TypeForm, TypeVar
596 T = TypeVar('T')
597 def as_instance(typx: TypeForm[T]) -> T | None:
598 if isinstance(typx, type):
599 return typx()
600 else:
601 return None
602 reveal_type(as_instance(int | str)) # N: Revealed type is "builtins.int | builtins.str | None"
603 reveal_type(as_instance(int)) # N: Revealed type is "builtins.int | None"
604 [builtins fixtures/primitives.pyi]
605 [typing fixtures/typing-full.pyi]
606
607 [case testLinkTypeFormToTypeIsWithTypeVariable]
608 from typing_extensions import TypeForm, TypeVar
609 from typing_extensions import TypeIs
610 T = TypeVar('T')
611 def isassignable(value: object, typx: TypeForm[T]) -> TypeIs[T]:
612 raise BaseException()
613 count: int | str = 1
614 if isassignable(count, int):
615 reveal_type(count) # N: Revealed type is "builtins.int"
616 else:
617 reveal_type(count) # N: Revealed type is "builtins.str"
618 [builtins fixtures/primitives.pyi]
619 [typing fixtures/typing-full.pyi]
620
621 [case testLinkTypeFormToTypeGuardWithTypeVariable]
622 from typing_extensions import TypeForm, TypeVar
623 from typing_extensions import TypeGuard
624 T = TypeVar('T')
625 def isassignable(value: object, typx: TypeForm[T]) -> TypeGuard[T]:
626 raise BaseException()
627 count: int | str = 1
628 if isassignable(count, int):
629 reveal_type(count) # N: Revealed type is "builtins.int"
630 else:
631 reveal_type(count) # N: Revealed type is "builtins.int | builtins.str"
632 [builtins fixtures/primitives.pyi]
633 [typing fixtures/typing-full.pyi]
634
635
636 -- Type Expressions Assignable To TypeForm Variable
637
638 [case testEveryKindOfTypeExpressionIsAssignableToATypeFormVariable]
639 # NOTE: Importing Callable from collections.abc also works OK
640 from typing import (
641 Any, Callable, Dict, List, Literal, NoReturn,
642 Optional, ParamSpec, Self, Type, TypeGuard, TypeVar, Union,
643 )
644 from typing_extensions import (
645 Annotated, Concatenate, LiteralString, Never, TypeAlias, TypeForm, TypeIs,
646 TypeVarTuple, Unpack,
647 )
648 #
649 class SomeClass:
650 pass
651 SomeTypeAlias: TypeAlias = SomeClass
652 SomeTypeVar = TypeVar('SomeTypeVar')
653 Ts = TypeVarTuple('Ts')
654 IntTuple: TypeAlias = tuple[int, Unpack[Ts]]
655 P = ParamSpec('P')
656 R = TypeVar('R')
657 #
658 typx: TypeForm
659 # Begin rules taken from: https://typing.python.org/en/latest/spec/annotations.html#grammar-token-expression-grammar-type_expression
660 # <Any>
661 typx = Any
662 class SelfBinder:
663 def bind_self(self) -> Self:
664 typx: TypeForm
665 # <Self> (valid only in some contexts)
666 typx = Self
667 return self
668 # <LiteralString>
669 typx = LiteralString
670 # <NoReturn>
671 typx = NoReturn
672 # <Never>
673 typx = Never
674 # <None>
675 typx = None
676 # name (where name must refer to a valid in-scope class)
677 typx = SomeClass
678 # name (where name must refer to a valid in-scope type alias)
679 typx = SomeTypeAlias
680 # name (where name must refer to a valid in-scope TypeVar)
681 # NOTE: Unbound TypeVar isn't currently accepted as a TypeForm. Is that OK?
682 typx = SomeTypeVar # E: Incompatible types in assignment (expression has type "TypeVar", variable has type "TypeForm[Any]")
683 # name '[' type_expression (',' type_expression)* ']'
684 typx = Dict[str, int]
685 # (TODO: Add: name '[' unpacked ']')
686 # (TODO: Add: name '[' type_expression_list (',' type_expression_list)* ']')
687 # name '[' '(' ')' ']' (denoting specialization with an empty TypeVarTuple)
688 typx = IntTuple[()]
689 # <Literal> '[' expression (',' expression) ']'
690 typx = Literal[1]
691 # type_expression '|' type_expression
692 typx = int | str
693 # <Optional> '[' type_expression ']'
694 typx = Optional[str]
695 # <Union> '[' type_expression (',' type_expression)* ']'
696 typx = Union[int, str]
697 # <type> '[' <Any> ']'
698 typx = type[Any]
699 # <type> '[' name ']' (where name must refer to a valid in-scope class)
700 typx = type[int]
701 # (TODO: Add: <type> '[' name ']' (where name must refer to a valid in-scope TypeVar))
702 # <Callable> '[' '...' ',' type_expression ']'
703 typx = Callable[..., str]
704 def bind_R(input: R) -> R:
705 typx: TypeForm
706 # <Callable> '[' name ',' type_expression ']' (where name must be a valid in-scope ParamSpec)
707 typx = Callable[P, R]
708 # <Callable> '[' <Concatenate> '[' (type_expression ',')+
709 # (name | '...') ']' ',' type_expression ']'
710 # (where name must be a valid in-scope ParamSpec)
711 typx = Callable[Concatenate[int, P], R]
712 return input
713 # <Callable> '[' '[' maybe_unpacked (',' maybe_unpacked)* ']' ',' type_expression ']'
714 typx = Callable[[int, str], None]
715 # <tuple> '[' '(' ')' ']' (representing an empty tuple)
716 typx = tuple[()]
717 # <tuple> '[' type_expression ',' '...' ']' (representing an arbitrary-length tuple)
718 typx = tuple[int, ...]
719 # <tuple> '[' maybe_unpacked (',' maybe_unpacked)* ']'
720 typx = tuple[int, str]
721 # <Annotated> '[' type_expression ',' expression (',' expression)* ']'
722 typx = Annotated[str, 'uppercase']
723 # <TypeGuard> '[' type_expression ']' (valid only in some contexts)
724 typx = TypeGuard[List[str]]
725 # <TypeIs> '[' type_expression ']' (valid only in some contexts)
726 typx = TypeIs[List[str]]
727 # string_annotation (must evaluate to a valid type_expression)
728 typx = 'int | str'
729 # End rules
730 [builtins fixtures/primitives.pyi]
731 [typing fixtures/typing-full.pyi]
732
733
734 -- Misc
735
736 [case testTypeFormHasAllObjectAttributesAndMethods]
737 from typing_extensions import TypeForm
738 typx: TypeForm[int | str] = int | str
739 print(typx.__class__) # OK
740 print(typx.__hash__()) # OK
741 obj: object = typx
742 [file builtins.py]
743 class object:
744 def __init__(self) -> None: pass
745 __class__: None
746 def __hash__(self) -> int: pass
747 def print(x):
748 raise BaseException()
749 class int: pass
750 class dict: pass
751 class str: pass
752 class type: pass
753 class tuple: pass
754 class ellipsis: pass
755 class BaseException: pass
756 class float: pass
757 [typing fixtures/typing-full.pyi]
758
759 [case testDottedTypeFormsAreRecognized]
760 from typing_extensions import TypeForm
761 import typing
762 class C1:
763 class C2:
764 pass
765 typx1: TypeForm[C1.C2] = C1.C2 # OK
766 typx2: TypeForm[typing.Any] = typing.Any # OK
767 [builtins fixtures/primitives.pyi]
768 [typing fixtures/typing-full.pyi]
769
770 -- mypy already refused to recognize TypeVars in value expressions before
771 -- the TypeForm feature was introduced.
772 [case testTypeVarTypeFormsAreOnlyRecognizedInStringAnnotation]
773 from typing import Generic, List, TypeForm, TypeVar
774 E = TypeVar('E')
775 class Box(Generic[E]):
776 def foo(self, e: E) -> None:
777 list_of_typx: List[TypeForm] = [E] # E: "E" is a type variable and only valid in type context
778 typx1: TypeForm = E # E: "E" is a type variable and only valid in type context
779 typx2: TypeForm = 'E'
780 [builtins fixtures/primitives.pyi]
781 [typing fixtures/typing-full.pyi]
782
783 [case testIncompleteTypeFormsAreNotRecognized]
784 from typing import Optional, TypeForm
785 typx: TypeForm = Optional # E: Incompatible types in assignment (expression has type "int", variable has type "TypeForm[Any]")
786 [builtins fixtures/primitives.pyi]
787 [typing fixtures/typing-full.pyi]