Debian Codegraph @

test-data/unit/check-generics.test

raw
1 -- Simple generic types
2 -- --------------------
3
4
5 [case testGenericMethodReturnType]
6 from typing import TypeVar, Generic
7 T = TypeVar('T')
8 a: A[B]
9 b: B
10 c: C
11 if int():
12 c = a.f() # E: Incompatible types in assignment (expression has type "B", variable has type "C")
13 b = a.f()
14
15 class A(Generic[T]):
16 def f(self) -> T: pass
17
18 class B: pass
19 class C: pass
20 [builtins fixtures/tuple.pyi]
21
22 [case testGenericMethodArgument]
23 from typing import TypeVar, Generic
24 T = TypeVar('T')
25
26 class A(Generic[T]):
27 def f(self, a: T) -> None: pass
28
29 a: A[B]
30 b: B
31 c: C
32
33 a.f(c) # E: Argument 1 to "f" of "A" has incompatible type "C"; expected "B"
34 a.f(b)
35
36 class B: pass
37 class C: pass
38 [case testGenericMemberVariable]
39 from typing import TypeVar, Generic
40 T = TypeVar('T')
41 class A(Generic[T]):
42 def __init__(self, v: T) -> None:
43 self.v = v
44
45 a: A[B]
46 b: B
47 c: C
48 a.v = c # Fail
49 a.v = b
50
51 class B: pass
52 class C: pass
53 [builtins fixtures/tuple.pyi]
54 [out]
55 main:10: error: Incompatible types in assignment (expression has type "C", variable has type "B")
56
57 [case testGenericMemberVariable2]
58 from typing import TypeVar, Generic
59 T = TypeVar('T')
60 a: A[B]
61 b: B
62 c: C
63 a.v = c # Fail
64 a.v = b
65
66 class A(Generic[T]):
67 v: T
68 class B: pass
69 class C: pass
70 [builtins fixtures/tuple.pyi]
71 [out]
72 main:6: error: Incompatible types in assignment (expression has type "C", variable has type "B")
73
74 [case testSimpleGenericSubtyping]
75 from typing import TypeVar, Generic
76 T = TypeVar('T')
77 b: A[B]
78 bb: A[B]
79 c: A[C]
80 if int():
81 c = b # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
82 b = c # E: Incompatible types in assignment (expression has type "A[C]", variable has type "A[B]")
83
84 if int():
85 b = b
86 if int():
87 b = bb
88
89 class A(Generic[T]): pass
90 class B: pass
91 class C(B): pass
92 [builtins fixtures/tuple.pyi]
93
94 [case testGenericTypeCompatibilityWithAny]
95 from typing import Any, TypeVar, Generic
96 T = TypeVar('T')
97 b: A[B]
98 c: A[C]
99 d: A[Any]
100
101 b = d
102 c = d
103 d = b
104 d = c
105
106 class A(Generic[T]): pass
107 class B: pass
108 class C(B): pass
109 [builtins fixtures/tuple.pyi]
110 [out]
111
112 [case testTypeVariableAsTypeArgument]
113 from typing import TypeVar, Generic
114 T = TypeVar('T')
115 a: A[B]
116 b: A[B]
117 c: A[C]
118
119 a.v = c # E: Incompatible types in assignment (expression has type "A[C]", variable has type "A[B]")
120 if int():
121 c = a.v # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
122 a.v = b
123 if int():
124 b = a.v
125
126 class A(Generic[T]):
127 v: A[T]
128
129 class B: pass
130 class C: pass
131
132 [case testMultipleGenericTypeParametersWithMemberVars]
133 from typing import TypeVar, Generic
134 S = TypeVar('S')
135 T = TypeVar('T')
136 a: A[B, C]
137 s: B
138 t: C
139
140 if int():
141 t = a.s # E: Incompatible types in assignment (expression has type "B", variable has type "C")
142 s = a.t # E: Incompatible types in assignment (expression has type "C", variable has type "B")
143
144 if int():
145 s = a.s
146 t = a.t
147
148 class A(Generic[S, T]):
149 s: S
150 t: T
151 class B: pass
152 class C: pass
153
154 [case testMultipleGenericTypeParametersWithMethods]
155 from typing import TypeVar, Generic
156 S = TypeVar('S')
157 T = TypeVar('T')
158 a: A[B, C]
159 s: B
160 t: C
161
162 a.f(s, s) # Fail
163 a.f(t, t) # Fail
164 a.f(s, t)
165
166 class A(Generic[S, T]):
167 def f(self, s: S, t: T) -> None: pass
168 class B: pass
169 class C: pass
170 [out]
171 main:8: error: Argument 2 to "f" of "A" has incompatible type "B"; expected "C"
172 main:9: error: Argument 1 to "f" of "A" has incompatible type "C"; expected "B"
173
174 [case testMultipleGenericTypeParametersAndSubtyping]
175 from typing import TypeVar, Generic
176 S = TypeVar('S')
177 T = TypeVar('T')
178 bc: A[B, C]
179 bb: A[B, B]
180 cb: A[C, B]
181
182 if int():
183 bb = bc # E: Incompatible types in assignment (expression has type "A[B, C]", variable has type "A[B, B]")
184 if int():
185 bb = cb # E: Incompatible types in assignment (expression has type "A[C, B]", variable has type "A[B, B]")
186 bc = bb # E: Incompatible types in assignment (expression has type "A[B, B]", variable has type "A[B, C]")
187
188 if int():
189 bb = bb
190 bc = bc
191
192 class A(Generic[S, T]):
193 s: S
194 t: T
195
196 class B: pass
197 class C(B):pass
198
199
200 -- Simple generic type bodies
201 -- --------------------------
202
203
204 [case testGenericTypeBody1]
205 from typing import TypeVar, Generic
206 T = TypeVar('T')
207 class A(Generic[T]):
208 a: T
209
210 def f(self, b: T) -> T:
211 self.f(x) # Fail
212 d = self # type: A[B] # Fail
213 self.a = self.f(self.a)
214 return self.a
215 c = self # type: A[T]
216 x: B
217 class B: pass
218 [out]
219 main:7: error: Argument 1 to "f" of "A" has incompatible type "B"; expected "T"
220 main:8: error: Incompatible types in assignment (expression has type "A[T]", variable has type "A[B]")
221
222 [case testGenericTypeBodyWithMultipleVariables]
223 from typing import TypeVar, Generic
224 S = TypeVar('S')
225 T = TypeVar('T')
226 class A(Generic[S, T]):
227 def f(self) -> None:
228 s: S
229 t: T
230 if int():
231 s = t # E: Incompatible types in assignment (expression has type "T", variable has type "S")
232 t = s # E: Incompatible types in assignment (expression has type "S", variable has type "T")
233 a = self # type: A[S, B] # E: Incompatible types in assignment (expression has type "A[S, T]", variable has type "A[S, B]")
234 b = self # type: A[T, T] # E: Incompatible types in assignment (expression has type "A[S, T]", variable has type "A[T, T]")
235 c = self # type: A[S, T]
236 if int():
237 t = t
238
239 class B: pass
240 [out]
241
242 [case testCompatibilityOfNoneWithTypeVar]
243 # flags: --no-strict-optional
244 from typing import TypeVar, Generic
245 T = TypeVar('T')
246 class A(Generic[T]):
247 def f(self) -> None:
248 a = None # type: T
249 a = None
250 [out]
251
252 [case testCompatibilityOfTypeVarWithObject]
253 # flags: --no-strict-optional
254 from typing import TypeVar, Generic
255 T = TypeVar('T')
256 class A(Generic[T]):
257 def f(self) -> T:
258 a = object() # type: T # E: Incompatible types in assignment (expression has type "object", variable has type "T")
259 if int():
260 a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "T")
261 b = self.f() # type: object
262 if int():
263 b = self.f()
264 return None
265 [out]
266
267
268 -- Operations with generic types
269 -- -----------------------------
270
271
272 [case testGenericOperations]
273 from typing import TypeVar, Generic
274 S = TypeVar('S')
275 T = TypeVar('T')
276 a: A[B, C]
277 b: B
278 c: C
279
280 if int():
281 b = a + b # E: Incompatible types in assignment (expression has type "C", variable has type "B")
282 c = a + c # E: Unsupported operand types for + ("A[B, C]" and "C")
283 if int():
284 c = a[c] # E: Incompatible types in assignment (expression has type "B", variable has type "C")
285 b = a[b] # E: Invalid index type "B" for "A[B, C]"; expected type "C"
286
287 if int():
288 c = a + b
289 b = a[c]
290
291 class A(Generic[S, T]):
292 def __add__(self, a: S) -> T: pass
293 def __getitem__(self, i: T) -> S: pass
294
295 class B: pass
296 class C: pass
297
298 [case testOperatorAssignmentWithIndexLvalue1]
299 from typing import TypeVar, Generic
300 T = TypeVar('T')
301 b: B
302 c: C
303 ac: A[C]
304
305 ac[b] += b # Fail
306 ac[c] += c # Fail
307 ac[b] += c
308 ac[b] = ac[b] + c
309
310 class A(Generic[T]):
311 def __getitem__(self, i: 'B') -> T: pass
312 def __setitem__(self, i: 'B', v: T) -> None: pass
313
314 class B: pass
315 class C:
316 def __add__(self, o: 'C') -> 'C': pass
317 [out]
318 main:7: error: Unsupported operand types for + ("C" and "B")
319 main:8: error: Invalid index type "C" for "A[C]"; expected type "B"
320
321 [case testOperatorAssignmentWithIndexLvalue2]
322 from typing import TypeVar, Generic
323 T = TypeVar('T')
324 b: B
325 c: C
326 ac: A[C]
327
328 ac[b] += c # Fail
329 ac[c] += c # Fail
330 ac[b] = ac[b] + c # Fail
331
332 class A(Generic[T]):
333 def __getitem__(self, i: 'B') -> T: pass
334 def __setitem__(self, i: 'C', v: T) -> None: pass
335
336 class B: pass
337 class C:
338 def __add__(self, o: 'C') -> 'C': pass
339 [out]
340 main:7: error: Invalid index type "B" for "A[C]"; expected type "C"
341 main:8: error: Invalid index type "C" for "A[C]"; expected type "B"
342 main:9: error: Invalid index type "B" for "A[C]"; expected type "C"
343
344
345 -- Nested generic types
346 -- --------------------
347
348
349 [case testNestedGenericTypes]
350 from typing import TypeVar, Generic
351 T = TypeVar('T')
352 aab: A[A[B]]
353 aac: A[A[C]]
354 ab: A[B]
355 ac: A[C]
356
357 if int():
358 ac = aab.x # E: Incompatible types in assignment (expression has type "A[B]", variable has type "A[C]")
359 ac.y = aab # E: Incompatible types in assignment (expression has type "A[A[B]]", variable has type "A[A[C]]")
360
361 if int():
362 ab = aab.x
363 ac = aac.x
364 ab.y = aab
365 ac.y = aac
366
367 class A(Generic[T]):
368 x: T
369 y: A[A[T]]
370
371 class B:
372 pass
373 class C:
374 pass
375
376
377 -- Generic functions
378 -- -----------------
379
380
381 [case testTypeCheckingGenericFunctionBody]
382 from typing import TypeVar, Generic
383 S = TypeVar('S')
384 T = TypeVar('T')
385 class A: pass
386 class p(Generic[T, S]):
387 def __init__(self, t: T, a: S) -> None: pass
388 def f(s: S, t: T) -> p[T, A]:
389 a = t # type: S # E: Incompatible types in assignment (expression has type "T", variable has type "S")
390 if int():
391 s = t # E: Incompatible types in assignment (expression has type "T", variable has type "S")
392 p_s_a: p[S, A]
393 if s:
394 return p_s_a # E: Incompatible return value type (got "p[S, A]", expected "p[T, A]")
395 b = t # type: T
396 c = s # type: S
397 p_t_a: p[T, A]
398 return p_t_a
399 [out]
400
401 [case testTypeCheckingGenericMethodBody]
402 from typing import TypeVar, Generic
403 T = TypeVar('T')
404 S = TypeVar('S')
405 class p(Generic[T, S]):
406 def __init__(self, t: T, a: S) -> None: pass
407 class A(Generic[T]):
408 def f(self, s: S, t: T) -> p[S, T]:
409 if int():
410 s = t # E: Incompatible types in assignment (expression has type "T", variable has type "S")
411 p_s_s: p[S, S]
412 if s:
413 return p_s_s # E: Incompatible return value type (got "p[S, S]", expected "p[S, T]")
414 p_t_t: p[T, T]
415 if t:
416 return p_t_t # E: Incompatible return value type (got "p[T, T]", expected "p[S, T]")
417 if 1:
418 t = t
419 s = s
420 p_s_t: p[S, T]
421 return p_s_t
422 [out]
423
424 [case testProhibitTypeApplicationToGenericFunctions]
425 from typing import TypeVar
426 T = TypeVar('T')
427 def f(x: T) -> T: pass
428
429 y = f[int] # E: Type application is only supported for generic classes
430 [out]
431
432
433 -- Generic types in expressions
434 -- ----------------------------
435
436
437 [case testTypeApplicationArgs]
438 from typing import TypeVar, Generic
439 T = TypeVar('T')
440 class Node(Generic[T]):
441 def __init__(self, x: T) -> None:
442 ...
443 Node[int]() # E: Missing positional argument "x" in call to "Node"
444 Node[int](1, 1, 1) # E: Too many arguments for "Node"
445 [out]
446
447 [case testTypeApplicationTvars]
448 from typing import TypeVar, Generic
449 T = TypeVar('T')
450 S = TypeVar('S')
451 class A(Generic[T, S]): pass
452 A[int]() # E: Type application has too few types (2 expected)
453 A[int, str, int]() # E: Type application has too many types (2 expected)
454 [out]
455
456 [case testInvalidTypeApplicationType]
457 import types
458 a: A
459 class A: pass
460 a[A]() # E: Value of type "A" is not indexable
461 A[A]() # E: The type "type[A]" is not generic and not indexable
462 [builtins fixtures/tuple.pyi]
463 [typing fixtures/typing-full.pyi]
464
465 [case testTypeApplicationArgTypes]
466 from typing import TypeVar, Generic
467 T = TypeVar('T')
468 class Node(Generic[T]):
469 def __init__(self, x: T) -> None:
470 ...
471
472 Node[int](1)
473 Node[int]('a') # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
474
475 class Dummy(Generic[T]):
476 def meth(self, x: T) -> None:
477 ...
478 def methout(self) -> T:
479 ...
480
481 Dummy[int]().meth(1)
482 Dummy[int]().meth('a') # E: Argument 1 to "meth" of "Dummy" has incompatible type "str"; expected "int"
483 reveal_type(Dummy[int]()) # N: Revealed type is "__main__.Dummy[builtins.int]"
484 reveal_type(Dummy[int]().methout()) # N: Revealed type is "builtins.int"
485 [out]
486
487 [case testTypeApplicationArgTypesSubclasses]
488 from typing import TypeVar, Generic
489 T = TypeVar('T')
490 S = TypeVar('S')
491 class C(Generic[T, S]):
492 def __init__(self, x: T, y: S) -> None:
493 ...
494
495 class D(C[int, T]): ...
496
497 D[str](1, 'a')
498 D[str](1, 1) # E: Argument 2 to "D" has incompatible type "int"; expected "str"
499
500 class E(D[str]): ...
501 E(1, 'a')
502 E(1, 1) # E: Argument 2 to "E" has incompatible type "int"; expected "str"
503 [out]
504
505 [case testTypeApplicationAlias]
506 from typing import TypeVar, Generic
507 T = TypeVar('T')
508 class Node(Generic[T]):
509 def __init__(self, x: T) -> None:
510 ...
511
512 Alias = Node
513 Alias[int](1)
514 Alias[int]("a") # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
515 [out]
516
517 [case testTypeApplicationCrash]
518 import types
519 type[int]
520 [builtins fixtures/tuple.pyi]
521
522
523 -- Generic type aliases
524 -- --------------------
525
526 [case testGenericTypeAliasesBasic]
527 from typing import TypeVar, Generic
528 T = TypeVar('T')
529 S = TypeVar('S')
530 class Node(Generic[T, S]):
531 def __init__(self, x: T, y: S) -> None:
532 ...
533
534 IntNode = Node[int, S]
535 IntIntNode = Node[int, int]
536 SameNode = Node[T, T]
537
538 n = Node(1, 1) # type: IntIntNode
539 n1 = Node(1, 'a') # type: IntIntNode # E: Argument 2 to "Node" has incompatible type "str"; expected "int"
540
541 m = Node(1, 1) # type: IntNode
542 m1 = Node('x', 1) # type: IntNode # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
543 m2 = Node(1, 1) # type: IntNode[str] # E: Argument 2 to "Node" has incompatible type "int"; expected "str"
544
545 s = Node(1, 1) # type: SameNode[int]
546 reveal_type(s) # N: Revealed type is "__main__.Node[builtins.int, builtins.int]"
547 s1 = Node(1, 'x') # type: SameNode[int] # E: Argument 2 to "Node" has incompatible type "str"; expected "int"
548
549 [out]
550
551 [case testGenericTypeAliasesBasic2]
552 from typing import TypeVar, Generic
553 T = TypeVar('T')
554 S = TypeVar('S')
555 class Node(Generic[T, S]):
556 def __init__(self, x: T, y: S) -> None:
557 ...
558
559 IntNode = Node[int, S]
560 IntIntNode = Node[int, int]
561 SameNode = Node[T, T]
562
563 def output_bad() -> IntNode[str]:
564 return Node(1, 1) # Error - bad return type, see out
565
566 def input(x: IntNode[str]) -> None:
567 pass
568 input(Node(1, 's'))
569 input(Node(1, 1)) # E: Argument 2 to "Node" has incompatible type "int"; expected "str"
570
571 def output() -> IntNode[str]:
572 return Node(1, 'x')
573 reveal_type(output()) # N: Revealed type is "__main__.Node[builtins.int, builtins.str]"
574
575 def func(x: IntNode[T]) -> IntNode[T]:
576 return x
577 reveal_type(func) # N: Revealed type is "def [T] (x: __main__.Node[builtins.int, T`-1]) -> __main__.Node[builtins.int, T`-1]"
578
579 func(1) # E: Argument 1 to "func" has incompatible type "int"; expected "Node[int, Never]"
580 func(Node('x', 1)) # E: Argument 1 to "Node" has incompatible type "str"; expected "int"
581 reveal_type(func(Node(1, 'x'))) # N: Revealed type is "__main__.Node[builtins.int, builtins.str]"
582
583 def func2(x: SameNode[T]) -> SameNode[T]:
584 return x
585 reveal_type(func2) # N: Revealed type is "def [T] (x: __main__.Node[T`-1, T`-1]) -> __main__.Node[T`-1, T`-1]"
586
587 func2(Node(1, 'x')) # E: Cannot infer value of type parameter "T" of "func2"
588 y = func2(Node('x', 'x'))
589 reveal_type(y) # N: Revealed type is "__main__.Node[builtins.str, builtins.str]"
590
591 def wrap(x: T) -> IntNode[T]:
592 return Node(1, x)
593
594 z: str
595 reveal_type(wrap(z)) # N: Revealed type is "__main__.Node[builtins.int, builtins.str]"
596
597 [out]
598 main:13: error: Argument 2 to "Node" has incompatible type "int"; expected "str"
599
600 -- Error formatting is a bit different (and probably better) with new analyzer
601 [case testGenericTypeAliasesWrongAliases]
602 # flags: --show-column-numbers --no-strict-optional
603 from typing import TypeVar, Generic, List, Callable, Tuple, Union
604 T = TypeVar('T')
605 S = TypeVar('S')
606 class Node(Generic[T, S]):
607 def __init__(self, x: T, y: S) -> None:
608 ...
609
610 A = Node[T] # Error
611 B = Node[T, T]
612 C = Node[T, T, T] # Error
613 D = Node[T, S]
614 E = Node[Node[T, T], List[T]]
615
616 F = Node[List[T, T], S] # Error
617 G = Callable[..., List[T, T]] # Error
618 H = Union[int, Tuple[T, Node[T]]] # Error
619 h: H # This was reported on previous line
620 h1: H[int, str] # Error
621
622 x = None # type: D[int, str]
623 reveal_type(x)
624 y = None # type: E[int]
625 reveal_type(y)
626
627 X = T # Error
628
629 [builtins fixtures/list.pyi]
630 [typing fixtures/typing-full.pyi]
631 [out]
632 main:9:5: error: "Node" expects 2 type arguments, but 1 given
633 main:11:5: error: "Node" expects 2 type arguments, but 3 given
634 main:15:10: error: "list" expects 1 type argument, but 2 given
635 main:16:19: error: "list" expects 1 type argument, but 2 given
636 main:17:25: error: "Node" expects 2 type arguments, but 1 given
637 main:19:5: error: Bad number of arguments for type alias, expected 1, given 2
638 main:22:13: note: Revealed type is "__main__.Node[builtins.int, builtins.str]"
639 main:24:13: note: Revealed type is "__main__.Node[__main__.Node[builtins.int, builtins.int], builtins.list[builtins.int]]"
640 main:26:5: error: Type variable "__main__.T" is invalid as target for type alias
641
642 [case testGenericTypeAliasesForAliases]
643 from typing import TypeVar, Generic, List, Union
644 T = TypeVar('T')
645 S = TypeVar('S')
646
647 class Node(Generic[T, S]):
648 def __init__(self, x: T, y: S) -> None:
649 pass
650
651 ListedNode = Node[List[T], List[S]]
652 Second = ListedNode[int, T]
653 Third = Union[int, Second[str]]
654
655 def f2(x: T) -> Second[T]:
656 return Node([1], [x])
657 reveal_type(f2('a')) # N: Revealed type is "__main__.Node[builtins.list[builtins.int], builtins.list[builtins.str]]"
658
659 def f3() -> Third:
660 return Node([1], ['x'])
661 reveal_type(f3()) # N: Revealed type is "builtins.int | __main__.Node[builtins.list[builtins.int], builtins.list[builtins.str]]"
662
663 [builtins fixtures/list.pyi]
664
665 [case testGenericTypeAliasesWithNestedArgs]
666 # flags: --pretty --show-error-codes
667 import other
668 a: other.Array[float]
669 reveal_type(a) # N: Revealed type is "other.array[Any, other.dtype[builtins.float]]"
670
671 [out]
672 main:3: error: Type argument "float" of "Array" must be a subtype of "generic" [type-var]
673 a: other.Array[float]
674 ^
675 [file other.py]
676 from typing import Any, Generic, TypeVar
677
678 DT = TypeVar("DT", covariant=True, bound='dtype[Any]')
679 DTS = TypeVar("DTS", covariant=True, bound='generic')
680 S = TypeVar("S", bound=Any)
681 ST = TypeVar("ST", bound='generic', covariant=True)
682
683 class common: pass
684 class generic(common): pass
685 class dtype(Generic[DTS]): pass
686 class array(common, Generic[S, DT]): pass
687 Array = array[Any, dtype[ST]]
688
689 [case testGenericTypeAliasesAny]
690 from typing import TypeVar, Generic
691 T = TypeVar('T')
692 S = TypeVar('S')
693 class Node(Generic[T, S]):
694 def __init__(self, x: T, y: S) -> None:
695 self.x = x
696 self.y = y
697
698 IntNode = Node[int, S]
699 AnyNode = Node[S, T]
700
701 def output() -> IntNode[str]:
702 return Node(1, 'x')
703 x = output() # type: IntNode # This is OK (implicit Any)
704
705 y: IntNode
706 y.x = 1
707 y.x = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
708 y.y = 1 # Both are OK (implicit Any)
709 y.y = 'x'
710
711 z = Node(1, 'x') # type: AnyNode
712 reveal_type(z) # N: Revealed type is "__main__.Node[Any, Any]"
713
714 [out]
715
716 [case testGenericTypeAliasesAccessingMethods]
717 from typing import TypeVar, Generic, List
718 T = TypeVar('T')
719 class Node(Generic[T]):
720 def __init__(self, x: T) -> None:
721 self.x = x
722 def meth(self) -> T:
723 return self.x
724
725 ListedNode = Node[List[T]]
726 l: ListedNode[int]
727 l.x.append(1)
728 l.meth().append(1)
729 reveal_type(l.meth()) # N: Revealed type is "builtins.list[builtins.int]"
730 l.meth().append('x') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
731
732 ListedNode[str]([]).x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "list[str]")
733
734 [builtins fixtures/list.pyi]
735
736 [case testGenericTypeAliasesSubclassing]
737 from typing import TypeVar, Generic, Tuple, List
738 T = TypeVar('T')
739 class Node(Generic[T]):
740 def __init__(self, x: T) -> None:
741 ...
742
743 TupledNode = Node[Tuple[T, T]]
744
745 class D(TupledNode[T]):
746 ...
747 class L(List[TupledNode[T]]):
748 ...
749
750 def f_bad(x: T) -> D[T]:
751 return D(1) # Error, see out
752
753 L[int]().append(Node((1, 1)))
754 L[int]().append(5) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "Node[tuple[int, int]]"
755
756 x = D((1, 1)) # type: D[int]
757 y = D(5) # type: D[int] # E: Argument 1 to "D" has incompatible type "int"; expected "tuple[int, int]"
758
759 def f(x: T) -> D[T]:
760 return D((x, x))
761 reveal_type(f('a')) # N: Revealed type is "__main__.D[builtins.str]"
762
763 [builtins fixtures/list.pyi]
764 [out]
765 main:15: error: Argument 1 to "D" has incompatible type "int"; expected "tuple[T, T]"
766
767 [case testGenericTypeAliasesSubclassingBad]
768
769 from typing import TypeVar, Generic, Tuple, Union
770 T = TypeVar('T')
771 class Node(Generic[T]):
772 def __init__(self, x: T) -> None:
773 ...
774
775 TupledNode = Node[Tuple[T, T]]
776 UNode = Union[int, Node[T]]
777
778 class C(TupledNode): ... # Same as TupledNode[Any]
779 class D(TupledNode[T]): ...
780 class E(Generic[T], UNode[T]): ... # E: Invalid base class "UNode"
781
782 reveal_type(D((1, 1))) # N: Revealed type is "__main__.D[builtins.int]"
783 [builtins fixtures/list.pyi]
784
785 [case testGenericTypeAliasesUnion]
786 from typing import TypeVar, Generic, Union, Any
787 T = TypeVar('T')
788 class Node(Generic[T]):
789 def __init__(self, x: T) -> None:
790 self.x = x
791
792 UNode = Union[int, Node[T]]
793 x = 1 # type: UNode[int]
794
795 x + 1 # E: Unsupported left operand type for + ("Node[int]") \
796 # N: Left operand is of type "int | Node[int]"
797 if not isinstance(x, Node):
798 x + 1
799
800 if not isinstance(x, int):
801 x.x = 1
802 x.x = 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
803
804 def f(x: T) -> UNode[T]:
805 if int():
806 return Node(x)
807 else:
808 return 1
809
810 reveal_type(f(1)) # N: Revealed type is "builtins.int | __main__.Node[builtins.int]"
811
812 TNode = Union[T, Node[int]]
813 s = 1 # type: TNode[str] # E: Incompatible types in assignment (expression has type "int", variable has type "str | Node[int]")
814
815 if not isinstance(s, str):
816 s.x = 1
817
818 z = None # type: TNode # Same as TNode[Any]
819 z.x
820 z.foo() # E: Item "Node[int]" of "Any | Node[int]" has no attribute "foo"
821
822 [builtins fixtures/isinstance.pyi]
823
824 [case testGenericTypeAliasesTuple]
825 from typing import TypeVar, Tuple
826 T = TypeVar('T')
827
828 SameTP = Tuple[T, T]
829 IntTP = Tuple[int, T]
830
831 def f1(x: T) -> SameTP[T]:
832 return x, x
833
834 a, b, c = f1(1) # E: Need more than 2 values to unpack (3 expected)
835 x, y = f1(1)
836 reveal_type(x) # N: Revealed type is "builtins.int"
837
838 def f2(x: IntTP[T]) -> IntTP[T]:
839 return x
840
841 f2((1, 2, 3)) # E: Argument 1 to "f2" has incompatible type "tuple[int, int, int]"; expected "tuple[int, Never]"
842 reveal_type(f2((1, 'x'))) # N: Revealed type is "tuple[builtins.int, builtins.str]"
843
844 [builtins fixtures/for.pyi]
845
846 [case testGenericTypeAliasesCallable]
847 from typing import TypeVar, Generic, Callable
848 T = TypeVar('T')
849 class Node(Generic[T]):
850 def __init__(self, x: T) -> None:
851 ...
852
853 BadC = Callable[T] # E: Please use "Callable[[<parameters>], <return type>]" or "Callable"
854
855 C = Callable[..., T]
856 C2 = Callable[[T, T], Node[T]]
857
858 def make_cb(x: T) -> C[T]:
859 return lambda *args: x
860
861 reveal_type(make_cb(1)) # N: Revealed type is "def (*Any, **Any) -> builtins.int"
862
863 def use_cb(arg: T, cb: C2[T]) -> Node[T]:
864 return cb(arg, arg)
865
866 use_cb(1, 1) # E: Argument 2 to "use_cb" has incompatible type "int"; expected "Callable[[int, int], Node[int]]"
867 my_cb: C2[int]
868 use_cb('x', my_cb) # E: Argument 2 to "use_cb" has incompatible type "Callable[[int, int], Node[int]]"; expected "Callable[[str, str], Node[str]]"
869 reveal_type(use_cb(1, my_cb)) # N: Revealed type is "__main__.Node[builtins.int]"
870 [builtins fixtures/tuple.pyi]
871
872 [out]
873
874 [case testGenericTypeAliasesPEPBasedExample]
875 from typing import TypeVar, List, Tuple
876 T = TypeVar('T', int, bool)
877
878 Vec = List[Tuple[T, T]]
879
880 vec = [] # type: Vec[bool]
881 vec.append('x') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "tuple[bool, bool]"
882 reveal_type(vec[0]) # N: Revealed type is "tuple[builtins.bool, builtins.bool]"
883
884 def fun1(v: Vec[T]) -> T:
885 return v[0][0]
886 def fun2(v: Vec[T], scale: T) -> Vec[T]:
887 return v
888
889 reveal_type(fun1([(1, 1)])) # N: Revealed type is "builtins.int"
890 fun1(1) # E: Argument 1 to "fun1" has incompatible type "int"; expected "list[tuple[bool, bool]]"
891 fun1([(1, 'x')]) # E: Cannot infer value of type parameter "T" of "fun1"
892
893 reveal_type(fun2([(1, 1)], 1)) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.int]]"
894 fun2([('x', 'x')], 'x') # E: Value of type variable "T" of "fun2" cannot be "str"
895
896 [builtins fixtures/list.pyi]
897
898 [case testGenericTypeAliasesImporting]
899 from typing import TypeVar
900 from a import Node, TupledNode
901 T = TypeVar('T')
902
903 n: TupledNode[int]
904 n.x = 1
905 n.y = (1, 1)
906 n.y = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "tuple[int, int]")
907
908 def f(x: Node[T, T]) -> TupledNode[T]:
909 return Node(x.x, (x.x, x.x))
910
911 f(1) # E: Argument 1 to "f" has incompatible type "int"; expected "Node[Never, Never]"
912 f(Node(1, 'x')) # E: Cannot infer value of type parameter "T" of "f"
913 reveal_type(Node('x', 'x')) # N: Revealed type is "a.Node[builtins.str, builtins.str]"
914
915 [file a.py]
916 from typing import TypeVar, Generic, Tuple
917 T = TypeVar('T')
918 S = TypeVar('S')
919 class Node(Generic[T, S]):
920 def __init__(self, x: T, y: S) -> None:
921 self.x = x
922 self.y = y
923
924 TupledNode = Node[T, Tuple[T, T]]
925
926 [builtins fixtures/list.pyi]
927
928 [case testGenericTypeAliasesImportingWithoutTypeVar]
929 from typing import Tuple
930 from lib import Transform
931
932 def int_tf(m: int) -> Transform[int, str]:
933 def transform(i: int, pos: int) -> Tuple[int, str]:
934 pass
935 return transform
936
937 var: Transform[int, str]
938 reveal_type(var) # N: Revealed type is "def (builtins.int, builtins.int) -> tuple[builtins.int, builtins.str]"
939 [file lib.py]
940 from typing import Callable, TypeVar, Tuple
941
942 T = TypeVar('T')
943 R = TypeVar('R')
944
945 Transform = Callable[[T, int], Tuple[T, R]]
946 [builtins fixtures/tuple.pyi]
947 [out]
948
949 [case testGenericTypeAliasesImportingWithoutTypeVarError]
950 from a import Alias
951 x: Alias[int, str] # E: Bad number of arguments for type alias, expected 1, given 2
952 reveal_type(x) # N: Revealed type is "builtins.list[builtins.list[Any]]"
953
954 [file a.py]
955 from typing import TypeVar, List
956 T = TypeVar('T')
957
958 Alias = List[List[T]]
959 [builtins fixtures/list.pyi]
960
961 [case testGenericAliasWithTypeVarsFromDifferentModules]
962 from mod import Alias, TypeVar
963
964 S = TypeVar('S')
965 NewAlias = Alias[int, int, S, S]
966 class C: pass
967
968 x: NewAlias[str]
969 reveal_type(x) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.int, builtins.str, builtins.str]]"
970 y: Alias[int, str, C, C]
971 reveal_type(y) # N: Revealed type is "builtins.list[tuple[builtins.int, builtins.str, __main__.C, __main__.C]]"
972
973 [file mod.py]
974 from typing import TypeVar, List, Tuple
975 import a
976 import b
977 T = TypeVar('T')
978 Alias = List[Tuple[T, a.T, b.T, b.B.T]] # alias_tvars here will be ['T', 'a.T', 'b.T', 'b.B.T']
979
980 [file a.py]
981 from typing import TypeVar
982 T = TypeVar('T')
983
984 [file b.py]
985 from typing import TypeVar
986
987 T = TypeVar('T')
988 class B:
989 T = TypeVar('T')
990 [builtins fixtures/list.pyi]
991 [out]
992
993 [case testTypeAliasesResultingInPlainInstance]
994 from typing import Optional, Union
995
996 O = Optional[int]
997 U = Union[int]
998
999 x: O
1000 y: U
1001
1002 reveal_type(x) # N: Revealed type is "builtins.int | None"
1003 reveal_type(y) # N: Revealed type is "builtins.int"
1004
1005 U[int] # E: Bad number of arguments for type alias, expected 0, given 1
1006 O[int] # E: Bad number of arguments for type alias, expected 0, given 1 \
1007 # E: Type application is only supported for generic classes
1008
1009 [case testAliasesInClassBodyNormalVsSubscripted]
1010
1011 from typing import Union, Type, Iterable
1012
1013 class A: pass
1014 class B(A): pass
1015 class C:
1016 a = A # This is a variable
1017 b = Union[int, str] # This is an alias
1018 c: Type[object] = Iterable[int] # This is however also a variable
1019 if int():
1020 a = B
1021 if int():
1022 b = int # E: Cannot assign multiple types to name "b" without an explicit "type[...]" annotation
1023 if int():
1024 c = int
1025 def f(self, x: a) -> None: pass # E: Variable "__main__.C.a" is not valid as a type \
1026 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
1027 def g(self, x: b) -> None: pass
1028 def h(self, x: c) -> None: pass # E: Variable "__main__.C.c" is not valid as a type \
1029 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
1030 x: b
1031 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
1032 [out]
1033
1034 [case testGenericTypeAliasesRuntimeExpressionsInstance]
1035 from typing import TypeVar, Generic
1036 T = TypeVar('T')
1037 S = TypeVar('S')
1038 class Node(Generic[T, S]):
1039 def __init__(self, x: T, y: S) -> None:
1040 ...
1041
1042 IntNode = Node[int, T]
1043 IntNode[int](1, 1)
1044 IntNode[int](1, 'a') # E: Argument 2 to "Node" has incompatible type "str"; expected "int"
1045
1046 SameNode = Node[T, T]
1047 ff = SameNode[T](1, 1) # E: Type variable "__main__.T" is unbound \
1048 # N: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class) \
1049 # N: (Hint: Use "T" in function signature to bind "T" inside a function)
1050 a = SameNode(1, 'x')
1051 reveal_type(a) # N: Revealed type is "__main__.Node[Any, Any]"
1052 b = SameNode[int](1, 1)
1053 reveal_type(b) # N: Revealed type is "__main__.Node[builtins.int, builtins.int]"
1054 SameNode[int](1, 'x') # E: Argument 2 to "Node" has incompatible type "str"; expected "int"
1055
1056 [out]
1057
1058 [case testGenericTypeAliasesRuntimeExpressionsOther]
1059 from typing import TypeVar, Union, Tuple, Callable, Any
1060 T = TypeVar('T')
1061
1062 CA = Callable[[T], int]
1063 TA = Tuple[T, int]
1064 UA = Union[T, int]
1065
1066 cs = CA + 1 # E: Unsupported left operand type for + ("<typing special form>")
1067 reveal_type(cs) # N: Revealed type is "Any"
1068
1069 ts = TA() # E: "<typing special form>" not callable
1070 reveal_type(ts) # N: Revealed type is "Any"
1071
1072 us = UA.x # E: "<typing special form>" has no attribute "x"
1073 reveal_type(us) # N: Revealed type is "Any"
1074
1075 xx = CA[str] + 1 # E: Type application is only supported for generic classes
1076 yy = TA[str]() # E: Type application is only supported for generic classes
1077 zz = UA[str].x # E: Type application is only supported for generic classes
1078 [builtins fixtures/tuple.pyi]
1079 [typing fixtures/typing-medium.pyi]
1080 [out]
1081
1082 [case testGenericTypeAliasesTypeVarBinding]
1083 from typing import TypeVar, Generic, List
1084 T = TypeVar('T')
1085 S = TypeVar('S')
1086
1087 class A(Generic[T, S]):
1088 def __init__(self, x: T, y: S) -> None: ...
1089
1090 class B(Generic[T, S]):
1091 def __init__(self, x: List[T], y: List[S]) -> None: ...
1092
1093 SameA = A[T, T]
1094 SameB = B[T, T]
1095
1096 class C(Generic[T]):
1097 a: SameA[T]
1098 b = SameB[T]([], [])
1099
1100 reveal_type(C[int]().a) # N: Revealed type is "__main__.A[builtins.int, builtins.int]"
1101 reveal_type(C[str]().b) # N: Revealed type is "__main__.B[builtins.str, builtins.str]"
1102
1103 [builtins fixtures/list.pyi]
1104
1105 [case testGenericTypeAliasesTypeVarConstraints]
1106 # flags: --show-column-numbers --no-strict-optional
1107 from typing import TypeVar, Generic
1108 T = TypeVar('T', int, list)
1109 S = TypeVar('S', int, list)
1110
1111 class A(Generic[T, S]):
1112 def __init__(self, x: T, y: S) -> None: ...
1113
1114 BadA = A[str, T] # One error here
1115 SameA = A[T, T]
1116
1117 x = None # type: SameA[int]
1118 y = None # type: SameA[str] # Another error here
1119
1120 [builtins fixtures/list.pyi]
1121 [out]
1122 main:9:8: error: Value of type variable "T" of "A" cannot be "str"
1123 main:13:1: error: Value of type variable "T" of "SameA" cannot be "str"
1124
1125 [case testGenericTypeAliasesIgnoredPotentialAlias]
1126 class A: ...
1127 Bad = A[int] # type: ignore
1128
1129 reveal_type(Bad) # N: Revealed type is "def () -> __main__.A"
1130 [out]
1131
1132 [case testSubscriptionOfBuiltinAliases]
1133 from typing import List, TypeVar
1134
1135 list[int]()
1136
1137 ListAlias = List
1138 def fun() -> ListAlias[int]:
1139 pass
1140
1141 reveal_type(fun()) # N: Revealed type is "builtins.list[builtins.int]"
1142
1143 BuiltinAlias = list
1144 BuiltinAlias[int]()
1145
1146 T = TypeVar('T')
1147 BadGenList = list[T]
1148
1149 reveal_type(BadGenList[int]()) # N: Revealed type is "builtins.list[builtins.int]"
1150 reveal_type(BadGenList()) # N: Revealed type is "builtins.list[Any]"
1151
1152 [builtins fixtures/list.pyi]
1153 [out]
1154
1155 [case testImportedTypeAliasInRuntimeContext]
1156 from m import Alias
1157
1158 n = Alias[int]([1])
1159 reveal_type(n) # N: Revealed type is "m.Node[builtins.list[builtins.int]]"
1160 bad = Alias[str]([1]) # E: List item 0 has incompatible type "int"; expected "str"
1161
1162 n2 = Alias([1]) # Same as Node[List[Any]]
1163 reveal_type(n2) # N: Revealed type is "m.Node[builtins.list[Any]]"
1164 [file m.py]
1165 from typing import TypeVar, Generic, List
1166 T = TypeVar('T')
1167
1168 class Node(Generic[T]):
1169 def __init__(self, x: T) -> None:
1170 self.x = x
1171
1172 Alias = Node[List[T]]
1173 [builtins fixtures/list.pyi]
1174 [out]
1175
1176 -- Simplified declaration of generics
1177 -- ----------------------------------
1178
1179 [case testSimplifiedGenericSimple]
1180 from typing import TypeVar, Generic
1181 T = TypeVar('T')
1182 S = TypeVar('S')
1183 class B(Generic[T]):
1184 def b(self) -> T: ...
1185
1186 class C(Generic[T]):
1187 def c(self) -> T: ...
1188
1189 class D(B[T], C[S]): ...
1190
1191 reveal_type(D[str, int]().b()) # N: Revealed type is "builtins.str"
1192 reveal_type(D[str, int]().c()) # N: Revealed type is "builtins.int"
1193 [builtins fixtures/list.pyi]
1194 [out]
1195
1196 [case testSimplifiedGenericCallable]
1197 from typing import TypeVar, Generic, Callable
1198 T = TypeVar('T')
1199 S = TypeVar('S')
1200 class B(Generic[T]):
1201 def b(self) -> T: ...
1202
1203 class D(B[Callable[[T], S]]): ...
1204
1205 reveal_type(D[str, int]().b()) # N: Revealed type is "def (builtins.str) -> builtins.int"
1206 [builtins fixtures/list.pyi]
1207 [out]
1208
1209 [case testSimplifiedGenericComplex]
1210 from typing import TypeVar, Generic, Tuple
1211 T = TypeVar('T')
1212 S = TypeVar('S')
1213 U = TypeVar('U')
1214
1215 class A(Generic[T, S]):
1216 pass
1217
1218 class B(Generic[T, S]):
1219 def m(self) -> Tuple[T, S]:
1220 pass
1221
1222 class C(A[S, B[T, int]], B[U, A[int, T]]):
1223 pass
1224
1225 c = C[object, int, str]()
1226 reveal_type(c.m()) # N: Revealed type is "tuple[builtins.str, __main__.A[builtins.int, builtins.int]]"
1227 [builtins fixtures/tuple.pyi]
1228 [out]
1229
1230
1231 [case testSimplifiedGenericOrder]
1232 from typing import TypeVar, Generic
1233 T = TypeVar('T')
1234 S = TypeVar('S')
1235
1236 class B(Generic[T]):
1237 def b(self) -> T: ...
1238
1239 class C(Generic[T]):
1240 def c(self) -> T: ...
1241
1242 class D(B[T], C[S], Generic[S, T]): ...
1243
1244 reveal_type(D[str, int]().b()) # N: Revealed type is "builtins.int"
1245 reveal_type(D[str, int]().c()) # N: Revealed type is "builtins.str"
1246 [builtins fixtures/list.pyi]
1247 [out]
1248
1249 [case testSimplifiedGenericDuplicate]
1250 from typing import TypeVar, Generic
1251 T = TypeVar('T')
1252
1253 class A(Generic[T, T]): # E: Duplicate type variables in Generic[...] or Protocol[...]
1254 pass
1255
1256 a = A[int]()
1257 [builtins fixtures/list.pyi]
1258 [out]
1259
1260 [case testSimplifiedGenericNotAll]
1261 from typing import TypeVar, Generic
1262 T = TypeVar('T')
1263 S = TypeVar('S')
1264
1265 class A(Generic[T]):
1266 pass
1267 class B(Generic[T]):
1268 pass
1269
1270 class C(A[T], B[S], Generic[T]): # E: If Generic[...] or Protocol[...] is present it should list all type variables
1271 pass
1272
1273 c = C[int, str]()
1274 [builtins fixtures/list.pyi]
1275 [out]
1276
1277 [case testSimplifiedGenericInvalid]
1278 from typing import TypeVar, Generic
1279 T = TypeVar('T')
1280
1281 class A(Generic[T]):
1282 pass
1283
1284 class B(A[S]): # E: Name "S" is not defined
1285 pass
1286 [builtins fixtures/list.pyi]
1287 [out]
1288
1289
1290 -- Multiple assignment with lists
1291 -- ------------------------------
1292
1293
1294 [case testMultipleAssignmentWithLists]
1295 from typing import List
1296 class A: pass
1297 class B: pass
1298 class B2(B): pass
1299 a: A
1300 b: B
1301 b2: B2
1302
1303 list_a = [a]
1304 list_b = [b]
1305 list_b2 = [b2]
1306
1307 if int():
1308 a, b = list_a # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1309 if int():
1310 b, a = list_a # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1311 if int():
1312 b2, b2 = list_b # E: Incompatible types in assignment (expression has type "B", variable has type "B2")
1313
1314 a, a = list_a
1315 b, b2, b = list_b2
1316 [builtins fixtures/for.pyi]
1317
1318 [case testMultipleAssignmentWithListsInInitialization]
1319 from typing import List
1320 class A: pass
1321 list_object = [object()]
1322 list_a = [A()]
1323 a, b = list_object # type: (A, object) # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1324 c, d = list_object # type: (object, A) # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1325 e, f = list_a # type: (A, object)
1326 [builtins fixtures/for.pyi]
1327
1328 [case testMultipleAssignmentWithListAndIndexing]
1329 from typing import List
1330 a: List[A]
1331 b: List[int]
1332
1333 a[1], b[1] = a # E: Incompatible types in assignment (expression has type "A", target has type "int")
1334 a[1], a[2] = a
1335
1336 class A: pass
1337 [file builtins.py]
1338 from typing import TypeVar, Generic, Iterable
1339 T = TypeVar('T')
1340 class object: pass
1341 class list(Iterable[T]):
1342 def __setitem__(self, x: int, v: T) -> None: pass
1343 class int: pass
1344 class type: pass
1345 class tuple: pass
1346 class function: pass
1347 class str: pass
1348 class dict: pass
1349
1350 [case testMultipleAssignmentWithIterable]
1351 from typing import Iterable, TypeVar
1352 a: int
1353 b: str
1354 T = TypeVar('T')
1355
1356 def f(x: T) -> Iterable[T]: pass
1357
1358 a, b = f(a) # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1359 b, b = f(a) # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1360 a, a = f(a)
1361 b, b = f(b)
1362 [builtins fixtures/for.pyi]
1363
1364
1365 -- Error messages
1366 -- --------------
1367
1368
1369 [case testErrorWithLongGenericTypeName]
1370 from typing import TypeVar, Generic
1371 B = TypeVar('B')
1372 C = TypeVar('C')
1373 D = TypeVar('D')
1374 E = TypeVar('E')
1375 F = TypeVar('F')
1376 G = TypeVar('G')
1377 H = TypeVar('H')
1378 I = TypeVar('I')
1379 J = TypeVar('J')
1380 K = TypeVar('K')
1381 L = TypeVar('L')
1382 M = TypeVar('M')
1383 N = TypeVar('N')
1384 O = TypeVar('O')
1385 P = TypeVar('P')
1386 Q = TypeVar('Q')
1387 R = TypeVar('R')
1388 S = TypeVar('S')
1389 T = TypeVar('T')
1390 U = TypeVar('U')
1391 V = TypeVar('V')
1392 W = TypeVar('W')
1393 X = TypeVar('X')
1394 Y = TypeVar('Y')
1395 Z = TypeVar('Z')
1396 class OO: pass
1397 a: A[object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object]
1398
1399 def f(a: OO) -> None:
1400 pass
1401
1402 f(a) # E: Argument 1 to "f" has incompatible type "A[object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object]"; expected "OO"
1403
1404 class A(Generic[B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]): pass
1405
1406 [case testErrorWithShorterGenericTypeName]
1407 from typing import TypeVar, Generic
1408 S = TypeVar('S')
1409 T = TypeVar('T')
1410 a: A[object, B]
1411 def f(a: 'B') -> None: pass
1412
1413 f(a) # E: Argument 1 to "f" has incompatible type "A[object, B]"; expected "B"
1414
1415 class A(Generic[S, T]): pass
1416 class B: pass
1417
1418 [case testErrorWithShorterGenericTypeName2]
1419 from typing import Callable, TypeVar, Generic
1420 S = TypeVar('S')
1421 T = TypeVar('T')
1422 a: A[object, Callable[[], None]]
1423 def f(a: 'B') -> None: pass
1424
1425 f(a) # E: Argument 1 to "f" has incompatible type "A[object, Callable[[], None]]"; expected "B"
1426
1427 class A(Generic[S, T]): pass
1428 class B: pass
1429
1430
1431 -- Overloads + generics
1432 -- --------------------
1433
1434
1435 [case testGenericArgumentInOverload]
1436 from foo import *
1437 [file foo.pyi]
1438 from typing import overload, List
1439 class A: pass
1440 class B: pass
1441 a: A
1442 b: B
1443
1444 @overload
1445 def f(a: List[A]) -> A: pass
1446 @overload
1447 def f(a: B) -> B: pass
1448
1449 b = f([a]) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1450 a = f([b]) # E: List item 0 has incompatible type "B"; expected "A"
1451 a = f(b) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1452
1453 a = f([a])
1454 b = f(b)
1455 [builtins fixtures/list.pyi]
1456
1457 [case testGenericFunctionAsOverloadItem]
1458 from foo import *
1459 [file foo.pyi]
1460 from typing import overload, TypeVar, List
1461 T = TypeVar('T')
1462 class A: pass
1463 class B: pass
1464
1465 @overload
1466 def f(a: B) -> B: pass
1467 @overload
1468 def f(a: List[T]) -> T: pass
1469
1470 a: A
1471 b: B
1472
1473 if int():
1474 b = f([a]) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1475 a = f([b]) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1476 if int():
1477 a = f(b) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1478
1479 if int():
1480 a = f([a])
1481 b = f([b])
1482 if int():
1483 b = f(b)
1484 [builtins fixtures/list.pyi]
1485
1486 [case testGenericDictWithOverload]
1487 from typing import Dict, Generic, TypeVar, Any, overload
1488 T = TypeVar("T")
1489
1490 class Key(Generic[T]): ...
1491 class CustomDict(dict):
1492 @overload # type: ignore[override]
1493 def __setitem__(self, key: Key[T], value: T) -> None: ...
1494 @overload
1495 def __setitem__(self, key: str, value: Any) -> None: ...
1496 def __setitem__(self, key, value):
1497 return super().__setitem__(key, value)
1498
1499 def a1(d: Dict[str, Any]) -> None:
1500 if (var := d.get("arg")) is None:
1501 var = d["arg"] = {}
1502 reveal_type(var) # N: Revealed type is "builtins.dict[Any, Any]"
1503
1504 def a2(d: CustomDict) -> None:
1505 if (var := d.get("arg")) is None:
1506 var = d["arg"] = {}
1507 reveal_type(var) # N: Revealed type is "builtins.dict[Any, Any]"
1508 [builtins fixtures/dict.pyi]
1509
1510
1511 -- Type variable scoping
1512 -- ---------------------
1513
1514
1515 [case testLocalTypeVariable]
1516 from typing import TypeVar
1517 def f() -> None:
1518 T = TypeVar('T')
1519 def g(x: T) -> T: pass
1520 a = g(1)
1521 if int():
1522 a = 1
1523 a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1524 [out]
1525
1526 [case testClassLevelTypeVariable]
1527 from typing import TypeVar
1528 class A:
1529 T = TypeVar('T')
1530 def g(self, x: T) -> T: pass
1531 a = A().g(1)
1532 if int():
1533 a = 1
1534 if int():
1535 a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1536
1537 [case testGenericInnerClass]
1538 from typing import TypeVar, Generic
1539 T = TypeVar('T')
1540 class A:
1541 class B(Generic[T]):
1542 def meth(self) -> T: ...
1543 B[int]()
1544 reveal_type(B[int]().meth) # N: Revealed type is "def () -> builtins.int"
1545
1546 A.B[int]()
1547 reveal_type(A.B[int]().meth) # N: Revealed type is "def () -> builtins.int"
1548
1549 [case testGenericClassInnerFunctionTypeVariable]
1550 from typing import TypeVar, Generic
1551 T = TypeVar('T')
1552 class A(Generic[T]):
1553 def __init__(self, a: T) -> None:
1554 self.a = a
1555 def f(self, n: int) -> None:
1556 def g(a: T):
1557 self.a = a
1558 g(self.a)
1559 g(n) # E: Argument 1 to "g" has incompatible type "int"; expected "T"
1560
1561 -- This is non-trivial with new analyzer (and also in fine grained incremental):
1562 -- We need to store whole tvar_scope, not only active class.
1563 [case testFunctionInGenericInnerClassTypeVariable-skip]
1564
1565 from typing import TypeVar, Generic
1566
1567 T = TypeVar('T')
1568 class Outer(Generic[T]):
1569 class Inner:
1570 x: T # E: Invalid type "__main__.T"
1571 def f(self, x: T) -> T: ... # E: Type variable "T" is bound by an outer class
1572 def g(self) -> None:
1573 y: T # E: Invalid type "__main__.T"
1574
1575 [case testGenericClassInsideOtherGenericClass]
1576 from typing import TypeVar, Generic
1577 T = TypeVar("T")
1578 K = TypeVar("K")
1579
1580 class C(Generic[T]):
1581 def __init__(self, t: T) -> None: ...
1582 class F(Generic[K]):
1583 def __init__(self, k: K) -> None: ...
1584 def foo(self) -> K: ...
1585
1586 reveal_type(C.F(17).foo()) # N: Revealed type is "builtins.int"
1587 reveal_type(C("").F(17).foo()) # N: Revealed type is "builtins.int"
1588 reveal_type(C.F) # N: Revealed type is "def [K] (k: K`1) -> __main__.C.F[K`1]"
1589 reveal_type(C("").F) # N: Revealed type is "def [K] (k: K`6) -> __main__.C.F[K`6]"
1590
1591
1592 -- Callable subtyping with generic functions
1593 -- -----------------------------------------
1594
1595
1596 [case testSubtypingWithGenericFunctions]
1597 from typing import TypeVar
1598 A = TypeVar('A')
1599 B = TypeVar('B')
1600
1601 def f1(x: A) -> A: ...
1602 def f2(x: A) -> B: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
1603 def f3(x: B) -> B: ...
1604 def f4(x: int) -> A: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
1605
1606 y1 = f1
1607 if int():
1608 y1 = f1
1609 if int():
1610 y1 = f2
1611 if int():
1612 y1 = f3
1613 if int():
1614 y1 = f4 # E: Incompatible types in assignment (expression has type "Callable[[int], A@f4]", variable has type "Callable[[A@f1], A@f1]")
1615
1616 y2 = f2
1617 if int():
1618 y2 = f2
1619 if int():
1620 y2 = f1 # E: Incompatible types in assignment (expression has type "Callable[[A@f1], A@f1]", variable has type "Callable[[A@f2], B]")
1621 if int():
1622 y2 = f3 # E: Incompatible types in assignment (expression has type "Callable[[B@f3], B@f3]", variable has type "Callable[[A], B@f2]")
1623 if int():
1624 y2 = f4 # E: Incompatible types in assignment (expression has type "Callable[[int], A@f4]", variable has type "Callable[[A@f2], B]")
1625
1626 y3 = f3
1627 if int():
1628 y3 = f3
1629 if int():
1630 y3 = f1
1631 if int():
1632 y3 = f2
1633 if int():
1634 y3 = f4 # E: Incompatible types in assignment (expression has type "Callable[[int], A]", variable has type "Callable[[B], B]")
1635
1636 y4 = f4
1637 if int():
1638 y4 = f4
1639 if int():
1640 y4 = f1 # E: Incompatible types in assignment (expression has type "Callable[[A@f1], A@f1]", variable has type "Callable[[int], A@f4]")
1641 if int():
1642 y4 = f2
1643 if int():
1644 y4 = f3 # E: Incompatible types in assignment (expression has type "Callable[[B], B]", variable has type "Callable[[int], A]")
1645
1646 [case testSubtypingWithGenericInnerFunctions]
1647 from typing import TypeVar
1648 A = TypeVar('A')
1649 B = TypeVar('B')
1650 T = TypeVar('T')
1651 def outer(t: T) -> None:
1652 def f1(x: A) -> A: ...
1653 def f2(x: A) -> B: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
1654 def f3(x: T) -> A: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
1655 def f4(x: A) -> T: ...
1656 def f5(x: T) -> T: ...
1657
1658 y1 = f1
1659 if int():
1660 y1 = f2
1661 y1 = f3 # E: Incompatible types in assignment (expression has type "Callable[[T], A@f3]", variable has type "Callable[[A@f1], A@f1]")
1662 y1 = f4 # E: Incompatible types in assignment (expression has type "Callable[[A@f4], T]", variable has type "Callable[[A@f1], A@f1]")
1663 y1 = f5 # E: Incompatible types in assignment (expression has type "Callable[[T], T]", variable has type "Callable[[A], A]")
1664
1665 y2 = f2
1666 if int():
1667 y2 = f1 # E: Incompatible types in assignment (expression has type "Callable[[A@f1], A@f1]", variable has type "Callable[[A@f2], B]")
1668
1669 y3 = f3
1670 if int():
1671 y3 = f1 # E: Incompatible types in assignment (expression has type "Callable[[A@f1], A@f1]", variable has type "Callable[[T], A@f3]")
1672 y3 = f2
1673 y3 = f4 # E: Incompatible types in assignment (expression has type "Callable[[A@f4], T]", variable has type "Callable[[T], A@f3]")
1674 y3 = f5 # E: Incompatible types in assignment (expression has type "Callable[[T], T]", variable has type "Callable[[T], A]")
1675
1676 y4 = f4
1677 if int():
1678 y4 = f1 # E: Incompatible types in assignment (expression has type "Callable[[A@f1], A@f1]", variable has type "Callable[[A@f4], T]")
1679 y4 = f2
1680 y4 = f3 # E: Incompatible types in assignment (expression has type "Callable[[T], A@f3]", variable has type "Callable[[A@f4], T]")
1681 y4 = f5 # E: Incompatible types in assignment (expression has type "Callable[[T], T]", variable has type "Callable[[A], T]")
1682
1683 y5 = f5
1684 if int():
1685 y5 = f1
1686 y5 = f2
1687 y5 = f3
1688 y5 = f4
1689
1690 [case testSubtypingWithGenericFunctionUsingTypevarWithValues]
1691 from typing import TypeVar, Callable
1692 T = TypeVar('T', int, str)
1693 def f(x: T) -> T: pass
1694 def g1(f: Callable[[str], str]) -> None: pass
1695 g1(f)
1696 def g2(f: Callable[[int], int]) -> None: pass
1697 g2(f)
1698 def g3(f: Callable[[object], object]) -> None: pass
1699 g3(f) # E: Argument 1 to "g3" has incompatible type "Callable[[T], T]"; \
1700 expected "Callable[[object], object]"
1701
1702 [case testSubtypingWithGenericFunctionUsingTypevarWithValues2]
1703 from typing import TypeVar, Callable
1704 T = TypeVar('T', int, str)
1705 def f(x: T) -> T: pass
1706 g = f
1707 g = f
1708
1709
1710 --Operations on type variable types
1711 -- ---------------------------------
1712
1713
1714 [case testTypeVariableTypeEquality]
1715 from typing import TypeVar
1716 T = TypeVar('T')
1717 def f(a: T, b: T) -> T:
1718 a.__ne__(b)
1719 if a == b:
1720 return a
1721 else:
1722 return b
1723 [builtins fixtures/ops.pyi]
1724
1725 [case testTypeVariableTypeIs]
1726 from typing import TypeVar
1727 T = TypeVar('T')
1728 def f(a: T, b: T) -> T:
1729 if a is b or a is 1:
1730 return a
1731 else:
1732 return b
1733 [builtins fixtures/ops.pyi]
1734
1735 [case testTypeVarLessThan]
1736 from typing import TypeVar
1737 T = TypeVar('T')
1738 def f(a: T, b: T) -> T:
1739 if a < b: # E: Unsupported left operand type for < ("T")
1740 return a
1741 else:
1742 return b
1743 [builtins fixtures/ops.pyi]
1744
1745 [case testTypeVarReversibleOperator]
1746 from typing import TypeVar
1747 class A:
1748 def __mul__(cls, other: int) -> str: return ""
1749 T = TypeVar("T", bound=A)
1750 def f(x: T) -> str:
1751 return reveal_type(x * 0) # N: Revealed type is "builtins.str"
1752
1753 [case testTypeVarReversibleOperatorTuple]
1754 from typing import TypeVar, Tuple
1755 class A(Tuple[int, int]):
1756 def __mul__(cls, other: Tuple[int, int]) -> str: return "" # type: ignore # overriding default __mul__
1757 T = TypeVar("T", bound=A)
1758 def f(x: T) -> str:
1759 return reveal_type(x * (1, 2) ) # N: Revealed type is "builtins.str"
1760
1761 [builtins fixtures/tuple.pyi]
1762
1763
1764 -- Subtyping generic callables
1765 -- ---------------------------
1766
1767 [case testSubtypingGenericTypeObject]
1768 from typing import Callable, Generic, TypeVar
1769 T = TypeVar('T')
1770 class C(Generic[T]):
1771 def __init__(self) -> None: pass
1772 x = C # type: Callable[[], C[int]]
1773 y = C # type: Callable[[], int] # E: Incompatible types in assignment (expression has type "type[C[T]]", variable has type "Callable[[], int]")
1774
1775 -- Special cases
1776 -- -------------
1777
1778
1779 [case testIdentityHigherOrderFunction]
1780 from typing import Callable, TypeVar
1781 A = TypeVar('A')
1782 B = TypeVar('B')
1783 def square(n: int) -> int:
1784 return n
1785 def id(f: Callable[[A], B]) -> Callable[[A], B]:
1786 return f
1787 g = id(square)
1788 g(1)
1789 g('x') # E: Argument 1 has incompatible type "str"; expected "int"
1790
1791
1792 [case testIdentityHigherOrderFunction2]
1793 from typing import Callable, TypeVar
1794 A = TypeVar('A')
1795 def voidify(n: int) -> None: pass
1796 def identity(f: Callable[[A], None]) -> Callable[[A], None]:
1797 return f
1798 identity(voidify)(3)
1799
1800 [case testIdentityHigherOrderFunction3]
1801 from typing import Callable, TypeVar
1802 A = TypeVar('A')
1803 B = TypeVar('B')
1804 def fn(n: B) -> None: pass
1805 def identity(f: A) -> A:
1806 return f
1807 identity(fn)
1808 identity(fn)('x')
1809
1810 [case testTypeVariableUnionAndCallableInTypeInference]
1811 from typing import Union, Callable, TypeVar
1812 T = TypeVar('T')
1813 def f(x: T, y: Union[T, Callable[[T], None]]) -> None: pass
1814 f('', '')
1815
1816 [case testGenericFunctionsWithUnalignedIds]
1817 from typing import TypeVar
1818 A = TypeVar('A')
1819 B = TypeVar('B')
1820 def f1(x: int, y: A) -> A: ...
1821 def f2(x: int, y: A) -> B: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
1822 def f3(x: A, y: B) -> B: ...
1823 g = f1
1824 g = f2
1825 g = f3
1826
1827 [case testTypeVariableWithContainerAndTuple]
1828 from typing import TypeVar, Container
1829 T = TypeVar('T')
1830 def f(x: Container[T]) -> T: ...
1831 reveal_type(f((1, 2))) # N: Revealed type is "builtins.int"
1832 [typing fixtures/typing-full.pyi]
1833 [builtins fixtures/tuple.pyi]
1834
1835 [case testClassMethodInGenericClassWithGenericConstructorArg]
1836 from typing import TypeVar, Generic
1837 T = TypeVar('T')
1838 class A(Generic[T]):
1839 def __init__(self, a: T) -> None: pass
1840 @classmethod
1841 def f(cls) -> None: pass
1842 [builtins fixtures/classmethod.pyi]
1843
1844 [case testClassMethodInClassWithGenericConstructor]
1845 from typing import TypeVar, Generic
1846 T = TypeVar('T')
1847 class A:
1848 def __init__(self, a: T) -> None: pass
1849 @classmethod
1850 def f(cls) -> None: pass
1851 [builtins fixtures/classmethod.pyi]
1852
1853 [case testGenericOperatorMethodOverlapping]
1854 from typing import TypeVar, Generic, Tuple
1855 T = TypeVar('T')
1856 T2 = TypeVar('T2')
1857 S = TypeVar('S', bound=str)
1858 S2 = TypeVar('S2', bound=str)
1859 class G(Generic[T]):
1860 pass
1861 class A:
1862 def __or__(self, x: G[T]) -> G[T]: pass
1863 def __ior__(self, x: G[T2]) -> G[T2]: pass
1864 class B:
1865 def __or__(self, x: G[T]) -> G[T]: pass
1866 def __ior__(self, x: G[S]) -> G[S]: pass \
1867 # E: Signatures of "__ior__" and "__or__" are incompatible
1868 class C:
1869 def __or__(self, x: G[S]) -> G[S]: pass
1870 def __ior__(self, x: G[S2]) -> G[S2]: pass
1871
1872 [case testGenericOperatorMethodOverlapping2]
1873 from typing import TypeVar, Generic, Tuple
1874 X = TypeVar('X')
1875 T = TypeVar('T', int, str)
1876 T2 = TypeVar('T2', int, str)
1877 S = TypeVar('S', float, str)
1878 S2 = TypeVar('S2', float, str)
1879 class G(Generic[X]):
1880 pass
1881 class A:
1882 def __or__(self, x: G[T]) -> G[T]: pass
1883 def __ior__(self, x: G[T2]) -> G[T2]: pass
1884 class B:
1885 def __or__(self, x: G[T]) -> G[T]: pass
1886 def __ior__(self, x: G[S]) -> G[S]: pass \
1887 # E: Signatures of "__ior__" and "__or__" are incompatible
1888 class C:
1889 def __or__(self, x: G[S]) -> G[S]: pass
1890 def __ior__(self, x: G[S2]) -> G[S2]: pass
1891 class D:
1892 def __or__(self, x: G[X]) -> G[X]: pass
1893 def __ior__(self, x: G[S2]) -> G[S2]: pass \
1894 # E: Signatures of "__ior__" and "__or__" are incompatible
1895
1896 [case testConstraintInferenceForAnyAgainstTypeT]
1897 from typing import Type, Any, TypeVar
1898
1899 T = TypeVar('T')
1900
1901 def f(c: Type[T]) -> T: ...
1902
1903 x: Any
1904 reveal_type(f(x)) # N: Revealed type is "Any"
1905
1906 [case testCallTypeTWithGenericBound]
1907 from typing import Generic, TypeVar, Type
1908 T = TypeVar('T')
1909 S = TypeVar('S', bound='A')
1910
1911 class A(Generic[T]): pass
1912
1913 def f(cls: Type[S]) -> None:
1914 cls()
1915
1916 [case testQualifiedTypeVariableName]
1917 import b
1918 def f(x: b.T) -> b.T: return x
1919 reveal_type(f)
1920 reveal_type(b.g)
1921 [file b.py]
1922 from typing import TypeVar
1923 T = TypeVar('T')
1924 def g(x: T) -> T: return x
1925 [out]
1926 main:3: note: Revealed type is "def [b.T] (x: b.T`-1) -> b.T`-1"
1927 main:4: note: Revealed type is "def [T] (x: T`-1) -> T`-1"
1928
1929 [case testPartiallyQualifiedTypeVariableName]
1930 from p import b
1931 def f(x: b.T) -> b.T: return x
1932 reveal_type(f)
1933 reveal_type(b.g)
1934 [file p/__init__.py]
1935 [file p/b.py]
1936 from typing import TypeVar
1937 T = TypeVar('T')
1938 def g(x: T) -> T: return x
1939 [out]
1940 main:3: note: Revealed type is "def [b.T] (x: b.T`-1) -> b.T`-1"
1941 main:4: note: Revealed type is "def [T] (x: T`-1) -> T`-1"
1942
1943 [case testGenericClassMethodSimple]
1944 from typing import Generic, TypeVar
1945 T = TypeVar('T')
1946
1947 class C(Generic[T]):
1948 @classmethod
1949 def get(cls) -> T: ...
1950
1951 class D(C[str]): ...
1952
1953 reveal_type(D.get()) # N: Revealed type is "builtins.str"
1954 reveal_type(D().get()) # N: Revealed type is "builtins.str"
1955 [builtins fixtures/classmethod.pyi]
1956
1957 [case testGenericClassMethodExpansion]
1958 from typing import Generic, TypeVar, Tuple
1959 T = TypeVar('T')
1960
1961 class C(Generic[T]):
1962 @classmethod
1963 def get(cls) -> T: ...
1964 class D(C[Tuple[T, T]]): ...
1965 class E(D[str]): ...
1966
1967 reveal_type(E.get()) # N: Revealed type is "tuple[builtins.str, builtins.str]"
1968 reveal_type(E().get()) # N: Revealed type is "tuple[builtins.str, builtins.str]"
1969 [builtins fixtures/classmethod.pyi]
1970
1971 [case testGenericClassMethodExpansionReplacingTypeVar]
1972 from typing import Generic, TypeVar
1973 T = TypeVar('T')
1974 S = TypeVar('S')
1975
1976 class C(Generic[T]):
1977 @classmethod
1978 def get(cls) -> T: ...
1979
1980 class D(C[S]): ...
1981 class E(D[int]): ...
1982
1983 reveal_type(E.get()) # N: Revealed type is "builtins.int"
1984 reveal_type(E().get()) # N: Revealed type is "builtins.int"
1985 [builtins fixtures/classmethod.pyi]
1986
1987 [case testGenericClassMethodUnboundOnClass]
1988 from typing import Generic, TypeVar
1989 T = TypeVar('T')
1990
1991 class C(Generic[T]):
1992 @classmethod
1993 def get(cls) -> T: ...
1994 @classmethod
1995 def make_one(cls, x: T) -> C[T]: ...
1996
1997 reveal_type(C.get) # N: Revealed type is "def [T] () -> T`1"
1998 reveal_type(C[int].get) # N: Revealed type is "def () -> builtins.int"
1999 reveal_type(C.make_one) # N: Revealed type is "def [T] (x: T`1) -> __main__.C[T`1]"
2000 reveal_type(C[int].make_one) # N: Revealed type is "def (x: builtins.int) -> __main__.C[builtins.int]"
2001 [builtins fixtures/classmethod.pyi]
2002
2003 [case testGenericClassMethodUnboundOnSubClass]
2004 from typing import Generic, TypeVar, Tuple
2005 T = TypeVar('T')
2006 S = TypeVar('S')
2007
2008 class C(Generic[T]):
2009 @classmethod
2010 def get(cls) -> T: ...
2011 @classmethod
2012 def make_one(cls, x: T) -> C[T]: ...
2013 class D(C[Tuple[T, S]]): ...
2014 class E(D[S, str]): ...
2015
2016 reveal_type(D.make_one) # N: Revealed type is "def [T, S] (x: tuple[T`1, S`2]) -> __main__.C[tuple[T`1, S`2]]"
2017 reveal_type(D[int, str].make_one) # N: Revealed type is "def (x: tuple[builtins.int, builtins.str]) -> __main__.C[tuple[builtins.int, builtins.str]]"
2018 reveal_type(E.make_one) # N: Revealed type is "def [S] (x: tuple[S`1, builtins.str]) -> __main__.C[tuple[S`1, builtins.str]]"
2019 reveal_type(E[int].make_one) # N: Revealed type is "def (x: tuple[builtins.int, builtins.str]) -> __main__.C[tuple[builtins.int, builtins.str]]"
2020 [builtins fixtures/classmethod.pyi]
2021
2022 [case testGenericClassClsNonGeneric]
2023 from typing import TypeVar, Generic
2024
2025 T = TypeVar('T')
2026
2027 class C(Generic[T]):
2028 @classmethod
2029 def f(cls, x: T) -> T:
2030 return x
2031
2032 @classmethod
2033 def other(cls) -> None:
2034 reveal_type(C) # N: Revealed type is "def [T] () -> __main__.C[T`1]"
2035 reveal_type(C[T]) # N: Revealed type is "def () -> __main__.C[T`1]"
2036 reveal_type(C.f) # N: Revealed type is "def [T] (x: T`1) -> T`1"
2037 reveal_type(C[T].f) # N: Revealed type is "def (x: T`1) -> T`1"
2038 reveal_type(cls.f) # N: Revealed type is "def (x: T`1) -> T`1"
2039 [builtins fixtures/classmethod.pyi]
2040
2041 [case testGenericClassUnrelatedVars]
2042 from typing import TypeVar, Generic
2043
2044 T = TypeVar('T')
2045 T2 = TypeVar('T2')
2046
2047 class C(Generic[T]):
2048 @classmethod
2049 def f(cls, x: T) -> T:
2050 return x
2051
2052 @classmethod
2053 def g(cls, x: T2) -> T2:
2054 cls.f(x) # E: Argument 1 to "f" of "C" has incompatible type "T2"; expected "T"
2055 return x
2056 [builtins fixtures/classmethod.pyi]
2057
2058 [case testGenericClassInGenericFunction]
2059 from typing import TypeVar, Generic
2060
2061 T = TypeVar('T')
2062
2063 class C(Generic[T]):
2064 def __init__(self, item: T) -> None: ...
2065 @classmethod
2066 def f(cls, x: T) -> T:
2067 return x
2068
2069 def foo(x: T, y: int) -> T:
2070 C(y) # OK
2071 C[T](y) # E: Argument 1 to "C" has incompatible type "int"; expected "T"
2072 C[T].f(y) # E: Argument 1 to "f" of "C" has incompatible type "int"; expected "T"
2073 C[T].f(x) # OK
2074 return x
2075 [builtins fixtures/classmethod.pyi]
2076
2077 # TODO: enable this when #7935 is fixed.
2078 [case testGenericClassInGenericFunctionOverloadedConstructor-skip]
2079 from typing import TypeVar, Generic, overload
2080
2081 T = TypeVar('T')
2082
2083 class C(Generic[T]):
2084 @overload
2085 def __new__(cls) -> C[None]: ...
2086 @overload
2087 def __new__(cls, item: T) -> C[T]: ...
2088 def __new__(cls, item=None):
2089 ...
2090 @classmethod
2091 def f(cls, x: T) -> T:
2092 return x
2093
2094 def foo(x: T, y: int) -> T:
2095 C.f(y)
2096 C(y) # OK
2097 C[T](y) # E: Argument 1 to "C" has incompatible type "int"; expected "T"
2098 C[T].f(y) # E: Argument 1 to "f" of "C" has incompatible type "int"; expected "T"
2099 C[T].f(x) # OK
2100 return x
2101 [builtins fixtures/classmethod.pyi]
2102
2103 [case testGenericClassDirectCall]
2104 from typing import TypeVar, Generic
2105
2106 T = TypeVar('T')
2107
2108 class C(Generic[T]):
2109 def __init__(self, item: T) -> None: ...
2110 @classmethod
2111 def f(cls) -> None:
2112 cls(1) # E: Argument 1 to "C" has incompatible type "int"; expected "T"
2113 [builtins fixtures/classmethod.pyi]
2114
2115 [case testGenericClassAlternativeConstructorPrecise]
2116 from typing import Generic, TypeVar, Type, Tuple
2117
2118 T = TypeVar('T')
2119
2120 class Base(Generic[T]):
2121 Q = TypeVar('Q', bound=Base[T])
2122
2123 def __init__(self, item: T) -> None: ...
2124
2125 @classmethod
2126 def make_pair(cls: Type[Q], item: T) -> Tuple[Q, Q]:
2127 if bool():
2128 return cls(0), cls(0) # E: Argument 1 to "Base" has incompatible type "int"; expected "T"
2129 return cls(item), cls(item)
2130 [builtins fixtures/classmethod.pyi]
2131
2132 [case testGenericClassAlternativeConstructorPreciseOverloaded]
2133 from typing import Generic, TypeVar, Type, Tuple, overload, Union
2134
2135 T = TypeVar('T')
2136
2137 class Base(Generic[T]):
2138 Q = TypeVar('Q', bound=Base[T])
2139
2140 def __init__(self, item: T) -> None: ...
2141
2142 @overload
2143 @classmethod
2144 def make_some(cls: Type[Q], item: T) -> Q: ...
2145
2146 @overload
2147 @classmethod
2148 def make_some(cls: Type[Q], item: T, n: int) -> Tuple[Q, ...]: ...
2149
2150 @classmethod
2151 def make_some(cls: Type[Q], item: T, n: int = 0) -> Union[Q, Tuple[Q, ...]]:
2152 if n:
2153 return (cls(item),)
2154 return cls(item)
2155
2156 reveal_type(Base.make_some) # N: Revealed type is "Overload(def [T] (item: T`1) -> __main__.Base[T`1], def [T] (item: T`1, n: builtins.int) -> builtins.tuple[__main__.Base[T`1], ...])"
2157 reveal_type(Base.make_some(1)) # N: Revealed type is "__main__.Base[builtins.int]"
2158 reveal_type(Base.make_some(1, 1)) # N: Revealed type is "builtins.tuple[__main__.Base[builtins.int], ...]"
2159
2160 class Sub(Base[str]): ...
2161 Sub.make_some(1) # E: No overload variant of "make_some" of "Base" matches argument type "int" \
2162 # N: Possible overload variants: \
2163 # N: def make_some(cls, item: str) -> Sub \
2164 # N: def make_some(cls, item: str, n: int) -> tuple[Sub, ...]
2165 [builtins fixtures/classmethod.pyi]
2166
2167 [case testNoGenericAccessOnImplicitAttributes]
2168 from typing import TypeVar, Generic
2169
2170 T = TypeVar('T')
2171
2172 class C(Generic[T]):
2173 def __init__(self, x: T) -> None:
2174 self.x = x
2175
2176 @classmethod
2177 def meth(cls) -> None:
2178 cls.x # E: Cannot access instance-only attribute "x" on class object \
2179 # E: Access to generic instance variables via class is ambiguous
2180 [builtins fixtures/classmethod.pyi]
2181
2182 [case testGenericClassMethodUnboundOnClassNonMatchingIdNonGeneric]
2183 from typing import Generic, TypeVar, Any, Tuple, Type
2184
2185 T = TypeVar('T')
2186 S = TypeVar('S')
2187 Q = TypeVar('Q', bound='A[Any]')
2188
2189 class A(Generic[T]):
2190 @classmethod
2191 def foo(cls: Type[Q]) -> Tuple[T, Q]: ...
2192
2193 class B(A[T], Generic[T, S]):
2194 def meth(self) -> None:
2195 reveal_type(A[T].foo) # N: Revealed type is "def () -> tuple[T`1, __main__.A[T`1]]"
2196 @classmethod
2197 def other(cls) -> None:
2198 reveal_type(cls.foo) # N: Revealed type is "def () -> tuple[T`1, __main__.B[T`1, S`2]]"
2199 reveal_type(B.foo) # N: Revealed type is "def [T, S] () -> tuple[T`1, __main__.B[T`1, S`2]]"
2200 [builtins fixtures/classmethod.pyi]
2201
2202 [case testGenericClassAlternativeConstructorPrecise2]
2203 from typing import Generic, TypeVar, Type, Tuple, Any
2204
2205 T = TypeVar('T')
2206 Q = TypeVar('Q')
2207
2208 class Base(Generic[T]):
2209 def __init__(self, item: T) -> None: ...
2210 @classmethod
2211 def make_pair(cls: Type[Q], item: T) -> Tuple[Q, Q]: ...
2212 class Sub(Base[T]):
2213 ...
2214
2215 reveal_type(Sub.make_pair('yes')) # N: Revealed type is "tuple[__main__.Sub[builtins.str], __main__.Sub[builtins.str]]"
2216 Sub[int].make_pair('no') # E: Argument 1 to "make_pair" of "Base" has incompatible type "str"; expected "int"
2217 [builtins fixtures/classmethod.pyi]
2218
2219 [case testGenericClassAttrUnboundOnClass]
2220 from typing import Generic, TypeVar
2221 T = TypeVar('T')
2222
2223 class C(Generic[T]):
2224 x: T
2225 @classmethod
2226 def get(cls) -> T:
2227 return cls.x # OK
2228
2229 x = C.x # E: Access to generic instance variables via class is ambiguous
2230 reveal_type(x) # N: Revealed type is "Any"
2231 xi = C[int].x # E: Access to generic instance variables via class is ambiguous
2232 reveal_type(xi) # N: Revealed type is "builtins.int"
2233 [builtins fixtures/classmethod.pyi]
2234
2235 [case testGenericClassAttrUnboundOnSubClass]
2236 from typing import Generic, TypeVar, Tuple
2237 T = TypeVar('T')
2238
2239 class C(Generic[T]):
2240 x: T
2241 class D(C[int]): ...
2242 class E(C[int]):
2243 x = 42
2244
2245 x = D.x # E: Access to generic instance variables via class is ambiguous
2246 reveal_type(x) # N: Revealed type is "builtins.int"
2247 E.x # OK
2248
2249 [case testGenericClassMethodOverloaded]
2250 from typing import Generic, TypeVar, overload, Tuple
2251 T = TypeVar('T')
2252
2253 class C(Generic[T]):
2254 @overload
2255 @classmethod
2256 def get(cls) -> T: ...
2257 @overload
2258 @classmethod
2259 def get(cls, n: int) -> Tuple[T, ...]: ...
2260 @classmethod
2261 def get(cls, n: int = 0):
2262 pass
2263
2264 class D(C[str]): ...
2265
2266 reveal_type(D.get()) # N: Revealed type is "builtins.str"
2267 reveal_type(D.get(42)) # N: Revealed type is "builtins.tuple[builtins.str, ...]"
2268 [builtins fixtures/classmethod.pyi]
2269
2270 [case testGenericClassMethodAnnotation]
2271 from typing import Generic, TypeVar, Type
2272 T = TypeVar('T')
2273
2274 class Maker(Generic[T]):
2275 x: T
2276 @classmethod
2277 def get(cls) -> T: ...
2278
2279 class B(Maker[B]): ...
2280
2281 def f(o: Maker[T]) -> T:
2282 if bool():
2283 return o.x
2284 return o.get()
2285 b = f(B())
2286 reveal_type(b) # N: Revealed type is "__main__.B"
2287
2288 def g(t: Type[Maker[T]]) -> T:
2289 if bool():
2290 return t.x
2291 return t.get()
2292 bb = g(B)
2293 reveal_type(bb) # N: Revealed type is "__main__.B"
2294 [builtins fixtures/classmethod.pyi]
2295
2296 [case testGenericClassMethodAnnotationDecorator]
2297 from typing import Generic, Callable, TypeVar, Iterator
2298
2299 T = TypeVar('T')
2300
2301 class Box(Generic[T]):
2302 @classmethod
2303 def wrap(cls, generator: Callable[[], T]) -> Box[T]: ...
2304
2305 class IteratorBox(Box[Iterator[T]]): ...
2306
2307 @IteratorBox.wrap # E: Argument 1 to "wrap" of "Box" has incompatible type "Callable[[], int]"; expected "Callable[[], Iterator[Never]]"
2308 def g() -> int:
2309 ...
2310 [builtins fixtures/classmethod.pyi]
2311
2312 [case testGenericClassMethodInGenericFunction]
2313 from typing import Generic, TypeVar
2314 T = TypeVar('T')
2315 S = TypeVar('S')
2316
2317 class C(Generic[T]):
2318 @classmethod
2319 def get(cls) -> T: ...
2320
2321 def func(x: S) -> S:
2322 return C[S].get()
2323 [builtins fixtures/classmethod.pyi]
2324
2325 [case testGenericStaticMethodInGenericFunction]
2326 from typing import Generic, TypeVar
2327 T = TypeVar('T')
2328 S = TypeVar('S')
2329
2330 class C(Generic[T]):
2331 @staticmethod
2332 def get() -> T: ...
2333
2334 def func(x: S) -> S:
2335 return C[S].get()
2336 [builtins fixtures/staticmethod.pyi]
2337
2338 [case testMultipleAssignmentFromAnyIterable]
2339 from typing import Any
2340 class A:
2341 def __iter__(self) -> Any: ...
2342
2343 x, y = A()
2344 reveal_type(x) # N: Revealed type is "Any"
2345 reveal_type(y) # N: Revealed type is "Any"
2346
2347 [case testSubclassingGenericSelfClassMethod]
2348 from typing import TypeVar, Type
2349
2350 AT = TypeVar('AT', bound='A')
2351
2352 class A:
2353 @classmethod
2354 def from_config(cls: Type[AT]) -> AT:
2355 ...
2356
2357 class B(A):
2358 @classmethod
2359 def from_config(cls: Type[B]) -> B:
2360 return B()
2361 [builtins fixtures/classmethod.pyi]
2362
2363 [case testSubclassingGenericSelfClassMethodOptional]
2364 from typing import TypeVar, Type, Optional
2365
2366 AT = TypeVar('AT', bound='A')
2367
2368 class A:
2369 @classmethod
2370 def from_config(cls: Type[AT]) -> Optional[AT]:
2371 return None
2372
2373 class B(A):
2374 @classmethod
2375 def from_config(cls: Type[B]) -> Optional[B]:
2376 return B()
2377 [builtins fixtures/classmethod.pyi]
2378
2379 [case testSubclassingGenericSelfClassMethodNonAnnotated]
2380 from typing import TypeVar, Type
2381
2382 AT = TypeVar('AT', bound='A')
2383
2384 class A:
2385 @classmethod
2386 def from_config(cls: Type[AT]) -> AT:
2387 ...
2388
2389 class B(A):
2390 @classmethod
2391 def from_config(cls) -> B:
2392 return B()
2393 [builtins fixtures/classmethod.pyi]
2394
2395 [case testAbstractGenericMethodInference]
2396 from abc import ABC, abstractmethod
2397 from typing import Callable, Generic, TypeVar
2398
2399 A = TypeVar('A')
2400 B = TypeVar('B')
2401 C = TypeVar('C')
2402
2403 class TwoTypes(Generic[A, B]):
2404
2405 def __call__(self) -> B: pass
2406
2407 class MakeTwoAbstract(ABC, Generic[A]):
2408
2409 def __init__(self) -> None: pass
2410
2411 @abstractmethod
2412 def __call__(self, b: B) -> TwoTypes[A, B]: pass
2413
2414 class MakeTwoConcrete(Generic[A]):
2415
2416 def __call__(self, b: B) -> TwoTypes[A, B]: pass
2417
2418
2419 class MakeTwoGenericSubAbstract(Generic[C], MakeTwoAbstract[C]):
2420
2421 def __call__(self, b: B) -> TwoTypes[C, B]: pass
2422
2423 class MakeTwoAppliedSubAbstract(MakeTwoAbstract[str]):
2424
2425 def __call__(self, b: B) -> TwoTypes[str, B]: pass
2426
2427 class Test():
2428
2429 def make_two(self,
2430 mts: MakeTwoAbstract[A],
2431 mte: MakeTwoConcrete[A],
2432 mtgsa: MakeTwoGenericSubAbstract[A],
2433 mtasa: MakeTwoAppliedSubAbstract) -> None:
2434 reveal_type(mts(2)) # N: Revealed type is "__main__.TwoTypes[A`-1, builtins.int]"
2435 reveal_type(mte(2)) # N: Revealed type is "__main__.TwoTypes[A`-1, builtins.int]"
2436 reveal_type(mtgsa(2)) # N: Revealed type is "__main__.TwoTypes[A`-1, builtins.int]"
2437 reveal_type(mtasa(2)) # N: Revealed type is "__main__.TwoTypes[builtins.str, builtins.int]"
2438 reveal_type(MakeTwoConcrete[int]()('foo')) # N: Revealed type is "__main__.TwoTypes[builtins.int, builtins.str]"
2439 reveal_type(MakeTwoConcrete[str]()(2)) # N: Revealed type is "__main__.TwoTypes[builtins.str, builtins.int]"
2440 reveal_type(MakeTwoAppliedSubAbstract()('foo')) # N: Revealed type is "__main__.TwoTypes[builtins.str, builtins.str]"
2441 reveal_type(MakeTwoAppliedSubAbstract()(2)) # N: Revealed type is "__main__.TwoTypes[builtins.str, builtins.int]"
2442 reveal_type(MakeTwoGenericSubAbstract[str]()('foo')) # N: Revealed type is "__main__.TwoTypes[builtins.str, builtins.str]"
2443 reveal_type(MakeTwoGenericSubAbstract[str]()(2)) # N: Revealed type is "__main__.TwoTypes[builtins.str, builtins.int]"
2444
2445 [case testGenericClassPropertyBound]
2446 from typing import Generic, TypeVar, Callable, Type, List, Dict
2447
2448 T = TypeVar('T')
2449 U = TypeVar('U')
2450
2451 def classproperty(f: Callable[..., U]) -> U: ...
2452
2453 class C(Generic[T]):
2454 @classproperty
2455 def test(self) -> T: ...
2456
2457 class D(C[str]): ...
2458 class E1(C[T], Generic[T, U]): ...
2459 class E2(C[U], Generic[T, U]): ...
2460 class G(C[List[T]]): ...
2461
2462 x: C[int]
2463 y: Type[C[int]]
2464 reveal_type(x.test) # N: Revealed type is "builtins.int"
2465 reveal_type(y.test) # N: Revealed type is "builtins.int"
2466
2467 xd: D
2468 yd: Type[D]
2469 reveal_type(xd.test) # N: Revealed type is "builtins.str"
2470 reveal_type(yd.test) # N: Revealed type is "builtins.str"
2471
2472 ye1: Type[E1[int, str]]
2473 ye2: Type[E2[int, str]]
2474 reveal_type(ye1.test) # N: Revealed type is "builtins.int"
2475 reveal_type(ye2.test) # N: Revealed type is "builtins.str"
2476
2477 xg: G[int]
2478 yg: Type[G[int]]
2479 reveal_type(xg.test) # N: Revealed type is "builtins.list[builtins.int]"
2480 reveal_type(yg.test) # N: Revealed type is "builtins.list[builtins.int]"
2481
2482 class Sup:
2483 attr: int
2484 S = TypeVar('S', bound=Sup)
2485
2486 def func(tp: Type[C[S]]) -> S:
2487 reveal_type(tp.test.attr) # N: Revealed type is "builtins.int"
2488
2489 reg: Dict[S, G[S]]
2490 reveal_type(reg[tp.test]) # N: Revealed type is "__main__.G[S`-1]"
2491 reveal_type(reg[tp.test].test) # N: Revealed type is "builtins.list[S`-1]"
2492
2493 if bool():
2494 return tp.test
2495 else:
2496 return reg[tp.test].test[0]
2497 [builtins fixtures/dict.pyi]
2498
2499 [case testGenericFunctionAliasExpand]
2500 from typing import Optional, TypeVar
2501
2502 T = TypeVar("T")
2503 def gen(x: T) -> T: ...
2504 gen_a = gen
2505
2506 S = TypeVar("S", int, str)
2507 class C: ...
2508 def test() -> Optional[S]:
2509 reveal_type(gen_a(C())) # N: Revealed type is "__main__.C"
2510 return None
2511
2512 [case testGenericFunctionMemberExpand]
2513 from typing import Optional, TypeVar, Callable
2514
2515 T = TypeVar("T")
2516
2517 class A:
2518 def __init__(self) -> None:
2519 self.gen: Callable[[T], T]
2520
2521 S = TypeVar("S", int, str)
2522 class C: ...
2523 def test() -> Optional[S]:
2524 reveal_type(A().gen(C())) # N: Revealed type is "__main__.C"
2525 return None
2526
2527 [case testGenericJoinCovariant]
2528 from typing import Generic, TypeVar, List
2529
2530 T = TypeVar("T", covariant=True)
2531
2532 class Container(Generic[T]): ...
2533 class Base: ...
2534 class A(Base): ...
2535 class B(Base): ...
2536
2537 a: A
2538 b: B
2539
2540 a_c: Container[A]
2541 b_c: Container[B]
2542
2543 reveal_type([a, b]) # N: Revealed type is "builtins.list[__main__.Base]"
2544 reveal_type([a_c, b_c]) # N: Revealed type is "builtins.list[__main__.Container[__main__.Base]]"
2545 [builtins fixtures/list.pyi]
2546
2547 [case testGenericJoinContravariant]
2548 from typing import Generic, TypeVar, List
2549
2550 T = TypeVar("T", contravariant=True)
2551
2552 class Container(Generic[T]): ...
2553 class A: ...
2554 class B(A): ...
2555
2556 a_c: Container[A]
2557 b_c: Container[B]
2558
2559 # TODO: this can be more precise than "object", see a comment in mypy/join.py
2560 reveal_type([a_c, b_c]) # N: Revealed type is "builtins.list[builtins.object]"
2561 [builtins fixtures/list.pyi]
2562
2563 [case testGenericJoinRecursiveTypes]
2564 from typing import Sequence, TypeVar
2565
2566 class A(Sequence[A]): ...
2567 class B(Sequence[B]): ...
2568
2569 a: A
2570 b: B
2571
2572 reveal_type([a, b]) # N: Revealed type is "builtins.list[typing.Sequence[builtins.object]]"
2573 [builtins fixtures/list.pyi]
2574
2575 [case testGenericJoinRecursiveInvariant]
2576 from typing import Generic, TypeVar
2577
2578 T = TypeVar("T")
2579 class I(Generic[T]): ...
2580
2581 class A(I[A]): ...
2582 class B(I[B]): ...
2583
2584 a: A
2585 b: B
2586 reveal_type([a, b]) # N: Revealed type is "builtins.list[builtins.object]"
2587 [builtins fixtures/list.pyi]
2588
2589 [case testGenericJoinNestedInvariantAny]
2590 from typing import Any, Generic, TypeVar
2591
2592 T = TypeVar("T")
2593 class I(Generic[T]): ...
2594
2595 a: I[I[int]]
2596 b: I[I[Any]]
2597 reveal_type([a, b]) # N: Revealed type is "builtins.list[__main__.I[__main__.I[Any]]]"
2598 reveal_type([b, a]) # N: Revealed type is "builtins.list[__main__.I[__main__.I[Any]]]"
2599 [builtins fixtures/list.pyi]
2600
2601 [case testOverlappingTypeVarIds]
2602 from typing import TypeVar, Generic
2603
2604 class A: ...
2605 class B: ...
2606
2607 T = TypeVar("T", bound=A)
2608 V = TypeVar("V", bound=B)
2609 S = TypeVar("S")
2610
2611 class Whatever(Generic[T]):
2612 def something(self: S) -> S:
2613 return self
2614
2615 # the "V" here had the same id as "T" and so mypy used to think it could expand one into another.
2616 # this test is here to make sure that doesn't happen!
2617 class WhateverPartTwo(Whatever[A], Generic[V]):
2618 def something(self: S) -> S:
2619 return self
2620
2621
2622 [case testConstrainedGenericSuper]
2623 from typing import Generic, TypeVar
2624
2625 AnyStr = TypeVar("AnyStr", str, bytes)
2626
2627 class Foo(Generic[AnyStr]):
2628 def method1(self, s: AnyStr, t: AnyStr) -> None: ...
2629
2630 class Bar(Foo[AnyStr]):
2631 def method1(self, s: AnyStr, t: AnyStr) -> None:
2632 super().method1('x', b'y') # Should be an error
2633 [out]
2634 main:10: error: Argument 1 to "method1" of "Foo" has incompatible type "str"; expected "AnyStr"
2635 main:10: error: Argument 2 to "method1" of "Foo" has incompatible type "bytes"; expected "AnyStr"
2636
2637 [case testTypeVariableClashVar]
2638 from typing import Generic, TypeVar, Callable
2639
2640 T = TypeVar("T")
2641 R = TypeVar("R")
2642 class C(Generic[R]):
2643 x: Callable[[T], R]
2644
2645 def func(x: C[R]) -> R:
2646 return x.x(42) # OK
2647
2648 [case testTypeVariableClashVarTuple]
2649 from typing import Generic, TypeVar, Callable, Tuple
2650
2651 T = TypeVar("T")
2652 R = TypeVar("R")
2653 class C(Generic[R]):
2654 x: Callable[[T], Tuple[R, T]]
2655
2656 def func(x: C[R]) -> R:
2657 if bool():
2658 return x.x(42)[0] # OK
2659 else:
2660 return x.x(42)[1] # E: Incompatible return value type (got "int", expected "R")
2661 [builtins fixtures/tuple.pyi]
2662
2663 [case testTypeVariableClashMethod]
2664 from typing import Generic, TypeVar, Callable
2665
2666 T = TypeVar("T")
2667 R = TypeVar("R")
2668 class C(Generic[R]):
2669 def x(self) -> Callable[[T], R]: ...
2670
2671 def func(x: C[R]) -> R:
2672 return x.x()(42) # OK
2673
2674 [case testTypeVariableClashMethodTuple]
2675 from typing import Generic, TypeVar, Callable, Tuple
2676
2677 T = TypeVar("T")
2678 R = TypeVar("R")
2679 class C(Generic[R]):
2680 def x(self) -> Callable[[T], Tuple[R, T]]: ...
2681
2682 def func(x: C[R]) -> R:
2683 if bool():
2684 return x.x()(42)[0] # OK
2685 else:
2686 return x.x()(42)[1] # E: Incompatible return value type (got "int", expected "R")
2687 [builtins fixtures/tuple.pyi]
2688
2689 [case testTypeVariableClashVarSelf]
2690 from typing import Self, TypeVar, Generic, Callable
2691
2692 T = TypeVar("T")
2693 S = TypeVar("S")
2694
2695 class C(Generic[T]):
2696 x: Callable[[S], Self]
2697 y: T
2698
2699 def foo(x: C[T]) -> T:
2700 return x.x(42).y # OK
2701
2702 [case testNestedGenericFunctionTypeApplication]
2703 from typing import TypeVar, Generic, List
2704
2705 A = TypeVar("A")
2706 B = TypeVar("B")
2707
2708 class C(Generic[A]):
2709 x: A
2710
2711 def foo(x: A) -> A:
2712 def bar() -> List[A]:
2713 y = C[List[A]]()
2714 z = C[List[B]]() # E: Type variable "__main__.B" is unbound \
2715 # N: (Hint: Use "Generic[B]" or "Protocol[B]" base class to bind "B" inside a class) \
2716 # N: (Hint: Use "B" in function signature to bind "B" inside a function)
2717 return y.x
2718 return bar()[0]
2719
2720
2721 -- TypeVar imported from typing_extensions
2722 -- ---------------------------------------
2723
2724 [case testTypeVarTypingExtensionsSimpleGeneric]
2725 from typing import Generic
2726 from typing_extensions import TypeVar
2727
2728 T = TypeVar("T")
2729
2730 class A(Generic[T]):
2731 def __init__(self, value: T) -> None:
2732 self.value = value
2733
2734 a: A = A(8)
2735 b: A[str] = A("")
2736
2737 reveal_type(A(1.23)) # N: Revealed type is "__main__.A[builtins.float]"
2738
2739 [builtins fixtures/tuple.pyi]
2740
2741 [case testTypeVarTypingExtensionsSimpleBound]
2742 from typing_extensions import TypeVar
2743
2744 T= TypeVar("T")
2745
2746 def func(var: T) -> T:
2747 return var
2748
2749 reveal_type(func(1)) # N: Revealed type is "builtins.int"
2750
2751 [builtins fixtures/tuple.pyi]
2752
2753 [case testGenericLambdaGenericMethodNoCrash]
2754 from typing import TypeVar, Union, Callable, Generic
2755
2756 S = TypeVar("S")
2757 T = TypeVar("T")
2758
2759 def f(x: Callable[[G[T]], int]) -> T: ...
2760
2761 class G(Generic[T]):
2762 def g(self, x: S) -> Union[S, T]: ...
2763
2764 reveal_type(f(lambda x: x.g(0))) # N: Revealed type is "builtins.int"
2765
2766 [case testDictStarInference]
2767 class B: ...
2768 class C1(B): ...
2769 class C2(B): ...
2770
2771 dict1 = {"a": C1()}
2772 dict2 = {"a": C2(), **dict1}
2773 reveal_type(dict2) # N: Revealed type is "builtins.dict[builtins.str, __main__.B]"
2774 [builtins fixtures/dict.pyi]
2775
2776 [case testDictStarAnyKeyJoinValue]
2777 from typing import Any
2778
2779 class B: ...
2780 class C1(B): ...
2781 class C2(B): ...
2782
2783 dict1: Any
2784 dict2 = {"a": C1(), **{x: C2() for x in dict1}}
2785 reveal_type(dict2) # N: Revealed type is "builtins.dict[Any, __main__.B]"
2786 [builtins fixtures/dict.pyi]
2787
2788 -- Type inference for generic decorators applied to generic callables
2789 -- ------------------------------------------------------------------
2790
2791 [case testInferenceAgainstGenericCallable]
2792 from typing import TypeVar, Callable, List
2793
2794 X = TypeVar('X')
2795 T = TypeVar('T')
2796
2797 def foo(x: Callable[[int], X]) -> List[X]:
2798 ...
2799 def bar(x: Callable[[X], int]) -> List[X]:
2800 ...
2801
2802 def id(x: T) -> T:
2803 ...
2804 reveal_type(foo(id)) # N: Revealed type is "builtins.list[builtins.int]"
2805 reveal_type(bar(id)) # N: Revealed type is "builtins.list[builtins.int]"
2806 [builtins fixtures/list.pyi]
2807
2808 [case testInferenceAgainstGenericCallableNoLeak]
2809 from typing import TypeVar, Callable
2810
2811 T = TypeVar('T')
2812
2813 def f(x: Callable[..., T]) -> T:
2814 return x()
2815
2816 def tpl(x: T) -> T:
2817 return x
2818
2819 # This is valid because of "..."
2820 reveal_type(f(tpl)) # N: Revealed type is "Any"
2821 [out]
2822
2823 [case testInferenceAgainstGenericCallableChain]
2824 from typing import TypeVar, Callable, List
2825
2826 X = TypeVar('X')
2827 T = TypeVar('T')
2828
2829 def chain(f: Callable[[X], T], g: Callable[[T], int]) -> Callable[[X], int]: ...
2830 def id(x: T) -> T:
2831 ...
2832 reveal_type(chain(id, id)) # N: Revealed type is "def (builtins.int) -> builtins.int"
2833 [builtins fixtures/list.pyi]
2834
2835 [case testInferenceAgainstGenericCallableGeneric]
2836 from typing import TypeVar, Callable, List
2837
2838 S = TypeVar('S')
2839 T = TypeVar('T')
2840 U = TypeVar('U')
2841
2842 def dec(f: Callable[[S], T]) -> Callable[[S], List[T]]:
2843 ...
2844 def id(x: U) -> U:
2845 ...
2846 reveal_type(dec(id)) # N: Revealed type is "def [S] (S`1) -> builtins.list[S`1]"
2847
2848 @dec
2849 def same(x: U) -> U:
2850 ...
2851 reveal_type(same) # N: Revealed type is "def [S] (S`3) -> builtins.list[S`3]"
2852 reveal_type(same(42)) # N: Revealed type is "builtins.list[builtins.int]"
2853 [builtins fixtures/list.pyi]
2854
2855 [case testInferenceAgainstGenericCallableGenericReverse]
2856 from typing import TypeVar, Callable, List
2857
2858 S = TypeVar('S')
2859 T = TypeVar('T')
2860 U = TypeVar('U')
2861
2862 def dec(f: Callable[[S], List[T]]) -> Callable[[S], T]:
2863 ...
2864 def id(x: U) -> U:
2865 ...
2866 reveal_type(dec(id)) # N: Revealed type is "def [T] (builtins.list[T`2]) -> T`2"
2867
2868 @dec
2869 def same(x: U) -> U:
2870 ...
2871 reveal_type(same) # N: Revealed type is "def [T] (builtins.list[T`4]) -> T`4"
2872 reveal_type(same([42])) # N: Revealed type is "builtins.int"
2873 [builtins fixtures/list.pyi]
2874
2875 [case testInferenceAgainstGenericCallableGenericArg]
2876 from typing import TypeVar, Callable, List
2877
2878 S = TypeVar('S')
2879 T = TypeVar('T')
2880 U = TypeVar('U')
2881
2882 def dec(f: Callable[[S], T]) -> Callable[[S], T]:
2883 ...
2884 def test(x: U) -> List[U]:
2885 ...
2886 reveal_type(dec(test)) # N: Revealed type is "def [S] (S`1) -> builtins.list[S`1]"
2887
2888 @dec
2889 def single(x: U) -> List[U]:
2890 ...
2891 reveal_type(single) # N: Revealed type is "def [S] (S`3) -> builtins.list[S`3]"
2892 reveal_type(single(42)) # N: Revealed type is "builtins.list[builtins.int]"
2893 [builtins fixtures/list.pyi]
2894
2895 [case testInferenceAgainstGenericCallableGenericChain]
2896 from typing import TypeVar, Callable, List
2897
2898 S = TypeVar('S')
2899 T = TypeVar('T')
2900 U = TypeVar('U')
2901
2902 def comb(f: Callable[[T], S], g: Callable[[S], U]) -> Callable[[T], U]: ...
2903 def id(x: U) -> U:
2904 ...
2905 reveal_type(comb(id, id)) # N: Revealed type is "def [T] (T`1) -> T`1"
2906 [builtins fixtures/list.pyi]
2907
2908 [case testInferenceAgainstGenericCallableGenericNonLinear]
2909 from typing import TypeVar, Callable, List
2910
2911 S = TypeVar('S')
2912 T = TypeVar('T')
2913 U = TypeVar('U')
2914
2915 def mix(fs: List[Callable[[S], T]]) -> Callable[[S], List[T]]:
2916 def inner(x: S) -> List[T]:
2917 return [f(x) for f in fs]
2918 return inner
2919
2920 # Errors caused by arg *name* mismatch are truly cryptic, but this is a known issue :/
2921 def id(__x: U) -> U:
2922 ...
2923 fs = [id, id, id]
2924 reveal_type(mix(fs)) # N: Revealed type is "def [S] (S`2) -> builtins.list[S`2]"
2925 reveal_type(mix([id, id, id])) # N: Revealed type is "def [S] (S`4) -> builtins.list[S`4]"
2926 [builtins fixtures/list.pyi]
2927
2928 [case testInferenceAgainstGenericCurry]
2929 from typing import Callable, List, TypeVar
2930
2931 S = TypeVar("S")
2932 T = TypeVar("T")
2933 U = TypeVar("U")
2934 V = TypeVar("V")
2935
2936 def dec1(f: Callable[[T], S]) -> Callable[[], Callable[[T], S]]: ...
2937 def dec2(f: Callable[[T, U], S]) -> Callable[[U], Callable[[T], S]]: ...
2938
2939 def test1(x: V) -> V: ...
2940 def test2(x: V, y: V) -> V: ...
2941
2942 reveal_type(dec1(test1)) # N: Revealed type is "def () -> def [T] (T`1) -> T`1"
2943 reveal_type(dec2(test2)) # N: Revealed type is "def [T] (T`3) -> def (T`3) -> T`3"
2944 [builtins fixtures/list.pyi]
2945
2946 [case testInferenceAgainstGenericCallableNewVariable]
2947 from typing import TypeVar, Callable, List
2948
2949 S = TypeVar('S')
2950 T = TypeVar('T')
2951 U = TypeVar('U')
2952
2953 def dec(f: Callable[[S], T]) -> Callable[[S], T]:
2954 ...
2955 def test(x: List[U]) -> List[U]:
2956 ...
2957 reveal_type(dec(test)) # N: Revealed type is "def [U] (builtins.list[U`-1]) -> builtins.list[U`-1]"
2958 [builtins fixtures/list.pyi]
2959
2960 [case testInferenceAgainstGenericCallableGenericAlias]
2961 from typing import TypeVar, Callable, List
2962
2963 S = TypeVar('S')
2964 T = TypeVar('T')
2965 U = TypeVar('U')
2966
2967 A = Callable[[S], T]
2968 B = Callable[[S], List[T]]
2969
2970 def dec(f: A[S, T]) -> B[S, T]:
2971 ...
2972 def id(x: U) -> U:
2973 ...
2974 reveal_type(dec(id)) # N: Revealed type is "def [S] (S`1) -> builtins.list[S`1]"
2975 [builtins fixtures/list.pyi]
2976
2977 [case testInferenceAgainstGenericCallableGenericProtocol]
2978 from typing import TypeVar, Protocol, Generic, Optional
2979
2980 T = TypeVar('T')
2981
2982 class F(Protocol[T]):
2983 def __call__(self, __x: T) -> T: ...
2984
2985 def lift(f: F[T]) -> F[Optional[T]]: ...
2986 def g(x: T) -> T:
2987 return x
2988
2989 reveal_type(lift(g)) # N: Revealed type is "def [T] (T`1 | None) -> T`1 | None"
2990 [builtins fixtures/list.pyi]
2991
2992 [case testInferenceAgainstGenericSplitOrder]
2993 from typing import TypeVar, Callable, List
2994
2995 S = TypeVar('S')
2996 T = TypeVar('T')
2997 U = TypeVar('U')
2998
2999 def dec(f: Callable[[T], S], g: Callable[[T], int]) -> Callable[[T], List[S]]: ...
3000 def id(x: U) -> U:
3001 ...
3002
3003 reveal_type(dec(id, id)) # N: Revealed type is "def (builtins.int) -> builtins.list[builtins.int]"
3004 [builtins fixtures/list.pyi]
3005
3006 [case testInferenceAgainstGenericSplitOrderGeneric]
3007 from typing import TypeVar, Callable, Tuple
3008
3009 S = TypeVar('S')
3010 T = TypeVar('T')
3011 U = TypeVar('U')
3012 V = TypeVar('V')
3013
3014 def dec(f: Callable[[T], S], g: Callable[[T], U]) -> Callable[[T], Tuple[S, U]]: ...
3015 def id(x: V) -> V:
3016 ...
3017
3018 reveal_type(dec(id, id)) # N: Revealed type is "def [T] (T`1) -> tuple[T`1, T`1]"
3019 [builtins fixtures/tuple.pyi]
3020
3021 [case testInferenceAgainstGenericSecondary]
3022 from typing import TypeVar, Callable, List
3023
3024 S = TypeVar('S')
3025 T = TypeVar('T')
3026 U = TypeVar('U')
3027
3028 def dec(f: Callable[[List[T]], List[int]]) -> Callable[[T], T]: ...
3029
3030 @dec
3031 def id(x: U) -> U:
3032 ...
3033 reveal_type(id) # N: Revealed type is "def (builtins.int) -> builtins.int"
3034 [builtins fixtures/tuple.pyi]
3035
3036 [case testInferenceAgainstGenericEllipsisSelfSpecialCase]
3037 from typing import Self, Callable, TypeVar
3038
3039 T = TypeVar("T")
3040 def dec(f: Callable[..., T]) -> Callable[..., T]: ...
3041
3042 class C:
3043 @dec
3044 def test(self) -> Self: ...
3045
3046 c: C
3047 reveal_type(c.test()) # N: Revealed type is "__main__.C"
3048
3049 [case testInferenceAgainstGenericBoundsAndValues]
3050 from typing import TypeVar, Callable, List
3051
3052 class B: ...
3053 class C(B): ...
3054
3055 S = TypeVar('S')
3056 T = TypeVar('T')
3057 UB = TypeVar('UB', bound=B)
3058 UC = TypeVar('UC', bound=C)
3059 V = TypeVar('V', int, str)
3060
3061 def dec1(f: Callable[[S], T]) -> Callable[[S], List[T]]:
3062 ...
3063 def dec2(f: Callable[[UC], T]) -> Callable[[UC], List[T]]:
3064 ...
3065 def id1(x: UB) -> UB:
3066 ...
3067 def id2(x: V) -> V:
3068 ...
3069
3070 reveal_type(dec1(id1)) # N: Revealed type is "def [S <: __main__.B] (S`1) -> builtins.list[S`1]"
3071 reveal_type(dec1(id2)) # N: Revealed type is "def [S in (builtins.int, builtins.str)] (S`3) -> builtins.list[S`3]"
3072 reveal_type(dec2(id1)) # N: Revealed type is "def [UC <: __main__.C] (UC`5) -> builtins.list[UC`5]"
3073 reveal_type(dec2(id2)) # N: Revealed type is "def (Never) -> builtins.list[Never]" \
3074 # E: Argument 1 to "dec2" has incompatible type "Callable[[V], V]"; expected "Callable[[Never], Never]"
3075
3076 [case testInferenceAgainstGenericLambdas]
3077 from typing import TypeVar, Callable, List
3078
3079 S = TypeVar('S')
3080 T = TypeVar('T')
3081
3082 def dec1(f: Callable[[T], T]) -> Callable[[T], List[T]]:
3083 ...
3084 def dec2(f: Callable[[S], T]) -> Callable[[S], List[T]]:
3085 ...
3086 def dec3(f: Callable[[List[S]], T]) -> Callable[[S], T]:
3087 def g(x: S) -> T:
3088 return f([x])
3089 return g
3090 def dec4(f: Callable[[S], List[T]]) -> Callable[[S], T]:
3091 ...
3092 def dec5(f: Callable[[int], T]) -> Callable[[int], List[T]]:
3093 def g(x: int) -> List[T]:
3094 return [f(x)] * x
3095 return g
3096
3097 I = TypeVar("I", bound=int)
3098 def dec4_bound(f: Callable[[I], List[T]]) -> Callable[[I], T]:
3099 ...
3100
3101 reveal_type(dec1(lambda x: x)) # N: Revealed type is "def [T] (T`3) -> builtins.list[T`3]"
3102 reveal_type(dec2(lambda x: x)) # N: Revealed type is "def [S] (S`5) -> builtins.list[S`5]"
3103 reveal_type(dec3(lambda x: x[0])) # N: Revealed type is "def [S] (S`8) -> S`8"
3104 reveal_type(dec4(lambda x: [x])) # N: Revealed type is "def [S] (S`11) -> S`11"
3105 reveal_type(dec1(lambda x: 1)) # N: Revealed type is "def (builtins.int) -> builtins.list[builtins.int]"
3106 reveal_type(dec5(lambda x: x)) # N: Revealed type is "def (builtins.int) -> builtins.list[builtins.int]"
3107 reveal_type(dec3(lambda x: x)) # N: Revealed type is "def [S] (S`19) -> builtins.list[S`19]"
3108 reveal_type(dec4(lambda x: x)) # N: Revealed type is "def [T] (builtins.list[T`23]) -> T`23"
3109 dec4_bound(lambda x: x) # E: Value of type variable "I" of "dec4_bound" cannot be "list[T]"
3110 [builtins fixtures/list.pyi]
3111
3112 [case testInferenceAgainstGenericParamSpecBasicInList]
3113 from typing import TypeVar, Callable, List, Tuple
3114 from typing_extensions import ParamSpec
3115
3116 T = TypeVar('T')
3117 P = ParamSpec('P')
3118 U = TypeVar('U')
3119 V = TypeVar('V')
3120
3121 def dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...
3122 def id(x: U) -> U: ...
3123 def either(x: U, y: U) -> U: ...
3124 def pair(x: U, y: V) -> Tuple[U, V]: ...
3125 reveal_type(dec(id)) # N: Revealed type is "def [T] (x: T`3) -> builtins.list[T`3]"
3126 reveal_type(dec(either)) # N: Revealed type is "def [T] (x: T`5, y: T`5) -> builtins.list[T`5]"
3127 reveal_type(dec(pair)) # N: Revealed type is "def [U, V] (x: U`-1, y: V`-2) -> builtins.list[tuple[U`-1, V`-2]]"
3128 [builtins fixtures/list.pyi]
3129
3130 [case testInferenceAgainstGenericParamSpecBasicDeList]
3131 from typing import TypeVar, Callable, List, Tuple
3132 from typing_extensions import ParamSpec
3133
3134 T = TypeVar('T')
3135 P = ParamSpec('P')
3136 U = TypeVar('U')
3137 V = TypeVar('V')
3138
3139 def dec(f: Callable[P, List[T]]) -> Callable[P, T]: ...
3140 def id(x: U) -> U: ...
3141 def either(x: U, y: U) -> U: ...
3142 reveal_type(dec(id)) # N: Revealed type is "def [T] (x: builtins.list[T`3]) -> T`3"
3143 reveal_type(dec(either)) # N: Revealed type is "def [T] (x: builtins.list[T`5], y: builtins.list[T`5]) -> T`5"
3144 [builtins fixtures/list.pyi]
3145
3146 [case testInferenceAgainstGenericParamSpecPopOff]
3147 from typing import TypeVar, Callable, List, Tuple
3148 from typing_extensions import ParamSpec, Concatenate
3149
3150 T = TypeVar('T')
3151 S = TypeVar('S')
3152 P = ParamSpec('P')
3153 U = TypeVar('U')
3154 V = TypeVar('V')
3155
3156 def dec(f: Callable[Concatenate[T, P], S]) -> Callable[P, Callable[[T], S]]: ...
3157 def id(x: U) -> U: ...
3158 def either(x: U, y: U) -> U: ...
3159 def pair(x: U, y: V) -> Tuple[U, V]: ...
3160 reveal_type(dec(id)) # N: Revealed type is "def () -> def [T] (T`2) -> T`2"
3161 reveal_type(dec(either)) # N: Revealed type is "def [T] (y: T`5) -> def (T`5) -> T`5"
3162 reveal_type(dec(pair)) # N: Revealed type is "def [V] (y: V`-2) -> def [T] (T`8) -> tuple[T`8, V`-2]"
3163 reveal_type(dec(dec)) # N: Revealed type is "def () -> def [T, P, S] (def (T`-1, *P.args, **P.kwargs) -> S`-3) -> def (*P.args, **P.kwargs) -> def (T`-1) -> S`-3"
3164 [builtins fixtures/list.pyi]
3165
3166 [case testInferenceAgainstGenericParamSpecPopOn]
3167 from typing import TypeVar, Callable, List, Tuple
3168 from typing_extensions import ParamSpec, Concatenate
3169
3170 T = TypeVar('T')
3171 S = TypeVar('S')
3172 P = ParamSpec('P')
3173 U = TypeVar('U')
3174 V = TypeVar('V')
3175
3176 def dec(f: Callable[P, Callable[[T], S]]) -> Callable[Concatenate[T, P], S]: ...
3177 def id() -> Callable[[U], U]: ...
3178 def either(x: U) -> Callable[[U], U]: ...
3179 def pair(x: U) -> Callable[[V], Tuple[V, U]]: ...
3180 reveal_type(dec(id)) # N: Revealed type is "def [T] (T`3) -> T`3"
3181 reveal_type(dec(either)) # N: Revealed type is "def [T] (T`6, x: T`6) -> T`6"
3182 reveal_type(dec(pair)) # N: Revealed type is "def [T, U] (T`9, x: U`-1) -> tuple[T`9, U`-1]"
3183 # This is counter-intuitive but looks correct, dec matches itself only if P can be empty
3184 reveal_type(dec(dec)) # N: Revealed type is "def [T, S] (T`13, f: def () -> def (T`13) -> S`14) -> S`14"
3185 [builtins fixtures/list.pyi]
3186
3187 [case testInferenceAgainstGenericParamSpecVsParamSpec]
3188 from typing import TypeVar, Callable, List, Tuple, Generic
3189 from typing_extensions import ParamSpec, Concatenate
3190
3191 T = TypeVar('T')
3192 P = ParamSpec('P')
3193 Q = ParamSpec('Q')
3194
3195 class Foo(Generic[P]): ...
3196 class Bar(Generic[P, T]): ...
3197
3198 def dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...
3199 def f(*args: Q.args, **kwargs: Q.kwargs) -> Foo[Q]: ...
3200 reveal_type(dec(f)) # N: Revealed type is "def [P] (*P.args, **P.kwargs) -> builtins.list[__main__.Foo[P`2]]"
3201 g: Callable[Concatenate[int, Q], Foo[Q]]
3202 reveal_type(dec(g)) # N: Revealed type is "def [Q] (builtins.int, *Q.args, **Q.kwargs) -> builtins.list[__main__.Foo[Q`-1]]"
3203 h: Callable[Concatenate[T, Q], Bar[Q, T]]
3204 reveal_type(dec(h)) # N: Revealed type is "def [T, Q] (T`-1, *Q.args, **Q.kwargs) -> builtins.list[__main__.Bar[Q`-2, T`-1]]"
3205 [builtins fixtures/list.pyi]
3206
3207 [case testInferenceAgainstGenericParamSpecVsParamSpecConcatenate]
3208 from typing import TypeVar, Callable, List, Tuple, Generic
3209 from typing_extensions import ParamSpec, Concatenate
3210
3211 T = TypeVar('T')
3212 P = ParamSpec('P')
3213 Q = ParamSpec('Q')
3214
3215 class Foo(Generic[P]): ...
3216
3217 def dec(f: Callable[P, int]) -> Callable[P, Foo[P]]: ...
3218 h: Callable[Concatenate[T, Q], int]
3219 g: Callable[Concatenate[T, Q], int]
3220 h = g
3221 reveal_type(dec(h)) # N: Revealed type is "def [T, Q] (T`-1, *Q.args, **Q.kwargs) -> __main__.Foo[[T`-1, **Q`-2]]"
3222 [builtins fixtures/list.pyi]
3223
3224 [case testInferenceAgainstGenericParamSpecSecondary]
3225 from typing import TypeVar, Callable, List, Tuple, Generic
3226 from typing_extensions import ParamSpec, Concatenate
3227
3228 T = TypeVar('T')
3229 P = ParamSpec('P')
3230 Q = ParamSpec('Q')
3231
3232 class Foo(Generic[P]): ...
3233
3234 def dec(f: Callable[P, Foo[P]]) -> Callable[P, Foo[P]]: ...
3235 g: Callable[[T], Foo[[int]]]
3236 reveal_type(dec(g)) # N: Revealed type is "def (builtins.int) -> __main__.Foo[[builtins.int]]"
3237 h: Callable[Q, Foo[[int]]]
3238 reveal_type(dec(g)) # N: Revealed type is "def (builtins.int) -> __main__.Foo[[builtins.int]]"
3239 [builtins fixtures/list.pyi]
3240
3241 [case testInferenceAgainstGenericParamSpecSecondOrder]
3242 from typing import TypeVar, Callable
3243 from typing_extensions import ParamSpec, Concatenate
3244
3245 T = TypeVar('T')
3246 S = TypeVar('S')
3247 P = ParamSpec('P')
3248 Q = ParamSpec('Q')
3249 U = TypeVar('U')
3250 W = ParamSpec('W')
3251
3252 def transform(
3253 dec: Callable[[Callable[P, T]], Callable[Q, S]]
3254 ) -> Callable[[Callable[Concatenate[int, P], T]], Callable[Concatenate[int, Q], S]]: ...
3255
3256 def dec(f: Callable[W, U]) -> Callable[W, U]: ...
3257 def dec2(f: Callable[Concatenate[str, W], U]) -> Callable[Concatenate[bytes, W], U]: ...
3258 reveal_type(transform(dec)) # N: Revealed type is "def [P, T] (def (builtins.int, *P.args, **P.kwargs) -> T`3) -> def (builtins.int, *P.args, **P.kwargs) -> T`3"
3259 reveal_type(transform(dec2)) # N: Revealed type is "def [W, T] (def (builtins.int, builtins.str, *W.args, **W.kwargs) -> T`7) -> def (builtins.int, builtins.bytes, *W.args, **W.kwargs) -> T`7"
3260 [builtins fixtures/tuple.pyi]
3261
3262 [case testNoAccidentalVariableClashInNestedGeneric]
3263 from typing import TypeVar, Callable, Generic, Tuple
3264
3265 T = TypeVar('T')
3266 S = TypeVar('S')
3267 U = TypeVar('U')
3268
3269 def pipe(x: T, f1: Callable[[T], S], f2: Callable[[S], U]) -> U: ...
3270 def and_then(a: T) -> Callable[[S], Tuple[S, T]]: ...
3271
3272 def apply(a: S, b: T) -> None:
3273 v1 = and_then(b)
3274 v2: Callable[[Tuple[S, T]], None]
3275 return pipe(a, v1, v2)
3276 [builtins fixtures/tuple.pyi]
3277
3278 [case testInferenceAgainstGenericParamSpecSpuriousBoundsNotUsed]
3279 from typing import TypeVar, Callable, Generic
3280 from typing_extensions import ParamSpec, Concatenate
3281
3282 Q = ParamSpec("Q")
3283 class Foo(Generic[Q]): ...
3284
3285 T1 = TypeVar("T1", bound=Foo[...])
3286 T2 = TypeVar("T2", bound=Foo[...])
3287 P = ParamSpec("P")
3288 def pop_off(fn: Callable[Concatenate[T1, P], T2]) -> Callable[P, Callable[[T1], T2]]:
3289 ...
3290
3291 @pop_off
3292 def test(command: Foo[Q]) -> Foo[Q]: ...
3293 reveal_type(test) # N: Revealed type is "def () -> def [Q] (__main__.Foo[Q`-1]) -> __main__.Foo[Q`-1]"
3294 [builtins fixtures/tuple.pyi]
3295
3296 [case testInferenceAgainstGenericVariadicBasicInList]
3297 from typing import Tuple, TypeVar, List, Callable
3298 from typing_extensions import Unpack, TypeVarTuple
3299
3300 T = TypeVar("T")
3301 Ts = TypeVarTuple("Ts")
3302 def dec(f: Callable[[Unpack[Ts]], T]) -> Callable[[Unpack[Ts]], List[T]]: ...
3303
3304 U = TypeVar("U")
3305 V = TypeVar("V")
3306 def id(x: U) -> U: ...
3307 def either(x: U, y: U) -> U: ...
3308 def pair(x: U, y: V) -> Tuple[U, V]: ...
3309
3310 reveal_type(dec(id)) # N: Revealed type is "def [T] (T`3) -> builtins.list[T`3]"
3311 reveal_type(dec(either)) # N: Revealed type is "def [T] (T`5, T`5) -> builtins.list[T`5]"
3312 reveal_type(dec(pair)) # N: Revealed type is "def [U, V] (U`-1, V`-2) -> builtins.list[tuple[U`-1, V`-2]]"
3313 [builtins fixtures/tuple.pyi]
3314
3315 [case testInferenceAgainstGenericVariadicBasicDeList]
3316 from typing import Tuple, TypeVar, List, Callable
3317 from typing_extensions import Unpack, TypeVarTuple
3318
3319 T = TypeVar("T")
3320 Ts = TypeVarTuple("Ts")
3321 def dec(f: Callable[[Unpack[Ts]], List[T]]) -> Callable[[Unpack[Ts]], T]: ...
3322
3323 U = TypeVar("U")
3324 V = TypeVar("V")
3325 def id(x: U) -> U: ...
3326 def either(x: U, y: U) -> U: ...
3327
3328 reveal_type(dec(id)) # N: Revealed type is "def [T] (builtins.list[T`3]) -> T`3"
3329 reveal_type(dec(either)) # N: Revealed type is "def [T] (builtins.list[T`5], builtins.list[T`5]) -> T`5"
3330 [builtins fixtures/tuple.pyi]
3331
3332 [case testInferenceAgainstGenericVariadicPopOff]
3333 from typing import TypeVar, Callable, List, Tuple
3334 from typing_extensions import Unpack, TypeVarTuple
3335
3336 T = TypeVar("T")
3337 S = TypeVar("S")
3338 Ts = TypeVarTuple("Ts")
3339 def dec(f: Callable[[T, Unpack[Ts]], S]) -> Callable[[Unpack[Ts]], Callable[[T], S]]: ...
3340
3341 U = TypeVar("U")
3342 V = TypeVar("V")
3343 def id(x: U) -> U: ...
3344 def either(x: U, y: U) -> U: ...
3345 def pair(x: U, y: V) -> Tuple[U, V]: ...
3346
3347 reveal_type(dec(id)) # N: Revealed type is "def () -> def [T] (T`2) -> T`2"
3348 reveal_type(dec(either)) # N: Revealed type is "def [T] (T`5) -> def (T`5) -> T`5"
3349 reveal_type(dec(pair)) # N: Revealed type is "def [V] (V`-2) -> def [T] (T`8) -> tuple[T`8, V`-2]"
3350 reveal_type(dec(dec)) # N: Revealed type is "def () -> def [T, Ts, S] (def (T`-1, *Unpack[Ts`-2]) -> S`-3) -> def (*Unpack[Ts`-2]) -> def (T`-1) -> S`-3"
3351 [builtins fixtures/list.pyi]
3352
3353 [case testInferenceAgainstGenericVariadicPopOn]
3354 from typing import TypeVar, Callable, List, Tuple
3355 from typing_extensions import Unpack, TypeVarTuple
3356
3357 T = TypeVar("T")
3358 S = TypeVar("S")
3359 Ts = TypeVarTuple("Ts")
3360 def dec(f: Callable[[Unpack[Ts]], Callable[[T], S]]) -> Callable[[T, Unpack[Ts]], S]: ...
3361
3362 U = TypeVar("U")
3363 V = TypeVar("V")
3364 def id() -> Callable[[U], U]: ...
3365 def either(x: U) -> Callable[[U], U]: ...
3366 def pair(x: U) -> Callable[[V], Tuple[V, U]]: ...
3367
3368 reveal_type(dec(id)) # N: Revealed type is "def [T] (T`3) -> T`3"
3369 reveal_type(dec(either)) # N: Revealed type is "def [T] (T`6, T`6) -> T`6"
3370 reveal_type(dec(pair)) # N: Revealed type is "def [T, U] (T`9, U`-1) -> tuple[T`9, U`-1]"
3371 # This is counter-intuitive but looks correct, dec matches itself only if Ts is empty
3372 reveal_type(dec(dec)) # N: Revealed type is "def [T, S] (T`13, def () -> def (T`13) -> S`14) -> S`14"
3373 [builtins fixtures/list.pyi]
3374
3375 [case testInferenceAgainstGenericVariadicVsVariadic]
3376 from typing import TypeVar, Callable, List, Generic
3377 from typing_extensions import Unpack, TypeVarTuple
3378
3379 T = TypeVar("T")
3380 S = TypeVar("S")
3381 Ts = TypeVarTuple("Ts")
3382 Us = TypeVarTuple("Us")
3383
3384 class Foo(Generic[Unpack[Ts]]): ...
3385 class Bar(Generic[Unpack[Ts], T]): ...
3386
3387 def dec(f: Callable[[Unpack[Ts]], T]) -> Callable[[Unpack[Ts]], List[T]]: ...
3388 def f(*args: Unpack[Us]) -> Foo[Unpack[Us]]: ...
3389 reveal_type(dec(f)) # N: Revealed type is "def [Ts] (*Unpack[Ts`2]) -> builtins.list[__main__.Foo[Unpack[Ts`2]]]"
3390 g: Callable[[Unpack[Us]], Foo[Unpack[Us]]]
3391 reveal_type(dec(g)) # N: Revealed type is "def [Ts] (*Unpack[Ts`4]) -> builtins.list[__main__.Foo[Unpack[Ts`4]]]"
3392 [builtins fixtures/list.pyi]
3393
3394 [case testInferenceAgainstGenericVariadicVsVariadicConcatenate]
3395 from typing import TypeVar, Callable, Generic
3396 from typing_extensions import Unpack, TypeVarTuple
3397
3398 T = TypeVar("T")
3399 S = TypeVar("S")
3400 Ts = TypeVarTuple("Ts")
3401 Us = TypeVarTuple("Us")
3402
3403 class Foo(Generic[Unpack[Ts]]): ...
3404
3405 def dec(f: Callable[[Unpack[Ts]], int]) -> Callable[[Unpack[Ts]], Foo[Unpack[Ts]]]: ...
3406 h: Callable[[T, Unpack[Us]], int]
3407 g: Callable[[T, Unpack[Us]], int]
3408 h = g
3409 reveal_type(dec(h)) # N: Revealed type is "def [T, Us] (T`-1, *Unpack[Us`-2]) -> __main__.Foo[T`-1, Unpack[Us`-2]]"
3410 [builtins fixtures/list.pyi]
3411
3412 [case testInferenceAgainstGenericVariadicSecondary]
3413 from typing import TypeVar, Callable, Generic
3414 from typing_extensions import Unpack, TypeVarTuple
3415
3416 T = TypeVar("T")
3417 Ts = TypeVarTuple("Ts")
3418 Us = TypeVarTuple("Us")
3419
3420 class Foo(Generic[Unpack[Ts]]): ...
3421
3422 def dec(f: Callable[[Unpack[Ts]], Foo[Unpack[Ts]]]) -> Callable[[Unpack[Ts]], Foo[Unpack[Ts]]]: ...
3423 g: Callable[[T], Foo[int]]
3424 reveal_type(dec(g)) # N: Revealed type is "def (builtins.int) -> __main__.Foo[builtins.int]"
3425 h: Callable[[Unpack[Us]], Foo[int]]
3426 reveal_type(dec(h)) # N: Revealed type is "def (builtins.int) -> __main__.Foo[builtins.int]"
3427 [builtins fixtures/list.pyi]
3428
3429 [case testTypeApplicationGenericConstructor]
3430 from typing import Generic, TypeVar, Callable
3431
3432 T = TypeVar("T")
3433 S = TypeVar("S")
3434 class C(Generic[T]):
3435 def __init__(self, f: Callable[[S], T], x: S) -> None:
3436 self.x = f(x)
3437
3438 reveal_type(C[int]) # N: Revealed type is "def [S] (f: def (S`-1) -> builtins.int, x: S`-1) -> __main__.C[builtins.int]"
3439 Alias = C[int]
3440 C[int, str] # E: Type application has too many types (1 expected)
3441
3442 [case testHigherOrderGenericPartial]
3443 from typing import TypeVar, Callable
3444
3445 T = TypeVar("T")
3446 S = TypeVar("S")
3447 U = TypeVar("U")
3448 def apply(f: Callable[[T], S], x: T) -> S: ...
3449 def id(x: U) -> U: ...
3450
3451 A1 = TypeVar("A1")
3452 A2 = TypeVar("A2")
3453 R = TypeVar("R")
3454 def fake_partial(fun: Callable[[A1, A2], R], arg: A1) -> Callable[[A2], R]: ...
3455
3456 f_pid = fake_partial(apply, id)
3457 reveal_type(f_pid) # N: Revealed type is "def [A2] (A2`2) -> A2`2"
3458 reveal_type(f_pid(1)) # N: Revealed type is "builtins.int"
3459
3460 [case testInvalidTypeVarParametersConcrete]
3461 from typing import Callable, Generic, ParamSpec, Protocol, TypeVar, overload
3462
3463 P = ParamSpec('P')
3464 P2 = ParamSpec('P2')
3465 R = TypeVar('R')
3466 R2 = TypeVar('R2')
3467
3468 class C(Generic[P, R, P2, R2]): ...
3469
3470 class Proto(Protocol[P, R]):
3471 @overload
3472 def __call__(self, f: Callable[P2, R2]) -> C[P2, R2, ..., R]: ...
3473 @overload
3474 def __call__(self, **kwargs) -> C[P, R, ..., [int, str]]: ... # E: Cannot use "[int, str]" for regular type variable, only for ParamSpec
3475 [builtins fixtures/tuple.pyi]
3476
3477 [case testInvalidTypeVarParametersArbitrary]
3478 from typing import Callable, Generic, ParamSpec, Protocol, TypeVar, overload
3479
3480 P = ParamSpec('P')
3481 P2 = ParamSpec('P2')
3482 R = TypeVar('R')
3483 R2 = TypeVar('R2')
3484
3485 class C(Generic[P, R, P2, R2]): ...
3486
3487 class Proto(Protocol[P, R]):
3488 @overload
3489 def __call__(self, f: Callable[P2, R2]) -> C[P2, R2, ..., R]: ...
3490 @overload
3491 def __call__(self, **kwargs) -> C[P, R, ..., ...]: ... # E: Cannot use "[VarArg(Any), KwArg(Any)]" for regular type variable, only for ParamSpec
3492 [builtins fixtures/tuple.pyi]
3493
3494 [case testGenericOverloadOverlapUnion]
3495 from typing import TypeVar, overload, Union, Generic
3496
3497 K = TypeVar("K")
3498 V = TypeVar("V")
3499 T = TypeVar("T")
3500
3501 class C(Generic[K, V]):
3502 @overload
3503 def pop(self, key: K) -> V: ...
3504 @overload
3505 def pop(self, key: K, default: Union[V, T] = ...) -> Union[V, T]: ...
3506 def pop(self, key: K, default: Union[V, T] = ...) -> Union[V, T]:
3507 ...
3508
3509 [case testOverloadedGenericInit]
3510 from typing import TypeVar, overload, Union, Generic
3511
3512 T = TypeVar("T")
3513 S = TypeVar("S")
3514
3515 class Int(Generic[T]): ...
3516 class Str(Generic[T]): ...
3517
3518 class C(Generic[T]):
3519 @overload
3520 def __init__(self: C[Int[S]], x: int, y: S) -> None: ...
3521 @overload
3522 def __init__(self: C[Str[S]], x: str, y: S) -> None: ...
3523 def __init__(self, x, y) -> None: ...
3524
3525 def foo(x: T):
3526 reveal_type(C) # N: Revealed type is "Overload(def [T, S] (x: builtins.int, y: S`-1) -> __main__.C[__main__.Int[S`-1]], def [T, S] (x: builtins.str, y: S`-1) -> __main__.C[__main__.Str[S`-1]])"
3527 reveal_type(C(0, x)) # N: Revealed type is "__main__.C[__main__.Int[T`-1]]"
3528 reveal_type(C("yes", x)) # N: Revealed type is "__main__.C[__main__.Str[T`-1]]"
3529
3530 [case testInstanceMethodBoundOnClass]
3531 from typing import TypeVar, Generic
3532
3533 T = TypeVar("T")
3534 class B(Generic[T]):
3535 def foo(self) -> T: ...
3536 class C(B[T]): ...
3537 class D(C[int]): ...
3538
3539 reveal_type(B.foo) # N: Revealed type is "def [T] (self: __main__.B[T`1]) -> T`1"
3540 reveal_type(B[int].foo) # N: Revealed type is "def (self: __main__.B[builtins.int]) -> builtins.int"
3541 reveal_type(C.foo) # N: Revealed type is "def [T] (self: __main__.B[T`1]) -> T`1"
3542 reveal_type(C[int].foo) # N: Revealed type is "def (self: __main__.B[builtins.int]) -> builtins.int"
3543 reveal_type(D.foo) # N: Revealed type is "def (self: __main__.B[builtins.int]) -> builtins.int"
3544
3545 [case testDeterminismFromJoinOrderingInSolver1]
3546 # Used to fail non-deterministically
3547 # https://github.com/python/mypy/issues/19121
3548 from __future__ import annotations
3549 from typing import Generic, Iterable, Iterator, Self, TypeVar
3550
3551 _T1 = TypeVar("_T1")
3552 _T2 = TypeVar("_T2")
3553 _T3 = TypeVar("_T3")
3554 _T_co = TypeVar("_T_co", covariant=True)
3555
3556 class Base(Iterable[_T1]):
3557 def __iter__(self) -> Iterator[_T1]: ...
3558 class A(Base[_T1]): ...
3559 class B(Base[_T1]): ...
3560 class C(Base[_T1]): ...
3561 class D(Base[_T1]): ...
3562 class E(Base[_T1]): ...
3563
3564 class zip2(Generic[_T_co]):
3565 def __new__(
3566 cls,
3567 iter1: Iterable[_T1],
3568 iter2: Iterable[_T2],
3569 iter3: Iterable[_T3],
3570 ) -> zip2[tuple[_T1, _T2, _T3]]: ...
3571 def __iter__(self) -> Self: ...
3572 def __next__(self) -> _T_co: ...
3573
3574 def draw(
3575 colors1: A[str] | B[str] | C[int] | D[int | str],
3576 colors2: A[str] | B[str] | C[int] | D[int | str],
3577 colors3: A[str] | B[str] | C[int] | D[int | str],
3578 ) -> None:
3579 for c1, c2, c3 in zip2(colors1, colors2, colors3):
3580 reveal_type(c1) # N: Revealed type is "builtins.int | builtins.str"
3581 reveal_type(c2) # N: Revealed type is "builtins.int | builtins.str"
3582 reveal_type(c3) # N: Revealed type is "builtins.int | builtins.str"
3583
3584 def takes_int_str_none(x: int | str | None) -> None: ...
3585
3586 def draw_none(
3587 colors1: A[str] | B[str] | C[int] | D[None],
3588 colors2: A[str] | B[str] | C[int] | D[None],
3589 colors3: A[str] | B[str] | C[int] | D[None],
3590 ) -> None:
3591 for c1, c2, c3 in zip2(colors1, colors2, colors3):
3592 # TODO: can't do reveal type because the union order is not deterministic
3593 takes_int_str_none(c1)
3594 takes_int_str_none(c2)
3595 takes_int_str_none(c3)
3596 [builtins fixtures/tuple.pyi]
3597
3598 [case testDeterminismFromJoinOrderingInSolver2]
3599 # Used to fail non-deterministically
3600 # https://github.com/python/mypy/issues/21445
3601 from typing import Generic, Iterable, TypeVar, overload
3602
3603 class A: ...
3604
3605 @overload
3606 def f0(a: A, b: object, /) -> object: ...
3607 @overload
3608 def f0(a: object, b: int, /) -> object: ...
3609 def f0(a, b, /): ...
3610
3611 @overload
3612 def f1(a: int, b: object, /) -> object: ...
3613 @overload
3614 def f1(a: object, b: A, /) -> object: ...
3615 def f1(a, b, /): ...
3616
3617 def g(a, b, /): ...
3618
3619 T = TypeVar("T")
3620 K = TypeVar("K")
3621 V = TypeVar("V")
3622
3623 class ziplike(Generic[T]):
3624 def __new__(cls, x: str, y: tuple[V, ...], /) -> ziplike[tuple[str, V]]:
3625 raise
3626 def __iter__(self) -> ziplike[T]:
3627 return self
3628 def __next__(self) -> T:
3629 raise
3630
3631 class dictlike(Generic[K, V]):
3632 def __init__(self, arg: Iterable[tuple[K, V]]) -> None: pass
3633
3634 x = dictlike(ziplike("012", (f0, f1, g)))
3635 reveal_type(x) # N: Revealed type is "__main__.dictlike[builtins.str, Overload(def (Any, Any) -> Any, def (Any, Any) -> Any, def (Any, Any) -> Any, def (Any, Any) -> Any)]"
3636 [builtins fixtures/dict.pyi]
3637
3638 [case testPropertyWithGenericSetter]
3639 from typing import TypeVar
3640
3641 class B: ...
3642 class C(B): ...
3643 T = TypeVar("T", bound=B)
3644
3645 class Test:
3646 @property
3647 def foo(self) -> list[C]: ...
3648 @foo.setter
3649 def foo(self, val: list[T]) -> None: ...
3650
3651 t1: Test
3652 t2: Test
3653
3654 lb: list[B]
3655 lc: list[C]
3656 li: list[int]
3657
3658 t1.foo = lb
3659 t1.foo = lc
3660 t1.foo = li # E: Value of type variable "T" of "foo" of "Test" cannot be "int"
3661
3662 t2.foo = [B()]
3663 t2.foo = [C()]
3664 t2.foo = [1] # E: Value of type variable "T" of "foo" of "Test" cannot be "int"
3665 [builtins fixtures/property.pyi]
3666
3667 [case testEmptyParamSpecConsistency]
3668 from typing import Generic, Callable
3669 from typing_extensions import ParamSpec
3670
3671 P = ParamSpec("P")
3672 class X1(Generic[P]):
3673 def __call__(self, *a: P.args, **k: P.kwargs) -> None: ...
3674 X2 = Callable[P, None]
3675
3676 x1: X1[()]
3677 x2: X2[()]
3678
3679 reveal_type(x1) # N: Revealed type is "__main__.X1[[]]"
3680 reveal_type(x2) # N: Revealed type is "def ()"
3681
3682 x1()
3683 x1(5) # E: Too many arguments for "__call__" of "X1"
3684 x2()
3685 x2(5) # E: Too many arguments
3686 [builtins fixtures/tuple.pyi]
3687
3688 [case testMissingTypeArgsInApplication]
3689 from typing import Generic
3690 from typing_extensions import Unpack, TypeVarTuple, ParamSpec
3691
3692 Ts = TypeVarTuple("Ts")
3693 P = ParamSpec("P")
3694
3695 class CanHaveZero1(Generic[Unpack[Ts]]): ...
3696 class CanHaveZero2(Generic[P]): ...
3697
3698 ok1: CanHaveZero1[()]
3699 ok2: CanHaveZero2[()]
3700 ok3: tuple[()]
3701
3702 reveal_type(ok1) # N: Revealed type is "__main__.CanHaveZero1[()]"
3703 reveal_type(ok2) # N: Revealed type is "__main__.CanHaveZero2[[]]"
3704 reveal_type(ok3) # N: Revealed type is "tuple[()]"
3705
3706 bad1: list[()] = [] # E: "list" expects 1 type argument, but none given
3707 [builtins fixtures/tuple.pyi]
3708
3709 [case testMissingTypeArgsInApplicationStrict]
3710 # flags: --strict
3711 from typing import Generic
3712 from typing_extensions import Unpack, TypeVarTuple, ParamSpec
3713
3714 Ts = TypeVarTuple("Ts")
3715 P = ParamSpec("P")
3716
3717 class CanHaveZero1(Generic[Unpack[Ts]]): ...
3718 class CanHaveZero2(Generic[P]): ...
3719
3720 ok1: CanHaveZero1[()]
3721 ok2: CanHaveZero2[()]
3722 ok3: tuple[()]
3723
3724 reveal_type(ok1) # N: Revealed type is "__main__.CanHaveZero1[()]"
3725 reveal_type(ok2) # N: Revealed type is "__main__.CanHaveZero2[[]]"
3726 reveal_type(ok3) # N: Revealed type is "tuple[()]"
3727
3728 bad1: list[()] = [] # E: "list" expects 1 type argument, but none given \
3729 # E: Missing type arguments for generic type "list"
3730 [builtins fixtures/tuple.pyi]
3731
3732 [case testGenericClassAsArgumentToType]
3733 from typing import TypeVar, Generic
3734
3735 T = TypeVar("T")
3736 def test(tp: type[T]) -> T: ...
3737
3738 class C(Generic[T]): ...
3739 reveal_type(test(C)) # N: Revealed type is "__main__.C[Any]"