Debian Codegraph @

test-data/unit/check-type-aliases.test

raw
1 [case testSimpleTypeAlias]
2 import typing
3 i = int
4 def f(x: i) -> None: pass
5 f(1)
6 f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
7 [targets __main__, __main__.f]
8
9 [case testUnionTypeAlias]
10 from typing import Union
11 U = Union[int, str]
12 def f(x: U) -> None: pass
13 f(1)
14 f('')
15 f(()) # E: Argument 1 to "f" has incompatible type "tuple[()]"; expected "int | str"
16 [targets __main__, __main__.f]
17 [builtins fixtures/tuple.pyi]
18
19 [case testTupleTypeAlias]
20 from typing import Tuple
21 T = Tuple[int, str]
22 def f(x: T) -> None: pass
23 f((1, 'x'))
24 f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "tuple[int, str]"
25 [targets __main__, __main__.f]
26 [builtins fixtures/tuple.pyi]
27
28 [case testCallableTypeAlias]
29 from typing import Callable
30 A = Callable[[int], None]
31 f: A
32 f(1)
33 f('') # E: Argument 1 has incompatible type "str"; expected "int"
34 [targets __main__]
35
36 [case testListTypeAlias]
37 from typing import List
38 A = List[int]
39 def f(x: A) -> None: pass
40 f([1])
41 f(['x']) # E: List item 0 has incompatible type "str"; expected "int"
42 [builtins fixtures/list.pyi]
43 [targets __main__, __main__.f]
44
45 [case testAnyTypeAlias]
46 from typing import Any
47 A = Any
48 def f(x: A) -> None:
49 x.foo()
50 f(1)
51 f('x')
52
53 [case testNoReturnTypeAlias]
54 # https://github.com/python/mypy/issues/11903
55 from typing import NoReturn
56 Never = NoReturn
57 a: Never # Used to be an error here
58
59 def f(a: Never): ...
60 f(5) # E: Argument 1 to "f" has incompatible type "int"; expected "Never"
61 [case testImportUnionAlias]
62 import typing
63 from _m import U
64 def f(x: U) -> None: pass
65 f(1)
66 f('x')
67 f(()) # E: Argument 1 to "f" has incompatible type "tuple[()]"; expected "int | str"
68 [file _m.py]
69 from typing import Union
70 U = Union[int, str]
71 [builtins fixtures/tuple.pyi]
72
73 [case testProhibitReassigningAliases]
74 A = float
75 if int():
76 A = int # E: Cannot assign multiple types to name "A" without an explicit "type[...]" annotation
77 [out]
78
79 [case testProhibitReassigningSubscriptedAliases]
80 from typing import Callable
81 A = Callable[[], float]
82 if int():
83 A = Callable[[], int] \
84 # E: Cannot assign multiple types to name "A" without an explicit "type[...]" annotation \
85 # E: Value of type "int" is not indexable
86 # the second error is because of `Callable = 0` in lib-stub/typing.pyi
87 [builtins fixtures/list.pyi]
88 [out]
89
90 [case testProhibitReassigningGenericAliases]
91 from typing import TypeVar, Union, Tuple
92 T = TypeVar('T')
93
94 A = Tuple[T, T]
95 if int():
96 A = Union[T, int] # E: Cannot assign multiple types to name "A" without an explicit "type[...]" annotation
97 [builtins fixtures/tuple.pyi]
98 [typing fixtures/typing-full.pyi]
99
100 [case testProhibitUsingVariablesAsTypesAndAllowAliasesAsTypes]
101
102 from typing import TypeVar, Sequence, Type
103 T = TypeVar('T')
104
105 A: Type[float] = int
106 if int():
107 A = float # OK
108 x: A # E: Variable "__main__.A" is not valid as a type \
109 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
110 def bad(tp: A) -> None: # E: Variable "__main__.A" is not valid as a type \
111 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
112 pass
113
114 Alias = int
115 GenAlias = Sequence[T]
116 def fun(x: Alias) -> GenAlias[int]: pass
117 [out]
118
119 [case testCorrectQualifiedAliasesAlsoInFunctions]
120 from typing import TypeVar, Generic
121 T = TypeVar('T')
122 S = TypeVar('S')
123
124 class X(Generic[T]):
125 A = X[S]
126 def f(self) -> X[T]:
127 pass
128
129 a: X[T]
130 b: A = a
131 c: A[T] = a
132 d: A[int] = a # E: Incompatible types in assignment (expression has type "X[T]", variable has type "X[int]")
133
134 def g(self) -> None:
135 a: X[T]
136 b: X.A = a
137 c: X.A[T] = a
138 d: X.A[int] = a # E: Incompatible types in assignment (expression has type "X[T]", variable has type "X[int]")
139
140 def g(arg: X[int]) -> None:
141 p: X[int] = arg.f()
142 q: X.A = arg.f()
143 r: X.A[str] = arg.f() # E: Incompatible types in assignment (expression has type "X[int]", variable has type "X[str]")
144 [out]
145
146 [case testProhibitBoundTypeVariableReuseForAliases]
147 from typing import TypeVar, Generic, List
148 T = TypeVar('T')
149 class C(Generic[T]):
150 A = List[T] # E: Can't use bound type variable "T" to define generic alias
151
152 x: C.A
153 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
154
155 def f(x: T) -> T:
156 A = List[T] # E: Can't use bound type variable "T" to define generic alias
157 return x
158 [builtins fixtures/list.pyi]
159 [out]
160
161 [case testTypeAliasInBuiltins]
162 def f(x: bytes): pass
163 bytes
164 f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "str"
165 [builtins fixtures/alias.pyi]
166
167 [case testEmptyTupleTypeAlias]
168 from typing import Tuple, Callable
169 EmptyTuple = Tuple[()]
170 x: EmptyTuple
171 reveal_type(x) # N: Revealed type is "tuple[()]"
172
173 EmptyTupleCallable = Callable[[Tuple[()]], None]
174 f: EmptyTupleCallable
175 reveal_type(f) # N: Revealed type is "def (tuple[()])"
176 [builtins fixtures/list.pyi]
177
178 [case testForwardTypeAlias]
179 def f(p: 'Alias') -> None:
180 pass
181
182 reveal_type(f) # N: Revealed type is "def (p: builtins.int)"
183 Alias = int
184 [out]
185
186 [case testForwardTypeAliasGeneric]
187 from typing import TypeVar, Tuple
188 def f(p: 'Alias[str]') -> None:
189 pass
190
191 reveal_type(f) # N: Revealed type is "def (p: tuple[builtins.int, builtins.str])"
192 T = TypeVar('T')
193 Alias = Tuple[int, T]
194 [builtins fixtures/tuple.pyi]
195 [out]
196
197 [case testRecursiveAliasesErrors1]
198 from typing import Type, Callable, Union
199
200 def test() -> None:
201 A = Union[A, int] # E: Cannot resolve name "A" (possible cyclic definition) \
202 # N: Recursive types are not allowed at function scope
203 B = Callable[[B], int] # E: Cannot resolve name "B" (possible cyclic definition) \
204 # N: Recursive types are not allowed at function scope
205 C = Type[C] # E: Cannot resolve name "C" (possible cyclic definition) \
206 # N: Recursive types are not allowed at function scope
207
208 [case testRecursiveAliasesErrors2]
209 # flags: --disable-error-code=used-before-def
210 from typing import Type, Callable, Union
211
212 def test() -> None:
213 A = Union[B, int]
214 B = Callable[[C], int]
215 C = Type[A]
216 x: A
217 reveal_type(x)
218 [out]
219 main:5: error: Cannot resolve name "A" (possible cyclic definition)
220 main:5: note: Recursive types are not allowed at function scope
221 main:5: error: Cannot resolve name "B" (possible cyclic definition)
222 main:6: error: Cannot resolve name "B" (possible cyclic definition)
223 main:6: note: Recursive types are not allowed at function scope
224 main:6: error: Cannot resolve name "C" (possible cyclic definition)
225 main:7: error: Cannot resolve name "C" (possible cyclic definition)
226 main:7: note: Recursive types are not allowed at function scope
227 main:9: note: Revealed type is "Any | builtins.int"
228
229 [case testDoubleForwardAlias]
230 # flags: --disable-error-code=used-before-def
231 from typing import List
232 x: A
233 A = List[B]
234 B = List[int]
235 reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[builtins.int]]"
236 [builtins fixtures/list.pyi]
237 [out]
238
239 [case testDoubleForwardAliasWithNamedTuple]
240 # flags: --disable-error-code=used-before-def
241 from typing import List, NamedTuple
242 x: A
243 A = List[B]
244 class B(NamedTuple):
245 x: str
246 reveal_type(x[0].x) # N: Revealed type is "builtins.str"
247 [builtins fixtures/list.pyi]
248 [out]
249
250 [case testJSONAliasApproximation]
251 from typing import List, Union, Dict
252
253 def test() -> None:
254 x: JSON # E: Cannot resolve name "JSON" (possible cyclic definition) \
255 # N: Recursive types are not allowed at function scope
256 JSON = Union[int, str, List[JSON], Dict[str, JSON]] # E: Cannot resolve name "JSON" (possible cyclic definition) \
257 # N: Recursive types are not allowed at function scope
258 reveal_type(x) # N: Revealed type is "Any"
259 if isinstance(x, list):
260 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
261 [builtins fixtures/isinstancelist.pyi]
262 [out]
263
264 [case testForwardRefToTypeVar]
265 # flags: --disable-error-code=used-before-def
266
267 from typing import TypeVar, List
268 reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
269 a: A[int]
270 A = List[T]
271 T = TypeVar('T')
272 [builtins fixtures/list.pyi]
273 [out]
274
275 [case testFunctionForwardRefAlias]
276
277 from typing import List, TypeVar
278
279 T = TypeVar('T')
280
281 def f(x: T) -> List[T]:
282 y: A[T]
283 reveal_type(y) # N: Revealed type is "builtins.list[T`-1]"
284 return [x] + y
285
286 A = List[T]
287 [builtins fixtures/list.pyi]
288 [out]
289
290 [case testFunctionForwardRefAlias2]
291
292 from typing import List, TypeVar
293
294 def f() -> None:
295 X = List[int]
296 x: A[X]
297 reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[builtins.int]]"
298
299 T = TypeVar('T')
300 A = List[T]
301 [builtins fixtures/list.pyi]
302 [out]
303
304 [case testNoneAlias]
305 from typing import Union
306 void = type(None)
307 x: void
308 reveal_type(x) # N: Revealed type is "None"
309 y: Union[int, void]
310 reveal_type(y) # N: Revealed type is "builtins.int | None"
311 [builtins fixtures/bool.pyi]
312
313 [case testNoneAliasStrict]
314 from typing import Optional, Union
315 void = type(None)
316 x: int
317 y: Union[int, void]
318 z: Optional[int]
319 x = y # E: Incompatible types in assignment (expression has type "int | None", variable has type "int")
320 y = z
321 [builtins fixtures/bool.pyi]
322
323 [case testAliasToTupleAndCallable]
324 from typing import Callable, Tuple
325 C = Callable
326 T = Tuple
327 c: C
328 t: T
329 reveal_type(c) # N: Revealed type is "def (*Any, **Any) -> Any"
330 reveal_type(t) # N: Revealed type is "builtins.tuple[Any, ...]"
331 bad: C[int] # E: Bad number of arguments for type alias, expected 0, given 1
332 also_bad: T[int] # E: Bad number of arguments for type alias, expected 0, given 1
333 [builtins fixtures/tuple.pyi]
334
335 [case testAliasRefOnClass]
336 from typing import Generic, TypeVar, Type
337
338 T = TypeVar('T')
339 class C(Generic[T]):
340 pass
341
342 class N:
343 A = C[T]
344 B = C[int]
345
346 x: N.A[C]
347 reveal_type(x) # N: Revealed type is "__main__.C[__main__.C[Any]]"
348
349 xx = N.A[C]()
350 reveal_type(xx) # N: Revealed type is "__main__.C[__main__.C[Any]]"
351
352 y = N.A()
353 reveal_type(y) # N: Revealed type is "__main__.C[Any]"
354
355 M = N
356 b = M.A[int]()
357 reveal_type(b) # N: Revealed type is "__main__.C[builtins.int]"
358
359 n: Type[N]
360 w = n.B()
361 reveal_type(w) # N: Revealed type is "__main__.C[builtins.int]"
362 [out]
363
364 [case testTypeAliasesToNamedTuple]
365 from nt import C, D, E
366
367 A1 = C
368 A2 = D
369 A3 = E
370
371 class Cls:
372 A1 = C
373 A2 = D
374 A3 = E
375
376 A1('no') # E: Argument 1 to "C" has incompatible type "str"; expected "int"
377 a1 = A1(1)
378 reveal_type(a1) # N: Revealed type is "tuple[builtins.int, fallback=nt.C]"
379
380 A2(0) # E: Argument 1 to "D" has incompatible type "int"; expected "str"
381 a2 = A2('yes')
382 reveal_type(a2) # N: Revealed type is "tuple[builtins.str, fallback=nt.D]"
383
384 a3 = A3()
385 reveal_type(a3) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=nt.E]"
386
387 Cls.A1('no') # E: Argument 1 has incompatible type "str"; expected "int"
388 ca1 = Cls.A1(1)
389 reveal_type(ca1) # N: Revealed type is "tuple[builtins.int, fallback=nt.C]"
390
391 Cls.A2(0) # E: Argument 1 has incompatible type "int"; expected "str"
392 ca2 = Cls.A2('yes')
393 reveal_type(ca2) # N: Revealed type is "tuple[builtins.str, fallback=nt.D]"
394
395 ca3 = Cls.A3()
396 reveal_type(ca3) # N: Revealed type is "tuple[builtins.int, builtins.str, fallback=nt.E]"
397 [file nt.pyi]
398 from typing import NamedTuple, Tuple
399
400 class C(NamedTuple):
401 x: int
402
403 D = NamedTuple('D', [('y', str)])
404
405 class E(Tuple[int, str]):
406 pass
407 [builtins fixtures/tuple.pyi]
408 [out]
409
410 [case testTypeAliasesToAny]
411 from typing import Any
412
413 A = Any
414 A # this should not fail
415 [out]
416
417 [case testDoubleImportsOfAnAlias]
418 from b import *
419 from c import *
420 [file b.py]
421 from a import A
422 [file c.py]
423 from a import A
424 [file a.py]
425 A = int
426 [out]
427
428 [case testDoubleImportsOfAnAlias2]
429 from b import A
430 from c import A
431 [file b.py]
432 from a import A
433 [file c.py]
434 from a import A
435 [file a.py]
436 A = int
437 [out]
438
439 [case testDoubleImportsOfAnAlias3]
440 from b import *
441 from c import *
442 [file b.py]
443 from a import A
444 [file c.py]
445 from a import A
446 [file a.py]
447 from typing import Union
448 A = Union[None]
449 [out]
450
451 [case testAliasToClassMethod]
452 from typing import TypeVar, Generic, Union, Type
453
454 T = TypeVar('T', bound='C')
455
456 MYPY = False
457 if MYPY:
458 test = classmethod
459
460 class C:
461 @test
462 def meth(cls: Type[T], arg: int) -> Union[T, int]: ...
463
464 class D(C): ...
465
466 reveal_type(D.meth(1)) # N: Revealed type is "__main__.D | builtins.int"
467 reveal_type(D().meth(1)) # N: Revealed type is "__main__.D | builtins.int"
468 [builtins fixtures/classmethod.pyi]
469 [out]
470
471 [case testAliasInImportCycle]
472 # cmd: mypy -m t t2
473 [file t.py]
474 MYPY = False
475 if MYPY:
476 from t2 import A
477 x: A
478 [file t2.py]
479 import t
480 from typing import Callable
481 A = Callable[[], None]
482 [builtins fixtures/bool.pyi]
483 [out]
484
485 [case testAliasInImportCycle2]
486 import a
487 [file a.pyi]
488 from b import Parameter
489
490 class _ParamType:
491 p: Parameter
492
493 _ConvertibleType = _ParamType
494
495 def convert_type(ty: _ConvertibleType):
496 ...
497
498 [file b.pyi]
499 from a import _ConvertibleType
500
501 class Parameter:
502 type: _ConvertibleType
503 [out]
504
505 [case testAliasInImportCycle3]
506 # cmd: mypy -m t t2
507
508 [file t.py]
509 MYPY = False
510 if MYPY:
511 from t2 import A
512 x: A
513 reveal_type(x) # N: Revealed type is "t2.D"
514
515 reveal_type(A) # N: Revealed type is "def () -> t2.D"
516 A()
517 [file t2.py]
518 import t
519 class D: pass
520 A = D
521 [builtins fixtures/bool.pyi]
522 [out]
523
524 [case testFlexibleAlias1]
525 from typing import TypeVar, List, Tuple
526 from mypy_extensions import FlexibleAlias
527
528 T = TypeVar('T')
529 U = TypeVar('U')
530
531 AnInt = FlexibleAlias[T, int]
532
533 x: AnInt[str]
534 reveal_type(x) # N: Revealed type is "builtins.int"
535
536 TwoArgs = FlexibleAlias[Tuple[T, U], bool]
537 TwoArgs2 = FlexibleAlias[Tuple[T, U], List[U]]
538
539 def welp(x: TwoArgs[str, int]) -> None:
540 reveal_type(x) # N: Revealed type is "builtins.bool"
541
542 def welp2(x: TwoArgs2[str, int]) -> None:
543 reveal_type(x) # N: Revealed type is "builtins.list[builtins.int]"
544
545
546 Id = FlexibleAlias[T, T]
547
548 def take_id(x: Id[int]) -> None:
549 reveal_type(x) # N: Revealed type is "builtins.int"
550
551 def id(x: Id[T]) -> T:
552 return x
553
554 # TODO: This doesn't work and maybe it should?
555 # Indirection = AnInt[T]
556 # y: Indirection[str]
557 # reveal_type(y) # E : Revealed type is "builtins.int"
558
559 # But this does
560 Indirection2 = FlexibleAlias[T, AnInt[T]]
561 z: Indirection2[str]
562 reveal_type(z) # N: Revealed type is "builtins.int"
563
564 Indirection3 = FlexibleAlias[Tuple[T, U], AnInt[T]]
565 w: Indirection3[str, int]
566 reveal_type(w) # N: Revealed type is "builtins.int"
567
568 [builtins fixtures/dict.pyi]
569
570 [case testFlexibleAlias2]
571 # flags: --always-true=BOGUS
572 from typing import TypeVar, Any
573 from mypy_extensions import FlexibleAlias
574
575 T = TypeVar('T')
576
577 BOGUS = True
578 if BOGUS:
579 Bogus = FlexibleAlias[T, Any]
580 else:
581 Bogus = FlexibleAlias[T, T]
582
583 class A:
584 x: Bogus[str]
585
586 reveal_type(A().x) # N: Revealed type is "Any"
587
588 def foo(x: Bogus[int]) -> None:
589 reveal_type(x) # N: Revealed type is "Any"
590
591 [builtins fixtures/dict.pyi]
592
593 [case testFlexibleAlias3]
594 # flags: --always-false=BOGUS
595 from typing import TypeVar, Any
596 from mypy_extensions import FlexibleAlias
597
598 T = TypeVar('T')
599
600 BOGUS = True
601 if BOGUS:
602 Bogus = FlexibleAlias[T, Any]
603 else:
604 Bogus = FlexibleAlias[T, T]
605
606 class A:
607 x: Bogus[str]
608
609 reveal_type(A().x) # N: Revealed type is "builtins.str"
610
611 def foo(x: Bogus[int]) -> None:
612 reveal_type(x) # N: Revealed type is "builtins.int"
613
614 [builtins fixtures/dict.pyi]
615
616 [case testOverrideByIdemAliasCorrectType]
617 C = C
618 class C: # type: ignore
619 pass
620 x: C
621 reveal_type(x) # N: Revealed type is "__main__.C"
622 [out]
623
624 [case testOverrideByIdemAliasCorrectTypeReversed]
625 class C:
626 pass
627 C = C # type: ignore
628 x: C
629 reveal_type(x) # N: Revealed type is "__main__.C"
630 [out]
631
632 [case testOverrideByIdemAliasCorrectTypeImported]
633 from other import C as B
634 C = B
635 x: C
636 reveal_type(x) # N: Revealed type is "other.C"
637 [file other.py]
638 class C:
639 pass
640 [out]
641
642 [case testConditionalExceptionAlias]
643
644 try:
645 E = E
646 except BaseException:
647 class E(BaseException): pass # type: ignore
648
649 try:
650 pass
651 except E as e:
652 reveal_type(e) # N: Revealed type is "__main__.E"
653 [builtins fixtures/exception.pyi]
654 [out]
655
656 [case testNestedClassOnAliasAsType]
657 class Out:
658 class In:
659 class Inner:
660 pass
661
662 O = Out
663 I = Out.In
664 OI = O.In
665 A = Out
666 B = A
667
668 w: O.In
669 x: I.Inner
670 y: OI.Inner
671 z: B.In
672 reveal_type(w) # N: Revealed type is "__main__.Out.In"
673 reveal_type(x) # N: Revealed type is "__main__.Out.In.Inner"
674 reveal_type(y) # N: Revealed type is "__main__.Out.In.Inner"
675 reveal_type(z) # N: Revealed type is "__main__.Out.In"
676
677
678 [case testSimplePep613]
679 from typing_extensions import TypeAlias
680 x: TypeAlias = str
681 a: x
682 reveal_type(a) # N: Revealed type is "builtins.str"
683
684 y: TypeAlias = "str"
685 b: y
686 reveal_type(b) # N: Revealed type is "builtins.str"
687
688 z: TypeAlias = "int | str"
689 c: z
690 reveal_type(c) # N: Revealed type is "builtins.int | builtins.str"
691 [builtins fixtures/tuple.pyi]
692
693 [case testForwardRefPep613]
694 from typing_extensions import TypeAlias
695
696 x: TypeAlias = "MyClass"
697 a: x
698 reveal_type(a) # N: Revealed type is "__main__.MyClass"
699
700 class MyClass: ...
701 [builtins fixtures/tuple.pyi]
702
703 [case testInvalidPep613]
704 from typing_extensions import TypeAlias
705
706 x: TypeAlias = list(int) # E: Invalid type alias: expression is not a valid type \
707 # E: Too many arguments for "list"
708 a: x
709 [builtins fixtures/tuple.pyi]
710
711 [case testAliasedImportPep613]
712 import typing as tpp
713 import typing_extensions as tpx
714 from typing import TypeAlias as TPA
715 from typing_extensions import TypeAlias as TXA
716 import typing
717 import typing_extensions
718
719 Int1: tpp.TypeAlias = int
720 Int2: tpx.TypeAlias = int
721 Int3: TPA = int
722 Int4: TXA = int
723 Int5: typing.TypeAlias = int
724 Int6: typing_extensions.TypeAlias = int
725
726 x1: Int1 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
727 x2: Int2 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
728 x3: Int3 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
729 x4: Int4 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
730 x5: Int5 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
731 x6: Int6 = "str" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
732 [builtins fixtures/tuple.pyi]
733 [typing fixtures/typing-medium.pyi]
734
735 [case testFunctionScopePep613]
736 from typing_extensions import TypeAlias
737
738 def f() -> None:
739 x: TypeAlias = str
740 a: x
741 reveal_type(a) # N: Revealed type is "builtins.str"
742
743 y: TypeAlias = "str"
744 b: y
745 reveal_type(b) # N: Revealed type is "builtins.str"
746 [builtins fixtures/tuple.pyi]
747
748 [case testImportCyclePep613]
749 # cmd: mypy -m t t2
750 [file t.py]
751 MYPY = False
752 if MYPY:
753 from t2 import A
754 x: A
755 reveal_type(x) # N: Revealed type is "builtins.str"
756 [file t2.py]
757 from typing_extensions import TypeAlias
758 A: TypeAlias = str
759 [builtins fixtures/bool.pyi]
760 [out]
761
762
763 [case testLiteralStringPep675]
764 # flags: --python-version 3.11
765 from typing import LiteralString as tpLS
766 from typing_extensions import LiteralString as tpxLS
767
768 def f(a: tpLS, b: tpxLS) -> None:
769 reveal_type(a) # N: Revealed type is "builtins.str"
770 reveal_type(b) # N: Revealed type is "builtins.str"
771
772 # This isn't the correct behaviour, but should unblock use of LiteralString in typeshed
773 f("asdf", "asdf")
774 string: str
775 f(string, string)
776
777 [builtins fixtures/tuple.pyi]
778 [typing fixtures/typing-medium.pyi]
779
780 [case testForwardTypeVarRefWithRecursiveFlag]
781 import c
782 [file a.py]
783 from typing import TypeVar, List, Any, Generic
784 from b import Alias
785
786 T = TypeVar("T", bound=Alias[Any])
787 def foo(x: T) -> T: ...
788
789 [file b.py]
790 from c import C
791 from typing import TypeVar, List
792
793 S = TypeVar("S")
794 Alias = List[C[S]]
795
796 [file c.py]
797 from typing import TypeVar, List, Generic
798 import a
799
800 S = TypeVar("S")
801 class C(Generic[S], List[Defer]): ...
802 class Defer: ...
803 [builtins fixtures/list.pyi]
804
805 [case testClassLevelTypeAliasesInUnusualContexts]
806 from typing import Union
807 from typing_extensions import TypeAlias
808
809 class Foo: pass
810
811 NormalImplicit = Foo
812 NormalExplicit: TypeAlias = Foo
813 SpecialImplicit = Union[int, str]
814 SpecialExplicit: TypeAlias = Union[int, str]
815
816 class Parent:
817 NormalImplicit = Foo
818 NormalExplicit: TypeAlias = Foo
819 SpecialImplicit = Union[int, str]
820 SpecialExplicit: TypeAlias = Union[int, str]
821
822 class Child(Parent): pass
823
824 p = Parent()
825 c = Child()
826
827 # Use type aliases in a runtime context
828
829 reveal_type(NormalImplicit) # N: Revealed type is "def () -> __main__.Foo"
830 reveal_type(NormalExplicit) # N: Revealed type is "def () -> __main__.Foo"
831 reveal_type(SpecialImplicit) # N: Revealed type is "typing._SpecialForm"
832 reveal_type(SpecialExplicit) # N: Revealed type is "typing._SpecialForm"
833
834 reveal_type(Parent.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo"
835 reveal_type(Parent.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo"
836 reveal_type(Parent.SpecialImplicit) # N: Revealed type is "typing._SpecialForm"
837 reveal_type(Parent.SpecialExplicit) # N: Revealed type is "typing._SpecialForm"
838
839 reveal_type(Child.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo"
840 reveal_type(Child.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo"
841 reveal_type(Child.SpecialImplicit) # N: Revealed type is "typing._SpecialForm"
842 reveal_type(Child.SpecialExplicit) # N: Revealed type is "typing._SpecialForm"
843
844 reveal_type(p.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo"
845 reveal_type(p.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo"
846 reveal_type(p.SpecialImplicit) # N: Revealed type is "typing._SpecialForm"
847 reveal_type(p.SpecialExplicit) # N: Revealed type is "typing._SpecialForm"
848
849 reveal_type(c.NormalImplicit) # N: Revealed type is "def () -> __main__.Foo"
850 reveal_type(p.NormalExplicit) # N: Revealed type is "def () -> __main__.Foo"
851 reveal_type(c.SpecialImplicit) # N: Revealed type is "typing._SpecialForm"
852 reveal_type(c.SpecialExplicit) # N: Revealed type is "typing._SpecialForm"
853
854 # Use type aliases in a type alias context in a plausible way
855
856 def plausible_top_1() -> NormalImplicit: pass
857 def plausible_top_2() -> NormalExplicit: pass
858 def plausible_top_3() -> SpecialImplicit: pass
859 def plausible_top_4() -> SpecialExplicit: pass
860 reveal_type(plausible_top_1) # N: Revealed type is "def () -> __main__.Foo"
861 reveal_type(plausible_top_2) # N: Revealed type is "def () -> __main__.Foo"
862 reveal_type(plausible_top_3) # N: Revealed type is "def () -> builtins.int | builtins.str"
863 reveal_type(plausible_top_4) # N: Revealed type is "def () -> builtins.int | builtins.str"
864
865 def plausible_parent_1() -> Parent.NormalImplicit: pass # E: Variable "__main__.Parent.NormalImplicit" is not valid as a type \
866 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
867 def plausible_parent_2() -> Parent.NormalExplicit: pass
868 def plausible_parent_3() -> Parent.SpecialImplicit: pass
869 def plausible_parent_4() -> Parent.SpecialExplicit: pass
870 reveal_type(plausible_parent_1) # N: Revealed type is "def () -> Parent.NormalImplicit?"
871 reveal_type(plausible_parent_2) # N: Revealed type is "def () -> __main__.Foo"
872 reveal_type(plausible_parent_3) # N: Revealed type is "def () -> builtins.int | builtins.str"
873 reveal_type(plausible_parent_4) # N: Revealed type is "def () -> builtins.int | builtins.str"
874
875 def plausible_child_1() -> Child.NormalImplicit: pass # E: Variable "__main__.Parent.NormalImplicit" is not valid as a type \
876 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
877 def plausible_child_2() -> Child.NormalExplicit: pass
878 def plausible_child_3() -> Child.SpecialImplicit: pass
879 def plausible_child_4() -> Child.SpecialExplicit: pass
880 reveal_type(plausible_child_1) # N: Revealed type is "def () -> Child.NormalImplicit?"
881 reveal_type(plausible_child_2) # N: Revealed type is "def () -> __main__.Foo"
882 reveal_type(plausible_child_3) # N: Revealed type is "def () -> builtins.int | builtins.str"
883 reveal_type(plausible_child_4) # N: Revealed type is "def () -> builtins.int | builtins.str"
884
885 # Use type aliases in a type alias context in an implausible way
886
887 def weird_parent_1() -> p.NormalImplicit: pass # E: Name "p.NormalImplicit" is not defined
888 def weird_parent_2() -> p.NormalExplicit: pass # E: Name "p.NormalExplicit" is not defined
889 def weird_parent_3() -> p.SpecialImplicit: pass # E: Name "p.SpecialImplicit" is not defined
890 def weird_parent_4() -> p.SpecialExplicit: pass # E: Name "p.SpecialExplicit" is not defined
891 reveal_type(weird_parent_1) # N: Revealed type is "def () -> Any"
892 reveal_type(weird_parent_2) # N: Revealed type is "def () -> Any"
893 reveal_type(weird_parent_3) # N: Revealed type is "def () -> Any"
894 reveal_type(weird_parent_4) # N: Revealed type is "def () -> Any"
895
896 def weird_child_1() -> c.NormalImplicit: pass # E: Name "c.NormalImplicit" is not defined
897 def weird_child_2() -> c.NormalExplicit: pass # E: Name "c.NormalExplicit" is not defined
898 def weird_child_3() -> c.SpecialImplicit: pass # E: Name "c.SpecialImplicit" is not defined
899 def weird_child_4() -> c.SpecialExplicit: pass # E: Name "c.SpecialExplicit" is not defined
900 reveal_type(weird_child_1) # N: Revealed type is "def () -> Any"
901 reveal_type(weird_child_2) # N: Revealed type is "def () -> Any"
902 reveal_type(weird_child_3) # N: Revealed type is "def () -> Any"
903 reveal_type(weird_child_4) # N: Revealed type is "def () -> Any"
904 [builtins fixtures/tuple.pyi]
905 [typing fixtures/typing-medium.pyi]
906
907 [case testMalformedTypeAliasRuntimeReassignments]
908 from typing import Union
909 from typing_extensions import TypeAlias
910
911 class Foo: pass
912
913 NormalImplicit = Foo
914 NormalExplicit: TypeAlias = Foo
915 SpecialImplicit = Union[int, str]
916 SpecialExplicit: TypeAlias = Union[int, str]
917
918 class Parent:
919 NormalImplicit = Foo
920 NormalExplicit: TypeAlias = Foo
921 SpecialImplicit = Union[int, str]
922 SpecialExplicit: TypeAlias = Union[int, str]
923
924 class Child(Parent): pass
925
926 p = Parent()
927 c = Child()
928
929 NormalImplicit = 4 # E: Cannot assign multiple types to name "NormalImplicit" without an explicit "type[...]" annotation \
930 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
931 NormalExplicit = 4 # E: Cannot assign multiple types to name "NormalExplicit" without an explicit "type[...]" annotation \
932 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
933 SpecialImplicit = 4 # E: Cannot assign multiple types to name "SpecialImplicit" without an explicit "type[...]" annotation
934 SpecialExplicit = 4 # E: Cannot assign multiple types to name "SpecialExplicit" without an explicit "type[...]" annotation
935
936 Parent.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
937 Parent.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
938 Parent.SpecialImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "<typing special form>")
939 Parent.SpecialExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "<typing special form>")
940
941 Child.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
942 Child.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
943 Child.SpecialImplicit = 4
944 Child.SpecialExplicit = 4
945
946 p.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
947 p.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
948 p.SpecialImplicit = 4
949 p.SpecialExplicit = 4
950
951 c.NormalImplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
952 c.NormalExplicit = 4 # E: Incompatible types in assignment (expression has type "int", variable has type "type[Foo]")
953 c.SpecialImplicit = 4
954 c.SpecialExplicit = 4
955 [builtins fixtures/tuple.pyi]
956 [typing fixtures/typing-medium.pyi]
957
958 [case testNewStyleUnionInTypeAliasWithMalformedInstance]
959 from typing import List
960
961 A = List[int, str] | int # E: "list" expects 1 type argument, but 2 given
962 B = int | list[int, str] # E: "list" expects 1 type argument, but 2 given
963 a: A
964 b: B
965 reveal_type(a) # N: Revealed type is "builtins.list[Any] | builtins.int"
966 reveal_type(b) # N: Revealed type is "builtins.int | builtins.list[Any]"
967 [builtins fixtures/type.pyi]
968
969 [case testValidTypeAliasValues]
970 from typing import TypeVar, Generic, List
971
972 T = TypeVar("T", int, str)
973 S = TypeVar("S", int, bytes)
974
975 class C(Generic[T]): ...
976 class D(C[S]): ... # E: Invalid type argument value for "C"
977
978 U = TypeVar("U")
979 A = List[C[U]]
980 x: A[bytes] # E: Value of type variable "T" of "C" cannot be "bytes"
981
982 V = TypeVar("V", bound=int)
983 class E(Generic[V]): ...
984 B = List[E[U]]
985 y: B[str] # E: Type argument "str" of "E" must be a subtype of "int"
986
987 [case testValidTypeAliasValuesMoreRestrictive]
988 from typing import TypeVar, Generic, List
989
990 T = TypeVar("T")
991 S = TypeVar("S", int, str)
992 U = TypeVar("U", bound=int)
993
994 class C(Generic[T]): ...
995
996 A = List[C[S]]
997 x: A[int]
998 x_bad: A[bytes] # E: Value of type variable "S" of "A" cannot be "bytes"
999
1000 B = List[C[U]]
1001 y: B[int]
1002 y_bad: B[str] # E: Type argument "str" of "B" must be a subtype of "int"
1003
1004 [case testTupleWithDifferentArgs]
1005 Alias1 = tuple[float]
1006 Alias2 = tuple[float, float]
1007 Alias3 = tuple[float, ...]
1008 Alias4 = tuple[float, float, ...] # E: Unexpected "..."
1009 [builtins fixtures/tuple.pyi]
1010
1011 [case testTupleWithDifferentArgsStub]
1012 # https://github.com/python/mypy/issues/11098
1013 import tup
1014
1015 [file tup.pyi]
1016 Correct1 = str | tuple[float, float, str]
1017 Correct2 = tuple[float] | str
1018 Correct3 = tuple[float, ...] | str
1019 Correct4 = tuple[float, str] | str
1020 Correct5 = tuple[int, str]
1021 Correct6 = tuple[int, ...]
1022
1023 RHSAlias1: type = tuple[int, int]
1024 RHSAlias2: type = tuple[int]
1025 RHSAlias3: type = tuple[int, ...]
1026
1027 # Wrong:
1028
1029 WrongTypeElement = str | tuple[float, 1] # E: Invalid type: try using Literal[1] instead?
1030 WrongEllipsis = str | tuple[float, float, ...] # E: Unexpected "..."
1031 [builtins fixtures/tuple.pyi]
1032
1033 [case testCompiledNoCrashOnSingleItemUnion]
1034 # flags: --no-strict-optional
1035 from typing import Callable, Union, Generic, TypeVar
1036
1037 Alias = Callable[[], int]
1038
1039 T = TypeVar("T")
1040 class C(Generic[T]):
1041 attr: Union[Alias, None] = None
1042
1043 @classmethod
1044 def test(cls) -> None:
1045 cls.attr
1046 [builtins fixtures/classmethod.pyi]
1047
1048 [case testRecursiveAliasTuple]
1049 from typing_extensions import TypeAlias
1050 from typing import Literal, Tuple, Union
1051
1052 Expr: TypeAlias = Union[
1053 Tuple[Literal[123], int],
1054 Tuple[Literal[456], "Expr"],
1055 ]
1056
1057 def eval(e: Expr) -> int:
1058 if e[0] == 123:
1059 return e[1]
1060 elif e[0] == 456:
1061 return -eval(e[1])
1062 [builtins fixtures/dict-full.pyi]
1063
1064 [case testTypeAliasType]
1065 from typing import Union
1066 from typing_extensions import TypeAliasType
1067
1068 TestType = TypeAliasType("TestType", Union[int, str])
1069 x: TestType = 42
1070 y: TestType = 'a'
1071 z: TestType = object() # E: Incompatible types in assignment (expression has type "object", variable has type "int | str")
1072
1073 TA = TypeAliasType("TA", value=int)
1074 a: TA = 1
1075 b: TA = 's' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1076
1077 TA2 = TypeAliasType("TA2", type_params=(), value=int) # shuffled arguments
1078 a2: TA2 = 1
1079 b2: TA2 = 's' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1080
1081 reveal_type(TestType) # N: Revealed type is "typing_extensions.TypeAliasType"
1082 TestType() # E: "TypeAliasType" not callable
1083
1084 class A:
1085 ClassAlias = TypeAliasType("ClassAlias", int)
1086 xc: A.ClassAlias = 1
1087 yc: A.ClassAlias = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1088 [builtins fixtures/tuple.pyi]
1089 [typing fixtures/typing-full.pyi]
1090
1091 [case testTypeAliasTypePython311]
1092 # flags: --python-version 3.11
1093 # Pinning to 3.11, because 3.12 has `TypeAliasType`
1094 from typing_extensions import TypeAliasType
1095
1096 TestType = TypeAliasType("TestType", int)
1097 x: TestType = 1
1098 [builtins fixtures/tuple.pyi]
1099
1100 [case testTypeAliasTypeInvalid]
1101 from typing_extensions import TypeAliasType
1102
1103 TestType = TypeAliasType("T", int) # E: String argument 1 "T" to TypeAliasType(...) does not match variable name "TestType"
1104
1105 T1 = T2 = TypeAliasType("T", int)
1106 t1: T1 # E: Variable "__main__.T1" is not valid as a type \
1107 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
1108
1109 T3 = TypeAliasType("T3", -1) # E: Invalid type: try using Literal[-1] instead?
1110 t3: T3
1111 reveal_type(t3) # N: Revealed type is "Any"
1112
1113 T4 = TypeAliasType("T4") # E: Missing positional argument "value" in call to "TypeAliasType"
1114 T5 = TypeAliasType("T5", int, str) # E: Too many positional arguments for "TypeAliasType" \
1115 # N: "TypeAliasType" defined in "typing_extensions" \
1116 # E: Argument 3 to "TypeAliasType" has incompatible type "type[str]"; expected "tuple[TypeVar? | ParamSpec? | TypeVarTuple?, ...]"
1117 [builtins fixtures/tuple.pyi]
1118 [typing fixtures/typing-full.pyi]
1119
1120 [case testTypeAliasTypeGeneric]
1121 from typing import Callable, Dict, Generic, TypeVar, Tuple
1122 from typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec, Unpack
1123
1124 K = TypeVar('K')
1125 V = TypeVar('V')
1126 T = TypeVar('T')
1127 Ts = TypeVarTuple("Ts")
1128 Ts1 = TypeVarTuple("Ts1")
1129 P = ParamSpec("P")
1130
1131 TestType = TypeAliasType("TestType", Dict[K, V], type_params=(K, V))
1132 x: TestType[int, str] = {1: 'a'}
1133 y: TestType[str, int] = {'a': 1}
1134 z: TestType[str, int] = {1: 'a'} # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "int"
1135 w: TestType[int] # E: Bad number of arguments for type alias, expected 2, given 1
1136
1137 InvertedDict = TypeAliasType("InvertedDict", Dict[K, V], type_params=(V, K))
1138 xi: InvertedDict[str, int] = {1: 'a'}
1139 yi: InvertedDict[str, int] = {'a': 1} # E: Dict entry 0 has incompatible type "str": "int"; expected "int": "str"
1140 zi: InvertedDict[int, str] = {1: 'a'} # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "int"
1141 reveal_type(xi) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
1142
1143 VariadicAlias1 = TypeAliasType("VariadicAlias1", Tuple[Unpack[Ts]], type_params=(Ts,))
1144 VariadicAlias2 = TypeAliasType("VariadicAlias2", Tuple[Unpack[Ts], K], type_params=(Ts, K))
1145 VariadicAlias3 = TypeAliasType("VariadicAlias3", Callable[[Unpack[Ts]], int], type_params=(Ts,))
1146 xv: VariadicAlias1[int, str] = (1, 'a')
1147 yv: VariadicAlias1[str, int] = (1, 'a') # E: Incompatible types in assignment (expression has type "tuple[int, str]", variable has type "tuple[str, int]")
1148 zv: VariadicAlias2[int, str] = (1, 'a')
1149 def int_in_int_out(x: int) -> int: return x
1150 wv: VariadicAlias3[int] = int_in_int_out
1151 reveal_type(wv) # N: Revealed type is "def (builtins.int) -> builtins.int"
1152
1153 ParamAlias = TypeAliasType("ParamAlias", Callable[P, int], type_params=(P,))
1154 def f(x: str, y: float) -> int: return 1
1155 def g(x: int, y: float) -> int: return 1
1156 xp1: ParamAlias[str, float] = f
1157 xp2: ParamAlias[str, float] = g # E: Incompatible types in assignment (expression has type "Callable[[int, float], int]", variable has type "Callable[[str, float], int]")
1158 xp3: ParamAlias[str, float] = lambda x, y: 1
1159
1160 class G(Generic[P, T]): ...
1161 ParamAlias2 = TypeAliasType("ParamAlias2", G[P, T], type_params=(P, T))
1162 xp: ParamAlias2[[int], str]
1163 reveal_type(xp) # N: Revealed type is "__main__.G[[builtins.int], builtins.str]"
1164 [builtins fixtures/dict.pyi]
1165 [typing fixtures/typing-full.pyi]
1166
1167 [case testTypeAliasTypeInvalidGeneric_no_native_parse]
1168 from typing_extensions import TypeAliasType, TypeVarTuple, ParamSpec
1169 from typing import Callable, Dict, Generic, TypeVar, Tuple, Unpack
1170
1171 K = TypeVar('K')
1172 V = TypeVar('V')
1173 T = TypeVar('T')
1174 Ts = TypeVarTuple("Ts")
1175 Ts1 = TypeVarTuple("Ts1")
1176 P = ParamSpec("P")
1177
1178 Ta0 = TypeAliasType("Ta0", int, type_params=(T, T)) # E: Duplicate type variable "T" in type_params argument to TypeAliasType
1179
1180 Ta1 = TypeAliasType("Ta1", int, type_params=K) # E: Tuple literal expected as the type_params argument to TypeAliasType
1181
1182 Ta2 = TypeAliasType("Ta2", int, type_params=(None,)) # E: Free type variable expected in type_params argument to TypeAliasType
1183
1184 Ta3 = TypeAliasType("Ta3", Dict[K, V], type_params=(V,)) # E: Type variable "K" is not included in type_params
1185 partially_generic1: Ta3[int] = {"a": 1}
1186 reveal_type(partially_generic1) # N: Revealed type is "builtins.dict[Any, builtins.int]"
1187 partially_generic2: Ta3[int] = {1: "a"} # E: Dict entry 0 has incompatible type "int": "str"; expected "Any": "int"
1188
1189 Ta4 = TypeAliasType("Ta4", Tuple[Unpack[Ts]], type_params=(Ts, Ts1)) # E: Can only use one TypeVarTuple in type_params argument to TypeAliasType
1190
1191 Ta5 = TypeAliasType("Ta5", Dict) # Unlike old style aliases, this is not generic
1192 non_generic_dict: Ta5[int, str] # E: Bad number of arguments for type alias, expected 0, given 2
1193 reveal_type(non_generic_dict) # N: Revealed type is "builtins.dict[Any, Any]"
1194
1195 Ta6 = TypeAliasType("Ta6", Tuple[Unpack[Ts]]) # E: TypeVarTuple "Ts" is not included in type_params
1196 unbound_tvt_alias: Ta6[int] # E: Bad number of arguments for type alias, expected 0, given 1
1197 reveal_type(unbound_tvt_alias) # N: Revealed type is "builtins.tuple[Any, ...]"
1198
1199 class G(Generic[P, T]): ...
1200 Ta7 = TypeAliasType("Ta7", G[P, T]) # E: ParamSpec "P" is not included in type_params \
1201 # E: Type variable "T" is not included in type_params
1202 unbound_ps_alias: Ta7[[int], str] # E: Bracketed expression "[...]" is not valid as a type \
1203 # N: Did you mean "List[...]"? \
1204 # E: Bad number of arguments for type alias, expected 0, given 2
1205 reveal_type(unbound_ps_alias) # N: Revealed type is "__main__.G[Any, Any]"
1206
1207 Ta8 = TypeAliasType("Ta8", Callable[P, int]) # E: ParamSpec "P" is not included in type_params
1208 unbound_ps_alias2: Ta8[int] # E: Bad number of arguments for type alias, expected 0, given 1
1209 reveal_type(unbound_ps_alias2) # N: Revealed type is "def [P] (*Any, **Any) -> builtins.int"
1210
1211 Ta9 = TypeAliasType("Ta9", Callable[P, T]) # E: ParamSpec "P" is not included in type_params \
1212 # E: Type variable "T" is not included in type_params
1213 unbound_ps_alias3: Ta9[int, str] # E: Bad number of arguments for type alias, expected 0, given 2
1214 reveal_type(unbound_ps_alias3) # N: Revealed type is "def [P] (*Any, **Any) -> Any"
1215
1216 Ta10 = TypeAliasType("Ta10", Callable[[Unpack[Ts]], str]) # E: TypeVarTuple "Ts" is not included in type_params
1217 unbound_tvt_alias2: Ta10[int] # E: Bad number of arguments for type alias, expected 0, given 1
1218 reveal_type(unbound_tvt_alias2) # N: Revealed type is "def (*Any) -> builtins.str"
1219
1220 class A(Generic[T]):
1221 Ta11 = TypeAliasType("Ta11", Dict[str, T], type_params=(T,)) # E: Can't use bound type variable "T" to define generic alias
1222 x: A.Ta11 = {"a": 1}
1223 reveal_type(x) # N: Revealed type is "builtins.dict[builtins.str, Any]"
1224 [builtins fixtures/dict.pyi]
1225 [typing fixtures/typing-full.pyi]
1226
1227 [case testTypeAliasTypeNoUnpackInTypeParams311]
1228 # flags: --python-version 3.11
1229 from typing_extensions import TypeAliasType, TypeVar, TypeVarTuple, Unpack
1230
1231 T = TypeVar("T")
1232 Ts = TypeVarTuple("Ts")
1233
1234 Ta1 = TypeAliasType("Ta1", None, type_params=(*Ts,)) # E: can't use starred expression here
1235 Ta2 = TypeAliasType("Ta2", None, type_params=(Unpack[Ts],)) # E: Free type variable expected in type_params argument to TypeAliasType \
1236 # N: Don't Unpack type variables in type_params
1237
1238 [builtins fixtures/tuple.pyi]
1239
1240 [case testAliasInstanceNameClash]
1241 from lib import func
1242 class A: ...
1243 func(A()) # E: Argument 1 to "func" has incompatible type "__main__.A"; expected "lib.A"
1244 [file lib.py]
1245 from typing import List, Union
1246
1247 A = Union[int, List[A]]
1248 def func(x: A) -> int: ...
1249 [builtins fixtures/tuple.pyi]
1250
1251 [case testAliasNonGeneric]
1252 from typing_extensions import TypeAlias
1253 class Foo: ...
1254
1255 ImplicitFoo = Foo
1256 ExplicitFoo: TypeAlias = Foo
1257
1258 x1: ImplicitFoo[str] # E: "Foo" expects no type arguments, but 1 given
1259 x2: ExplicitFoo[str] # E: "Foo" expects no type arguments, but 1 given
1260
1261 def is_foo(x: object):
1262 if isinstance(x, ImplicitFoo):
1263 pass
1264 if isinstance(x, ExplicitFoo):
1265 pass
1266
1267 [builtins fixtures/tuple.pyi]
1268
1269 [case testAliasExplicitNoArgsTuple]
1270 from typing import Any, Tuple, assert_type
1271 from typing_extensions import TypeAlias
1272
1273 Implicit = Tuple
1274 Explicit: TypeAlias = Tuple
1275
1276 x1: Implicit[str] # E: Bad number of arguments for type alias, expected 0, given 1
1277 x2: Explicit[str] # E: Bad number of arguments for type alias, expected 0, given 1
1278 assert_type(x1, Tuple[Any, ...])
1279 assert_type(x2, Tuple[Any, ...])
1280 [builtins fixtures/tuple.pyi]
1281
1282 [case testAliasExplicitNoArgsCallable]
1283 from typing import Any, Callable, assert_type
1284 from typing_extensions import TypeAlias
1285
1286 Implicit = Callable
1287 Explicit: TypeAlias = Callable
1288
1289 x1: Implicit[str] # E: Bad number of arguments for type alias, expected 0, given 1
1290 x2: Explicit[str] # E: Bad number of arguments for type alias, expected 0, given 1
1291 assert_type(x1, Callable[..., Any])
1292 assert_type(x2, Callable[..., Any])
1293 [builtins fixtures/tuple.pyi]
1294
1295 [case testExplicitTypeAliasToSameNameOuterProhibited]
1296 from typing import TypeVar, Generic
1297 from typing_extensions import TypeAlias
1298
1299 T = TypeVar("T")
1300 class Foo(Generic[T]):
1301 bar: Bar[T]
1302
1303 class Bar(Generic[T]):
1304 Foo: TypeAlias = Foo[T] # E: Can't use bound type variable "T" to define generic alias
1305 [builtins fixtures/tuple.pyi]
1306
1307 [case testExplicitTypeAliasToSameNameOuterAllowed]
1308 from typing import TypeVar, Generic
1309 from typing_extensions import TypeAlias
1310
1311 T = TypeVar("T")
1312 class Foo(Generic[T]):
1313 bar: Bar[T]
1314
1315 U = TypeVar("U")
1316 class Bar(Generic[T]):
1317 Foo: TypeAlias = Foo[U]
1318 var: Foo[T]
1319 x: Bar[int]
1320 reveal_type(x.var.bar) # N: Revealed type is "__main__.Bar[builtins.int]"
1321 [builtins fixtures/tuple.pyi]
1322
1323 [case testExplicitTypeAliasClassVarProhibited]
1324 from typing import ClassVar
1325 from typing_extensions import TypeAlias
1326
1327 Foo: TypeAlias = ClassVar[int] # E: ClassVar[...] can't be used inside a type alias
1328 [builtins fixtures/tuple.pyi]
1329
1330 [case testAnnotatedWithCallableAsParameterTypeAlias]
1331 from typing_extensions import Annotated, TypeAlias
1332
1333 def something() -> None: ...
1334
1335 A: TypeAlias = list[Annotated[str, something()]]
1336 a: A
1337 reveal_type(a) # N: Revealed type is "builtins.list[builtins.str]"
1338 [builtins fixtures/tuple.pyi]
1339
1340 [case testAnnotatedWithCallableAsParameterTypeAliasDeeper]
1341 from typing_extensions import Annotated, TypeAlias
1342
1343 def something() -> None: ...
1344
1345 A: TypeAlias = list[Annotated[Annotated[str, something()], something()]]
1346 a: A
1347 reveal_type(a) # N: Revealed type is "builtins.list[builtins.str]"
1348 [builtins fixtures/tuple.pyi]
1349
1350 [case testTypeAliasDict]
1351 D = dict[str, int]
1352 d = D()
1353 reveal_type(d) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
1354 reveal_type(D()) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
1355 reveal_type(D(x=1)) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
1356 reveal_type(D(x="asdf")) # E: No overload variant of "dict" matches argument type "str" \
1357 # N: Possible overload variants: \
1358 # N: def dict(**kwargs: int) -> dict[str, int] \
1359 # N: def dict(arg: Iterable[tuple[str, int]], **kwargs: int) -> dict[str, int] \
1360 # N: Revealed type is "Any"
1361 [builtins fixtures/dict.pyi]
1362
1363 [case testTypeAliasesInCyclicImport1]
1364 import p.aliases
1365
1366 [file p/__init__.py]
1367 [file p/aliases.py]
1368 from typing_extensions import TypeAlias
1369 from .defs import C, Alias1
1370
1371 Alias2: TypeAlias = Alias1[C]
1372
1373 [file p/defs.py]
1374 from typing import TypeVar
1375 from typing_extensions import TypeAlias
1376 import p.aliases
1377
1378 C = TypeVar("C", bound="SomeClass")
1379 Alias1: TypeAlias = C
1380
1381 class SomeClass:
1382 pass
1383 [builtins fixtures/tuple.pyi]
1384 [typing fixtures/typing-full.pyi]
1385
1386 [case testTypeAliasesInCyclicImport2]
1387 import p.aliases
1388
1389 [file p/__init__.py]
1390 [file p/aliases.py]
1391 from typing_extensions import TypeAlias
1392 from .defs import C, Alias1
1393
1394 Alias2: TypeAlias = Alias1[C]
1395
1396 [file p/defs.py]
1397 from typing import TypeVar, Union
1398 from typing_extensions import TypeAlias
1399 import p.aliases
1400
1401 C = TypeVar("C", bound="SomeClass")
1402 Alias1: TypeAlias = Union[C, int]
1403
1404 class SomeClass:
1405 pass
1406 [builtins fixtures/tuple.pyi]
1407
1408 [case testTypeAliasesInCyclicImport3]
1409 import p.aliases
1410
1411 [file p/__init__.py]
1412 [file p/aliases.py]
1413 from typing_extensions import TypeAlias
1414 from .defs import C, Alias1
1415
1416 Alias2: TypeAlias = Alias1[C]
1417
1418 [file p/defs.py]
1419 from typing import TypeVar
1420 from typing_extensions import TypeAlias
1421 import p.aliases
1422
1423 C = TypeVar("C", bound="list[SomeClass]")
1424 Alias1: TypeAlias = C
1425
1426 class SomeClass:
1427 pass
1428 [builtins fixtures/tuple.pyi]
1429 [typing fixtures/typing-full.pyi]
1430
1431 [case testTypeAliasesInCyclicImport4]
1432 import p.aliases
1433
1434 [file p/__init__.py]
1435 [file p/aliases.py]
1436 from typing_extensions import TypeAlias
1437 from .defs import C, Alias1
1438
1439 Alias2: TypeAlias = Alias1[C]
1440
1441 [file p/defs.py]
1442 from typing import TypeVar, Union
1443 from typing_extensions import TypeAlias
1444 import p.aliases
1445
1446 C = TypeVar("C", bound="list[SomeClass]")
1447 Alias1: TypeAlias = Union[C, int]
1448
1449 class SomeClass:
1450 pass
1451 [builtins fixtures/tuple.pyi]