Debian Codegraph @

test-data/unit/check-inference.test

raw
1 -- Inferring locals/globals with simple types
2 -- ------------------------------------------
3
4
5 [case testInferSimpleGvarType]
6 class A: pass
7 class B: pass
8
9 x = A()
10 y = B()
11 if int():
12 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
13 if int():
14 x = A()
15 if int():
16 x = y # E: Incompatible types in assignment (expression has type "B", variable has type "A")
17 if int():
18 x = x
19 [case testInferSimpleLvarType]
20 import typing
21 def f() -> None:
22 x = A()
23 y = B()
24 if int():
25 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
26 x = A()
27 x = y # E: Incompatible types in assignment (expression has type "B", variable has type "A")
28 x = x
29 class A: pass
30 class B: pass
31 [out]
32
33 [case testLvarInitializedToVoid]
34 import typing
35 def f() -> None:
36 a = g() # E: "g" does not return a value (it only ever returns None)
37 #b, c = g() # "g" does not return a value (it only ever returns None) TODO
38
39 def g() -> None: pass
40 [out]
41
42 [case testInferringLvarTypeFromArgument]
43 import typing
44 def f(a: 'A') -> None:
45 b = a
46 if int():
47 b = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
48 b = a
49 a = b
50
51 class A: pass
52 class B: pass
53 [out]
54
55 [case testInferringLvarTypeFromGvar]
56
57 g: B
58
59 def f() -> None:
60 a = g
61 if int():
62 a = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
63 a = B()
64
65 class A: pass
66 class B: pass
67 [out]
68
69 [case testInferringImplicitDynamicTypeForLvar]
70 import typing
71 def f() -> None:
72 a = g()
73 None(a) # E: "None" not callable
74 a.x()
75
76 def g(): pass
77 [out]
78
79 [case testInferringExplicitDynamicTypeForLvar]
80 from typing import Any
81 g: Any
82
83 def f(a: Any) -> None:
84 b = g
85 None(b) # E: "None" not callable
86 a.x()
87 [out]
88
89
90 -- Inferring types of local variables with complex types
91 -- -----------------------------------------------------
92
93
94 [case testInferringTupleTypeForLvar]
95
96 def f() -> None:
97 a = A(), B()
98 aa: A
99 bb: B
100 if int():
101 bb = a[0] # E: Incompatible types in assignment (expression has type "A", variable has type "B")
102 aa = a[1] # E: Incompatible types in assignment (expression has type "B", variable has type "A")
103 aa = a[0]
104 bb = a[1]
105
106 class A: pass
107 class B: pass
108 [builtins fixtures/tuple.pyi]
109 [out]
110
111 [case testInferringTupleTypeForLvarWithNones]
112 import typing
113 def f() -> None:
114 a = A(), None
115 b = None, A()
116
117 class A: pass
118 [builtins fixtures/tuple.pyi]
119 [out]
120
121 [case testInferringGenericTypeForLvar]
122 from typing import TypeVar, Generic
123 T = TypeVar('T')
124 class A(Generic[T]): pass
125 a_i: A[int]
126 a_s: A[str]
127
128 def f() -> None:
129 a_int = A() # type: A[int]
130 a = a_int
131 if int():
132 a = a_s # E: Incompatible types in assignment (expression has type "A[str]", variable has type "A[int]")
133 a = a_i
134 [builtins fixtures/tuple.pyi]
135 [out]
136
137 [case testInferringFunctionTypeForLvar]
138 import typing
139 def f() -> None:
140 a = g
141 a(B()) # E: Argument 1 has incompatible type "B"; expected "A"
142 a(A())
143
144 def g(a: 'A') -> None: pass
145
146 class A: pass
147 class B: pass
148 [out]
149
150 [case testInferringFunctionTypeForLvarFromTypeObject]
151 import typing
152 def f() -> None:
153 a = A
154 a(A()) # E: Too many arguments
155 a()
156 t = a # type: type
157
158 class A: pass
159 [out]
160
161
162 -- Inferring variable types in multiple definition
163 -- -----------------------------------------------
164
165
166 [case testInferringLvarTypesInMultiDef]
167 import typing
168 def f() -> None:
169 a, b = A(), B()
170 if int():
171 a = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
172 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
173 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
174
175 a = A()
176 b = B()
177
178 class A: pass
179 class B: pass
180 [out]
181
182 [case testInferringLvarTypesInTupleAssignment]
183 from typing import Tuple
184 def f() -> None:
185 t: Tuple[A, B]
186 a, b = t
187 if int():
188 a = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
189 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
190 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
191
192 a = A()
193 b = B()
194
195 class A: pass
196 class B: pass
197 [builtins fixtures/tuple.pyi]
198 [out]
199
200 [case testInferringLvarTypesInNestedTupleAssignment1]
201 from typing import Tuple
202 def f() -> None:
203 t: Tuple[A, B]
204 a1, (a, b) = A(), t
205 if int():
206 a = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
207 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
208 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
209
210 a = A()
211 b = B()
212
213 class A: pass
214 class B: pass
215 [builtins fixtures/tuple.pyi]
216 [out]
217
218 [case testInferringLvarTypesInNestedTupleAssignment2]
219 import typing
220 def f() -> None:
221 a, (b, c) = A(), (B(), C())
222 if int():
223 a = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
224 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
225 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
226 c = A() # E: Incompatible types in assignment (expression has type "A", variable has type "C")
227
228 a = A()
229 b = B()
230 c = C()
231
232 class A: pass
233 class B: pass
234 class C: pass
235 [out]
236
237 [case testInferringLvarTypesInNestedListAssignment]
238 import typing
239 def f() -> None:
240 a, (b, c) = A(), [B(), C()]
241 if int():
242 a = b # E: Incompatible types in assignment (expression has type "B", variable has type "A")
243 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
244 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
245 c = A() # E: Incompatible types in assignment (expression has type "A", variable has type "C")
246
247 a = A()
248 b = B()
249 c = C()
250
251 class A: pass
252 class B: pass
253 class C: pass
254 [out]
255
256 [case testInferringLvarTypesInMultiDefWithNoneTypes]
257 import typing
258 def f() -> None:
259 a, b = A(), None
260 c, d = None, A()
261
262 class A: pass
263 [out]
264
265 [case testInferringLvarTypesInNestedTupleAssignmentWithNoneTypes]
266 import typing
267 def f() -> None:
268 a1, (a2, b) = A(), (A(), None)
269
270 class A: pass
271 [out]
272
273 [case testClassObjectsNotUnpackableWithoutIterableMetaclass]
274 from typing import Type
275
276 class Foo: ...
277 A: Type[Foo] = Foo
278 a, b = Foo # E: "type[Foo]" object is not iterable
279 c, d = A # E: "type[Foo]" object is not iterable
280
281 class Meta(type): ...
282 class Bar(metaclass=Meta): ...
283 B: Type[Bar] = Bar
284 e, f = Bar # E: "type[Bar]" object is not iterable
285 g, h = B # E: "type[Bar]" object is not iterable
286
287 reveal_type(a) # E: Cannot determine type of "a" # N: Revealed type is "Any"
288 reveal_type(b) # E: Cannot determine type of "b" # N: Revealed type is "Any"
289 reveal_type(c) # E: Cannot determine type of "c" # N: Revealed type is "Any"
290 reveal_type(d) # E: Cannot determine type of "d" # N: Revealed type is "Any"
291 reveal_type(e) # E: Cannot determine type of "e" # N: Revealed type is "Any"
292 reveal_type(f) # E: Cannot determine type of "f" # N: Revealed type is "Any"
293 reveal_type(g) # E: Cannot determine type of "g" # N: Revealed type is "Any"
294 reveal_type(h) # E: Cannot determine type of "h" # N: Revealed type is "Any"
295 [out]
296
297 [case testInferringLvarTypesUnpackedFromIterableClassObject]
298 from typing import Iterator, Type, TypeVar, Union, overload
299 class Meta(type):
300 def __iter__(cls) -> Iterator[int]:
301 yield from [1, 2, 3]
302
303 class Meta2(type):
304 def __iter__(cls) -> Iterator[str]:
305 yield from ["foo", "bar", "baz"]
306
307 class Meta3(type): ...
308
309 class Foo(metaclass=Meta): ...
310 class Bar(metaclass=Meta2): ...
311 class Baz(metaclass=Meta3): ...
312 class Spam: ...
313
314 class Eggs(metaclass=Meta):
315 @overload
316 def __init__(self, x: int) -> None: ...
317 @overload
318 def __init__(self, x: int, y: int, z: int) -> None: ...
319 def __init__(self, x: int, y: int = ..., z: int = ...) -> None: ...
320
321 A: Type[Foo] = Foo
322 B: Type[Union[Foo, Bar]] = Foo
323 C: Union[Type[Foo], Type[Bar]] = Foo
324 D: Type[Union[Foo, Baz]] = Foo
325 E: Type[Union[Foo, Spam]] = Foo
326 F: Type[Eggs] = Eggs
327 G: Type[Union[Foo, Eggs]] = Foo
328
329 a, b, c = Foo
330 d, e, f = A
331 g, h, i = B
332 j, k, l = C
333 m, n, o = D # E: "type[Baz]" object is not iterable
334 p, q, r = E # E: "type[Spam]" object is not iterable
335 s, t, u = Eggs
336 v, w, x = F
337 y, z, aa = G
338
339 for var in [a, b, c, d, e, f, s, t, u, v, w, x, y, z, aa]:
340 reveal_type(var) # N: Revealed type is "builtins.int"
341
342 for var2 in [g, h, i, j, k, l]:
343 reveal_type(var2) # N: Revealed type is "builtins.int | builtins.str"
344
345 for var3 in [m, n, o, p, q, r]:
346 reveal_type(var3) # N: Revealed type is "builtins.int | Any"
347
348 T = TypeVar("T", bound=Type[Foo])
349
350 def check(x: T) -> T:
351 a, b, c = x
352 for var in [a, b, c]:
353 reveal_type(var) # N: Revealed type is "builtins.int"
354 return x
355
356 T2 = TypeVar("T2", bound=Type[Union[Foo, Bar]])
357
358 def check2(x: T2) -> T2:
359 a, b, c = x
360 for var in [a, b, c]:
361 reveal_type(var) # N: Revealed type is "builtins.int | builtins.str"
362 return x
363
364 T3 = TypeVar("T3", bound=Union[Type[Foo], Type[Bar]])
365
366 def check3(x: T3) -> T3:
367 a, b, c = x
368 for var in [a, b, c]:
369 reveal_type(var) # N: Revealed type is "builtins.int | builtins.str"
370 return x
371 [out]
372
373 [case testInferringLvarTypesUnpackedFromIterableClassObjectWithGenericIter]
374 from typing import Iterator, Type, TypeVar
375
376 T = TypeVar("T")
377 class Meta(type):
378 def __iter__(self: Type[T]) -> Iterator[T]: ...
379 class Foo(metaclass=Meta): ...
380
381 A, B, C = Foo
382 reveal_type(A) # N: Revealed type is "__main__.Foo"
383 reveal_type(B) # N: Revealed type is "__main__.Foo"
384 reveal_type(C) # N: Revealed type is "__main__.Foo"
385 [out]
386
387 [case testInferringLvarTypesInMultiDefWithInvalidTuple]
388 from typing import Tuple
389 t: Tuple[object, object, object]
390
391 def f() -> None:
392 a, b = t # Fail
393 c, d, e, f = t # Fail
394 g, h, i = t
395 [builtins fixtures/tuple.pyi]
396 [out]
397 main:5: error: Too many values to unpack (2 expected, 3 provided)
398 main:6: error: Need more than 3 values to unpack (4 expected)
399
400 [case testInvalidRvalueTypeInInferredMultipleLvarDefinition]
401 import typing
402 def f() -> None:
403 a, b = f # E: "Callable[[], None]" object is not iterable
404 c, d = A() # E: "A" object is not iterable
405 class A: pass
406 [builtins fixtures/for.pyi]
407 [out]
408
409 [case testInvalidRvalueTypeInInferredNestedTupleAssignment]
410 import typing
411 def f() -> None:
412 a1, (a2, b) = A(), f # E: "Callable[[], None]" object is not iterable
413 a3, (c, d) = A(), A() # E: "A" object is not iterable
414 class A: pass
415 [builtins fixtures/for.pyi]
416 [out]
417
418 [case testInferringMultipleLvarDefinitionWithListRvalue]
419 from typing import List
420
421 class C: pass
422 class D: pass
423
424 def f() -> None:
425 list_c = [C()]
426 list_d = [D()]
427 a, b = list_c
428 c, d, e = list_d
429 if int():
430 a = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
431 b = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
432 c = C() # E: Incompatible types in assignment (expression has type "C", variable has type "D")
433 b = c # E: Incompatible types in assignment (expression has type "D", variable has type "C")
434
435 a = C()
436 b = C()
437 c = D()
438 d = D()
439 e = D()
440
441 a = b
442 c = d
443 d = e
444 [builtins fixtures/for.pyi]
445 [out]
446
447 [case testInferringNestedTupleAssignmentWithListRvalue]
448 from typing import List
449
450 class C: pass
451 class D: pass
452
453 def f() -> None:
454 list_c = [C()]
455 list_d = [D()]
456 c1, (a, b) = C(), list_c
457 c2, (c, d, e) = C(), list_d
458 if int():
459 a = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
460 b = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
461 c = C() # E: Incompatible types in assignment (expression has type "C", variable has type "D")
462 b = c # E: Incompatible types in assignment (expression has type "D", variable has type "C")
463
464 a = C()
465 b = C()
466 c = D()
467 d = D()
468 e = D()
469
470 a = b
471 c = d
472 d = e
473 [builtins fixtures/for.pyi]
474 [out]
475
476 [case testInferringMultipleLvarDefinitionWithImplicitDynamicRvalue]
477 import typing
478 def f() -> None:
479 a, b = g()
480 a.x
481 b.x
482 def g(): pass
483
484 [case testInferringMultipleLvarDefinitionWithExplicitDynamicRvalue]
485 from typing import Any
486 def f(d: Any) -> None:
487 a, b = d
488 a.x
489 b.x
490
491 [case testInferringTypesFromIterable]
492 from typing import Iterable
493 class Nums(Iterable[int]):
494 def __iter__(self): pass
495 def __next__(self): pass
496 a, b = Nums()
497 reveal_type(a) # N: Revealed type is "builtins.int"
498 reveal_type(b) # N: Revealed type is "builtins.int"
499 if int():
500 a = b = 1
501 if int():
502 a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
503 if int():
504 b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
505 [builtins fixtures/for.pyi]
506
507 [case testInferringTypesFromIterableStructuralSubtyping1]
508 from typing import Iterator
509 class Nums:
510 def __iter__(self) -> Iterator[int]: pass
511 a, b = Nums()
512 reveal_type(a) # N: Revealed type is "builtins.int"
513 reveal_type(b) # N: Revealed type is "builtins.int"
514 if int():
515 a = b = 1
516 if int():
517 a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
518 if int():
519 b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
520 [builtins fixtures/for.pyi]
521
522 [case testInferringTypesFromIterableStructuralSubtyping2]
523 from typing import Self
524 class Nums:
525 def __iter__(self) -> Self: pass
526 def __next__(self) -> int: pass
527 a, b = Nums()
528 reveal_type(a) # N: Revealed type is "builtins.int"
529 reveal_type(b) # N: Revealed type is "builtins.int"
530 if int():
531 a = b = 1
532 if int():
533 a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
534 if int():
535 b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
536 [builtins fixtures/tuple.pyi]
537
538
539 -- Type variable inference for generic functions
540 -- ---------------------------------------------
541
542
543 [case testInferSimpleGenericFunction]
544 from typing import Tuple, TypeVar
545 T = TypeVar('T')
546 a: A
547 b: B
548 c: Tuple[A, object]
549
550 def id(a: T) -> T: pass
551
552 if int():
553 b = id(a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
554 a = id(b) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
555 if int():
556 a = id(c) # E: Incompatible types in assignment (expression has type "tuple[A, object]", variable has type "A")
557
558 if int():
559 a = id(a)
560 b = id(b)
561 c = id(c)
562
563 class A: pass
564 class B: pass
565 [builtins fixtures/tuple.pyi]
566
567 [case testInferringGenericFunctionTypeForLvar]
568 from typing import TypeVar
569 T = TypeVar('T')
570 def f() -> None:
571 a = id
572 b: int
573 c: str
574 if int():
575 b = a(c) # E: Incompatible types in assignment (expression has type "str", variable has type "int")
576 b = a(b)
577 c = a(c)
578 def id(x: T) -> T:
579 return x
580 [out]
581
582 [case testUnderspecifiedInferenceResult]
583 # flags: --no-strict-optional
584 from typing import TypeVar
585 T = TypeVar('T')
586 class A: pass
587 a: A
588
589 def ff() -> None:
590 x = f() # E: Need type annotation for "x"
591 reveal_type(x) # N: Revealed type is "Any"
592
593 def f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
594 def g(a: T) -> None: pass
595
596 g(None) # Ok
597 f() # Ok because not used to infer local variable type
598 g(a)
599 [out]
600
601 [case testInferenceWithMultipleConstraints]
602 from typing import TypeVar
603
604 class A: pass
605 class B(A): pass
606
607 T = TypeVar('T')
608 a: A
609 b: B
610
611 def f(a: T, b: T) -> T: pass
612
613 if int():
614 b = f(a, b) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
615 if int():
616 b = f(b, a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
617 if int():
618 a = f(a, b)
619 if int():
620 a = f(b, a)
621
622 [case testInferenceWithMultipleVariables]
623 from typing import Tuple, TypeVar
624 T = TypeVar('T')
625 S = TypeVar('S')
626
627 def f(a: T, b: S) -> Tuple[T, S]: pass
628
629 class A: pass
630 class B: pass
631
632 a: A
633 b: B
634 taa: Tuple[A, A]
635 tab: Tuple[A, B]
636 tba: Tuple[B, A]
637
638 if int():
639 taa = f(a, b) # E: Argument 2 to "f" has incompatible type "B"; expected "A"
640 if int():
641 taa = f(b, a) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
642 if int():
643 tba = f(a, b) # E: Argument 1 to "f" has incompatible type "A"; expected "B" \
644 # E: Argument 2 to "f" has incompatible type "B"; expected "A"
645
646 if int():
647 tab = f(a, b)
648 if int():
649 tba = f(b, a)
650 [builtins fixtures/tuple.pyi]
651
652 [case testConstraintSolvingWithSimpleGenerics]
653 from typing import TypeVar, Generic
654 T = TypeVar('T')
655 ao: A[object]
656 ab: A[B]
657 ac: A[C]
658
659 def f(a: 'A[T]') -> 'A[T]': pass
660
661 def g(a: T) -> T: pass
662
663 class A(Generic[T]): pass
664 class B: pass
665 class C: pass
666
667 if int():
668 ab = f(ao) # E: Argument 1 to "f" has incompatible type "A[object]"; expected "A[B]"
669 ao = f(ab) # E: Argument 1 to "f" has incompatible type "A[B]"; expected "A[object]"
670 if int():
671 ab = f(ac) # E: Argument 1 to "f" has incompatible type "A[C]"; expected "A[B]"
672 if int():
673 ab = g(ao) # E: Argument 1 to "g" has incompatible type "A[object]"; expected "A[B]"
674 ao = g(ab) # E: Argument 1 to "g" has incompatible type "A[B]"; expected "A[object]"
675
676 if int():
677 ab = f(ab)
678 ac = f(ac)
679 ao = f(ao)
680
681 if int():
682 ab = g(ab)
683 ao = g(ao)
684 [case testConstraintSolvingFailureWithSimpleGenerics]
685 from typing import TypeVar, Generic
686 T = TypeVar('T')
687 ao: A[object]
688 ab: A[B]
689
690 def f(a: 'A[T]', b: 'A[T]') -> None: pass
691
692 class A(Generic[T]): pass
693 class B: pass
694
695
696 f(ao, ab) # E: Cannot infer value of type parameter "T" of "f"
697 f(ab, ao) # E: Cannot infer value of type parameter "T" of "f"
698 f(ao, ao)
699 f(ab, ab)
700
701 [case testTypeInferenceWithCalleeDefaultArgs]
702 # flags: --no-strict-optional
703 from typing import TypeVar
704 T = TypeVar('T')
705 a = None # type: A
706 o = None # type: object
707
708 def f(a: T = None) -> T: pass
709 def g(a: T, b: T = None) -> T: pass
710
711 class A: pass
712
713 if int():
714 a = f(o) # E: Incompatible types in assignment (expression has type "object", variable has type "A")
715 if int():
716 a = g(a, o) # E: Incompatible types in assignment (expression has type "object", variable has type "A")
717
718 if int():
719 o = f()
720 if int():
721 o = f(o)
722 if int():
723 a = f(a)
724 if int():
725 a = g(a)
726
727
728 -- Generic function inference with multiple inheritance
729 -- ----------------------------------------------------
730
731
732 [case testGenericFunctionInferenceWithMultipleInheritance]
733 from typing import TypeVar
734
735 class I: pass
736 class J: pass
737
738 class A(I, J): pass
739 class B(I, J): pass
740 class C(I): pass
741 class D(J): pass
742
743 T = TypeVar('T')
744 def f(a: T, b: T) -> T: pass
745 def g(x: I) -> None: pass
746
747 a = f(A(), C())
748 g(a)
749 b = f(A(), B())
750 g(b)
751 c = f(A(), D())
752 g(c) # E: Argument 1 to "g" has incompatible type "J"; expected "I"
753 d = f(D(), A())
754 g(d) # E: Argument 1 to "g" has incompatible type "J"; expected "I"
755 e = f(D(), C())
756 g(e) # E: Argument 1 to "g" has incompatible type "object"; expected "I"
757
758 [case testGenericFunctionInferenceWithMultipleInheritance2]
759 from typing import TypeVar
760
761 class I: pass
762 class J: pass
763
764 class A(I): pass
765 class B(A, J): pass
766 class C(I, J): pass
767
768 T = TypeVar('T')
769 def f(a: T, b: T) -> T: pass
770 def g(x: I) -> None: pass
771 def h(x: J) -> None: pass
772
773 a = f(B(), C())
774 g(a)
775 h(a) # E: Argument 1 to "h" has incompatible type "I"; expected "J"
776 b = f(C(), B())
777 g(b)
778 h(b) # E: Argument 1 to "h" has incompatible type "I"; expected "J"
779 c = f(A(), B())
780 g(a)
781 h(b) # E: Argument 1 to "h" has incompatible type "I"; expected "J"
782
783 [case testGenericFunctionInferenceWithMultipleInheritance3]
784 from typing import TypeVar
785
786 class I: pass
787 class J: pass
788 class K(J): pass
789
790 class A(K): pass
791 class B(A, I): pass
792 class C(I, J): pass
793
794 T = TypeVar('T')
795 def f(a: T, b: T) -> T: pass
796 def g(x: K) -> None: pass
797
798 a = f(B(), C())
799 g(a) # E: Argument 1 to "g" has incompatible type "J"; expected "K"
800 b = f(A(), C())
801 g(b) # E: Argument 1 to "g" has incompatible type "J"; expected "K"
802 c = f(A(), B())
803 g(c)
804
805 [case testPrecedenceOfFirstBaseAsInferenceResult]
806 from typing import TypeVar
807 from abc import abstractmethod, ABCMeta
808 class A: pass
809 class B(A, I, J): pass
810 class C(A, I, J): pass
811
812 def f(a: T, b: T) -> T: pass
813
814 T = TypeVar('T')
815 a: A
816 i: I
817 j: J
818
819 a = f(B(), C())
820
821 class I(metaclass=ABCMeta): pass
822 class J(metaclass=ABCMeta): pass
823
824
825 [builtins fixtures/tuple.pyi]
826
827
828 -- Generic function inference with function arguments
829 -- --------------------------------------------------
830
831
832 [case testNonOverloadedMapInference]
833 from typing import TypeVar, Callable, List
834 t = TypeVar('t')
835 s = TypeVar('s')
836 class A: pass
837 b = bool()
838 def f(x: bool) -> A: pass
839 def mymap(f: Callable[[t], s], a: List[t]) -> List[s]: pass
840
841 l = mymap(f, [b])
842 if int():
843 l = [A()]
844 lb = [b]
845 if int():
846 l = lb # E: Incompatible types in assignment (expression has type "list[bool]", variable has type "list[A]")
847 [builtins fixtures/for.pyi]
848
849 [case testGenericFunctionWithTypeTypeAsCallable]
850 from typing import Callable, Type, TypeVar
851 T = TypeVar('T')
852 def f(x: Callable[..., T]) -> T: return x()
853 class A: pass
854 x: Type[A]
855 y = f(x)
856 reveal_type(y) # N: Revealed type is "__main__.A"
857
858 -- Generic function inference with unions
859 -- --------------------------------------
860
861
862 [case testUnionInference]
863 from typing import TypeVar, Union, List
864 T = TypeVar('T')
865 U = TypeVar('U')
866 def f(x: Union[T, int], y: T) -> T: pass
867 f(1, 'a')() # E: "str" not callable
868 f('a', 1)() # E: "object" not callable
869 f('a', 'a')() # E: "str" not callable
870 f(1, 1)() # E: "int" not callable
871
872 def g(x: Union[T, List[T]]) -> List[T]: pass
873 def h(x: List[str]) -> None: pass
874 g('a')() # E: "list[str]" not callable
875
876 # The next line is a case where there are multiple ways to satisfy a constraint
877 # involving a Union. Either T = list[str] or T = str would turn out to be valid,
878 # but mypy doesn't know how to branch on these two options (and potentially have
879 # to backtrack later) and defaults to T = Never. The result is an
880 # awkward error message. Either a better error message, or simply accepting the
881 # call, would be preferable here.
882 g(['a']) # E: Argument 1 to "g" has incompatible type "list[str]"; expected "list[Never]"
883
884 h(g(['a']))
885
886 def i(x: Union[List[T], List[U]], y: List[T], z: List[U]) -> None: pass
887 a = [1]
888 b = ['b']
889 i(a, a, b)
890 i(b, a, b)
891 i(a, b, b) # E: Argument 1 to "i" has incompatible type "list[int]"; expected "list[str]"
892 [builtins fixtures/list.pyi]
893
894 [case testCallableListJoinInference]
895 from typing import Any, Callable
896
897 def fun() -> None:
898 callbacks = [
899 callback1,
900 callback2,
901 ]
902
903 for c in callbacks:
904 call(c, 1234) # this must not fail
905
906 def callback1(i: int) -> int:
907 return i
908 def callback2(i: int) -> str:
909 return 'hello'
910 def call(c: Callable[[int], Any], i: int) -> None:
911 c(i)
912 [builtins fixtures/list.pyi]
913 [out]
914
915 [case testCallableMeetAndJoin]
916 from typing import Callable, Any, TypeVar
917
918 class A: ...
919 class B(A): ...
920
921 def f(c: Callable[[B], int]) -> None: ...
922
923 c: Callable[[A], int]
924 d: Callable[[B], int]
925
926 lst = [c, d]
927 reveal_type(lst) # N: Revealed type is "builtins.list[def (__main__.B) -> builtins.int]"
928
929 T = TypeVar('T')
930 def meet_test(x: Callable[[T], int], y: Callable[[T], int]) -> T: ...
931
932 CA = Callable[[A], A]
933 CB = Callable[[B], B]
934
935 ca: Callable[[CA], int]
936 cb: Callable[[CB], int]
937 reveal_type(meet_test(ca, cb)) # N: Revealed type is "def (__main__.A) -> __main__.B"
938 [builtins fixtures/list.pyi]
939 [out]
940
941 [case testUnionInferenceWithTypeVarValues]
942 from typing import TypeVar, Union
943 AnyStr = TypeVar('AnyStr', bytes, str)
944 def f(x: Union[AnyStr, int], *a: AnyStr) -> None: pass
945 f('foo')
946 f('foo', 'bar')
947 f('foo', b'bar') # E: Value of type variable "AnyStr" of "f" cannot be "Sequence[object]"
948 f(1)
949 f(1, 'foo')
950 f(1, 'foo', b'bar') # E: Value of type variable "AnyStr" of "f" cannot be "Sequence[object]"
951 [builtins fixtures/primitives.pyi]
952
953
954 [case testUnionTwoPassInference-skip]
955 from typing import TypeVar, Union, List
956 T = TypeVar('T')
957 U = TypeVar('U')
958 def j(x: Union[List[T], List[U]], y: List[T]) -> List[U]: pass
959
960 a = [1]
961 b = ['b']
962 # We could infer: Since List[str] <: List[T], we must have T = str.
963 # Then since List[int] <: Union[List[str], List[U]], and List[int] is
964 # not a subtype of List[str], we must have U = int.
965 # This is not currently implemented.
966 j(a, b)
967 [builtins fixtures/list.pyi]
968
969
970 [case testUnionContext]
971 from typing import TypeVar, Union, List
972 T = TypeVar('T')
973 def f() -> List[T]: pass
974 d1 = f() # type: Union[List[int], str]
975 d2 = f() # type: Union[int, str] # E: Incompatible types in assignment (expression has type "list[Never]", variable has type "int | str")
976 def g(x: T) -> List[T]: pass
977 d3 = g(1) # type: Union[List[int], List[str]]
978 [builtins fixtures/list.pyi]
979
980
981 [case testGenericFunctionSubtypingWithUnions]
982 from typing import TypeVar, Union, List
983 T = TypeVar('T')
984 S = TypeVar('S')
985 def k1(x: int, y: List[T]) -> List[Union[T, int]]: pass
986 def k2(x: S, y: List[T]) -> List[Union[T, int]]: pass
987 a = k2
988 if int():
989 a = k2
990 if int():
991 a = k1 # E: Incompatible types in assignment (expression has type "Callable[[int, list[T@k1]], list[T@k1 | int]]", variable has type "Callable[[S, list[T@k2]], list[T@k2 | int]]")
992 b = k1
993 if int():
994 b = k1
995 if int():
996 b = k2
997 [builtins fixtures/list.pyi]
998
999 [case testAmbiguousUnionContextAndMultipleInheritance]
1000 from typing import TypeVar, Union, Generic
1001
1002 _T = TypeVar('_T')
1003
1004 class T(Generic[_T]): pass
1005 class U(Generic[_T]): pass
1006 class V(T[_T], U[_T]): pass
1007
1008 def wait_for(fut: Union[T[_T], U[_T]]) -> _T: ...
1009
1010 reveal_type(wait_for(V[str]())) # N: Revealed type is "builtins.str"
1011
1012 [case testAmbiguousUnionContextAndMultipleInheritance2]
1013 from typing import TypeVar, Union, Generic
1014
1015 _T = TypeVar('_T')
1016 _S = TypeVar('_S')
1017
1018 class T(Generic[_T, _S]): pass
1019 class U(Generic[_T, _S]): pass
1020 class V(T[_T, _S], U[_T, _S]): pass
1021
1022 def wait_for(fut: Union[T[_T, _S], U[_T, _S]]) -> T[_T, _S]: ...
1023
1024 reveal_type(wait_for(V[int, str]())) \
1025 # N: Revealed type is "__main__.T[builtins.int, builtins.str]"
1026
1027
1028 -- Literal expressions
1029 -- -------------------
1030
1031
1032 [case testDictLiteral]
1033 from typing import Dict
1034 class A: pass
1035 class B: pass
1036 def d_ab() -> Dict[A, B]: return {}
1037 def d_aa() -> Dict[A, A]: return {}
1038 a: A
1039 b: B
1040 d = {a:b}
1041 if int():
1042 d = d_ab()
1043 if int():
1044 d = d_aa() # E: Incompatible types in assignment (expression has type "dict[A, A]", variable has type "dict[A, B]")
1045 [builtins fixtures/dict.pyi]
1046
1047 [case testSetLiteral]
1048 from typing import Any, Set
1049 a: int
1050 x: Any
1051 def s_i() -> Set[int]: return set()
1052 def s_s() -> Set[str]: return set()
1053 s = {a}
1054 if int():
1055 s = {x}
1056 if int():
1057 s = s_i()
1058 if int():
1059 s = s_s() # E: Incompatible types in assignment (expression has type "set[str]", variable has type "set[int]")
1060 [builtins fixtures/set.pyi]
1061
1062 [case testSetWithStarExpr]
1063 s = {1, 2, *(3, 4)}
1064 t = {1, 2, *s}
1065 reveal_type(s) # N: Revealed type is "builtins.set[builtins.int]"
1066 reveal_type(t) # N: Revealed type is "builtins.set[builtins.int]"
1067 [builtins fixtures/set.pyi]
1068
1069 [case testListLiteralWithFunctionsErasesNames]
1070 def f1(x: int) -> int: ...
1071 def g1(y: int) -> int: ...
1072 def h1(x: int) -> int: ...
1073
1074 list_1 = [f1, g1]
1075 list_2 = [f1, h1]
1076 reveal_type(list_1) # N: Revealed type is "builtins.list[def (builtins.int) -> builtins.int]"
1077 reveal_type(list_2) # N: Revealed type is "builtins.list[def (x: builtins.int) -> builtins.int]"
1078
1079 def f2(x: int, z: str) -> int: ...
1080 def g2(y: int, z: str) -> int: ...
1081 def h2(x: int, z: str) -> int: ...
1082
1083 list_3 = [f2, g2]
1084 list_4 = [f2, h2]
1085 reveal_type(list_3) # N: Revealed type is "builtins.list[def (builtins.int, z: builtins.str) -> builtins.int]"
1086 reveal_type(list_4) # N: Revealed type is "builtins.list[def (x: builtins.int, z: builtins.str) -> builtins.int]"
1087 [builtins fixtures/list.pyi]
1088
1089 [case testListLiteralWithSimilarFunctionsErasesName]
1090 from typing import Union
1091
1092 class A: ...
1093 class B(A): ...
1094 class C: ...
1095 class D: ...
1096
1097 def f(x: Union[A, C], y: B) -> A: ...
1098 def g(z: Union[B, D], y: A) -> B: ...
1099 def h(x: Union[B, D], y: A) -> B: ...
1100
1101 list_1 = [f, g]
1102 list_2 = [f, h]
1103 reveal_type(list_1) # N: Revealed type is "builtins.list[def (__main__.B, y: __main__.B) -> __main__.A]"
1104 reveal_type(list_2) # N: Revealed type is "builtins.list[def (x: __main__.B, y: __main__.B) -> __main__.A]"
1105 [builtins fixtures/list.pyi]
1106
1107 [case testListLiteralWithNameOnlyArgsDoesNotEraseNames]
1108 def f(*, x: int) -> int: ...
1109 def g(*, y: int) -> int: ...
1110 def h(*, x: int) -> int: ...
1111
1112 list_1 = [f, g] # E: List item 0 has incompatible type "def f(*, x: int) -> int"; expected "def g(*, y: int) -> int"
1113 list_2 = [f, h]
1114 [builtins fixtures/list.pyi]
1115
1116
1117 -- For statements
1118 -- --------------
1119
1120
1121 [case testInferenceOfFor1]
1122 a: A
1123 b: B
1124
1125 class A: pass
1126 class B: pass
1127
1128 for x in [A()]:
1129 b = x # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1130 a = x
1131
1132 for y in []: # E: Need type annotation for "y"
1133 a = y
1134 reveal_type(y) # N: Revealed type is "Any"
1135 [builtins fixtures/for.pyi]
1136
1137 [case testInferenceOfFor2]
1138 class A: pass
1139 class B: pass
1140 class C: pass
1141
1142 a: A
1143 b: B
1144 c: C
1145 for x, (y, z) in [(A(), (B(), C()))]:
1146 b = x # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1147 c = y # E: Incompatible types in assignment (expression has type "B", variable has type "C")
1148 a = z # E: Incompatible types in assignment (expression has type "C", variable has type "A")
1149 a = x
1150 b = y
1151 c = z
1152 for xx, yy, zz in [(A(), B())]: # E: Need more than 2 values to unpack (3 expected)
1153 pass
1154 for xx, (yy, zz) in [(A(), B())]: # E: "B" object is not iterable
1155 pass
1156 for xxx, yyy in [(1, 2)]:
1157 pass
1158 [builtins fixtures/for.pyi]
1159
1160 [case testInferenceOfFor3]
1161 class A: pass
1162 class B: pass
1163
1164 a: A
1165 b: B
1166
1167 for x, y in [[A()]]:
1168 b = x # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1169 b = y # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1170 a = x
1171 a = y
1172
1173 for e, f in [[]]: # E: Need type annotation for "e" \
1174 # E: Need type annotation for "f"
1175 reveal_type(e) # N: Revealed type is "Any"
1176 reveal_type(f) # N: Revealed type is "Any"
1177
1178 [builtins fixtures/for.pyi]
1179
1180 [case testForStatementInferenceWithVoid]
1181 def f() -> None: pass
1182
1183 for x in f(): # E: "f" does not return a value (it only ever returns None) \
1184 # E: "None" has no attribute "__iter__" (not iterable)
1185 pass
1186 [builtins fixtures/for.pyi]
1187
1188 [case testReusingInferredForIndex]
1189 import typing
1190
1191 class A: pass
1192 class B: pass
1193
1194 for a in [A()]: pass
1195 a = A()
1196 if int():
1197 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1198 for a in []: pass
1199 a = A()
1200 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1201 [builtins fixtures/for.pyi]
1202
1203 [case testReusingInferredForIndex2]
1204 # flags: --allow-redefinition-old
1205
1206 def f() -> None:
1207 for a in [A()]: pass
1208 a = A()
1209 a
1210 if int():
1211 a = B() \
1212 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1213 for a in []: pass # E: Need type annotation for "a"
1214 a = A()
1215 if int():
1216 a = B() \
1217 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1218 class A: pass
1219 class B: pass
1220 [builtins fixtures/for.pyi]
1221 [out]
1222
1223 [case testReusingInferredForIndex3]
1224 # flags: --disallow-redefinition-old
1225 def f() -> None:
1226 for a in [A()]: pass
1227 a = A()
1228 a
1229 if int():
1230 a = B() \
1231 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1232 for a in []: pass
1233 a = A()
1234 if int():
1235 a = B() \
1236 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1237 class A: pass
1238 class B: pass
1239 [builtins fixtures/for.pyi]
1240 [out]
1241
1242 [case testForStatementIndexNarrowing]
1243 from typing import TypedDict
1244
1245 class X(TypedDict):
1246 hourly: int
1247 daily: int
1248
1249 x: X
1250 for a in ("hourly", "daily"):
1251 reveal_type(a) # N: Revealed type is "Literal['hourly']? | Literal['daily']?"
1252 reveal_type(x[a]) # N: Revealed type is "builtins.int"
1253 reveal_type(a.upper()) # N: Revealed type is "builtins.str"
1254 c = a
1255 reveal_type(c) # N: Revealed type is "builtins.str"
1256 a = "monthly"
1257 reveal_type(a) # N: Revealed type is "builtins.str"
1258 a = "yearly"
1259 reveal_type(a) # N: Revealed type is "builtins.str"
1260 a = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1261 reveal_type(a) # N: Revealed type is "builtins.str"
1262 d = a
1263 reveal_type(d) # N: Revealed type is "builtins.str"
1264
1265 b: str
1266 for b in ("hourly", "daily"):
1267 reveal_type(b) # N: Revealed type is "builtins.str"
1268 reveal_type(b.upper()) # N: Revealed type is "builtins.str"
1269 [builtins fixtures/for.pyi]
1270 [typing fixtures/typing-full.pyi]
1271
1272
1273 -- Regression tests
1274 -- ----------------
1275
1276
1277 [case testMultipleAssignmentWithPartialDefinition]
1278 a: A
1279 if int():
1280 x, a = a, a
1281 if int():
1282 x = a
1283 a = x
1284 if int():
1285 x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1286 a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1287 class A: pass
1288
1289 [case testMultipleAssignmentWithPartialDefinition2]
1290 a: A
1291 if int():
1292 a, x = [a, a]
1293 if int():
1294 x = a
1295 a = x
1296 if int():
1297 x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1298 a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1299 class A: pass
1300 [builtins fixtures/for.pyi]
1301
1302 [case testMultipleAssignmentWithPartialDefinition3]
1303 from typing import Any, cast
1304 a: A
1305 if int():
1306 x, a = cast(Any, a)
1307 if int():
1308 x = a
1309 a = x
1310 if int():
1311 x = object()
1312 a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
1313 class A: pass
1314
1315 [case testInferGlobalDefinedInBlock]
1316 class A: pass
1317 class B: pass
1318
1319 if int():
1320 a = A()
1321 if int():
1322 a = A()
1323 if int():
1324 a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1325
1326 [case testAssigningAnyStrToNone]
1327 from typing import Tuple, TypeVar
1328 AnyStr = TypeVar('AnyStr', str, bytes)
1329
1330 def f(x: AnyStr) -> Tuple[AnyStr]: pass
1331 x = None
1332 (x,) = f('')
1333 reveal_type(x) # N: Revealed type is "builtins.str"
1334 [builtins fixtures/tuple.pyi]
1335
1336
1337 -- Inferring attribute types
1338 -- -------------------------
1339
1340
1341 [case testInferAttributeType]
1342 import typing
1343 class A:
1344 a = B()
1345 class B: pass
1346
1347 A().a = B()
1348 A().a = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1349
1350 [case testInferAttributeTypeAndAssignInInit]
1351 import typing
1352 class A:
1353 a = B()
1354 def __init__(self) -> None:
1355 self.a = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1356 self.a = B()
1357 class B: pass
1358 [out]
1359
1360 [case testInferAttributeInInit]
1361 import typing
1362 class B: pass
1363 class A:
1364 def __init__(self) -> None:
1365 self.a = A()
1366 self.b = B()
1367 a = A()
1368 a.a = A()
1369 a.b = B()
1370 a.a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1371 a.b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1372
1373 [case testInferAttributeInInitUsingChainedAssignment]
1374 import typing
1375 class B: pass
1376 class A:
1377 def __init__(self) -> None:
1378 self.a = self.b = A()
1379 a = A()
1380 a.a = A()
1381 a.b = A()
1382 a.a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1383 a.b = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1384
1385
1386 -- Lambdas
1387 -- -------
1388
1389
1390 [case testInferLambdaType]
1391 from typing import List, Callable
1392 li = [1]
1393 l = lambda: li
1394 f1 = l # type: Callable[[], List[int]]
1395 f2 = l # type: Callable[[], List[str]] # E: Incompatible types in assignment (expression has type "Callable[[], list[int]]", variable has type "Callable[[], list[str]]")
1396 [builtins fixtures/list.pyi]
1397
1398 [case testInferLambdaType2]
1399 from typing import List, Callable
1400 l = lambda: [B()]
1401 f1 = l # type: Callable[[], List[B]]
1402 f2 = l # type: Callable[[], List[A]] # E: Incompatible types in assignment (expression has type "Callable[[], list[B]]", variable has type "Callable[[], list[A]]")
1403
1404 class A: pass
1405 class B: pass
1406 [builtins fixtures/list.pyi]
1407
1408 [case testUninferableLambda]
1409 from typing import TypeVar, Callable
1410 X = TypeVar('X')
1411 def f(x: Callable[[X], X]) -> X: pass
1412 y = f(lambda x: x) # E: Need type annotation for "y"
1413
1414 [case testUninferableLambdaWithTypeError]
1415 from typing import TypeVar, Callable
1416 X = TypeVar('X')
1417 def f(x: Callable[[X], X], y: str) -> X: pass
1418 y = f(lambda x: x, 1) # E: Need type annotation for "y" \
1419 # E: Argument 2 to "f" has incompatible type "int"; expected "str"
1420
1421 [case testInferLambdaNone]
1422 # flags: --no-strict-optional
1423 from typing import Callable
1424 def f(x: Callable[[], None]) -> None: pass
1425 def g(x: Callable[[], int]) -> None: pass
1426 a = lambda: None
1427 f(a)
1428 g(a)
1429 b = lambda: None # type: Callable[[], None]
1430 f(b)
1431 g(b)
1432
1433 [case testLambdaDefaultContext]
1434 from typing import Callable
1435 def f(a: Callable[..., None] = lambda *a, **k: None):
1436 pass
1437
1438 def g(a: Callable[..., None] = lambda *a, **k: 1): # E: Incompatible default for parameter "a" (default has type "def (*a: Any, **k: Any) -> int", parameter has type "Callable[..., None]")
1439 pass
1440 [builtins fixtures/dict.pyi]
1441
1442 [case testLambdaVarargContext]
1443 # Should not crash
1444 from typing import Callable
1445 def f(a: Callable[[int, int, int], int] = lambda *a, **k: 1):
1446 pass
1447 [builtins fixtures/dict.pyi]
1448
1449 [case testLambdaDeferredSpecialCase]
1450 from typing import Callable
1451
1452 class A:
1453 def f(self) -> None:
1454 h(lambda: self.x)
1455
1456 def g(self) -> None:
1457 self.x = 1
1458
1459 def h(x: Callable[[], int]) -> None:
1460 pass
1461
1462 [case testLambdaJoinWithDynamicConstructor]
1463 from typing import Any, Union
1464
1465 class Wrapper:
1466 def __init__(self, x: Any) -> None: ...
1467
1468 def f(cond: bool) -> Any:
1469 f = Wrapper if cond else lambda x: x
1470 reveal_type(f) # N: Revealed type is "(def (x: Any) -> __main__.Wrapper) | (def (x: Any) -> Any)"
1471 return f(3)
1472
1473 def g(cond: bool) -> Any:
1474 f = lambda x: x if cond else Wrapper
1475 reveal_type(f) # N: Revealed type is "def (x: Any) -> Any | (def (x: Any) -> __main__.Wrapper)"
1476 return f(3)
1477
1478 def h(cond: bool) -> Any:
1479 f = (lambda x: x) if cond else Wrapper
1480 reveal_type(f) # N: Revealed type is "(def (x: Any) -> Any) | (def (x: Any) -> __main__.Wrapper)"
1481 return f(3)
1482
1483 -- Boolean operators
1484 -- -----------------
1485
1486 [case testOrOperationWithGenericOperands]
1487 from typing import List
1488 a: List[A]
1489 o: List[object]
1490 a2 = a or []
1491 if int():
1492 a = a2
1493 a2 = o # E: Incompatible types in assignment (expression has type "list[object]", variable has type "list[A]")
1494 class A: pass
1495 [builtins fixtures/list.pyi]
1496
1497
1498 -- Accessing variable before its type has been inferred
1499 -- ----------------------------------------------------
1500
1501
1502 [case testAccessGlobalVarBeforeItsTypeIsAvailable]
1503 import typing
1504 x.y # E: Cannot determine type of "x" # E: Name "x" is used before definition
1505 x = object()
1506 x.y # E: "object" has no attribute "y"
1507
1508 [case testAccessDataAttributeBeforeItsTypeIsAvailable]
1509
1510 a: A
1511 a.x.y # E: Cannot determine type of "x"
1512 class A:
1513 def __init__(self) -> None:
1514 self.x = object()
1515 a.x.y # E: "object" has no attribute "y"
1516
1517
1518 -- Ducktype declarations
1519 -- ---------------------
1520
1521
1522 [case testListWithDucktypeCompatibility]
1523 from typing import List, _promote
1524 class A: pass
1525 @_promote(A)
1526 class B: pass
1527 a: List[A]
1528 x1 = [A(), B()]
1529 x2 = [B(), A()]
1530 x3 = [B(), B()]
1531 if int():
1532 a = x1
1533 if int():
1534 a = x2
1535 if int():
1536 a = x3 \
1537 # E: Incompatible types in assignment (expression has type "list[B]", variable has type "list[A]") \
1538 # N: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \
1539 # N: Consider using "Sequence" instead, which is covariant
1540 [builtins fixtures/list.pyi]
1541 [typing fixtures/typing-medium.pyi]
1542
1543 [case testListWithDucktypeCompatibilityAndTransitivity]
1544 from typing import List, _promote
1545 class A: pass
1546 @_promote(A)
1547 class B: pass
1548 @_promote(B)
1549 class C: pass
1550 a: List[A]
1551 x1 = [A(), C()]
1552 x2 = [C(), A()]
1553 x3 = [B(), C()]
1554 if int():
1555 a = x1
1556 if int():
1557 a = x2
1558 if int():
1559 a = x3 \
1560 # E: Incompatible types in assignment (expression has type "list[B]", variable has type "list[A]") \
1561 # N: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \
1562 # N: Consider using "Sequence" instead, which is covariant
1563 [builtins fixtures/list.pyi]
1564 [typing fixtures/typing-medium.pyi]
1565
1566
1567 -- Inferring type of variable when initialized to an empty collection
1568 -- ------------------------------------------------------------------
1569
1570
1571 [case testInferListInitializedToEmpty]
1572 a = []
1573 a.append(1)
1574 a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
1575 [builtins fixtures/list.pyi]
1576
1577 [case testInferListInitializedToEmptyUsingUpdate]
1578 a = []
1579 a.extend([''])
1580 a.append(0) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
1581 [builtins fixtures/list.pyi]
1582
1583 [case testInferListInitializedToEmptyAndNotAnnotated]
1584 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1585 [builtins fixtures/list.pyi]
1586
1587 [case testInferListInitializedToEmptyAndReadBeforeAppend]
1588 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1589 if a: pass
1590 a.xyz # E: "list[Any]" has no attribute "xyz"
1591 a.append('')
1592 [builtins fixtures/list.pyi]
1593
1594 [case testInferListInitializedToEmptyAndIncompleteTypeInAppend]
1595 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1596 a.append([])
1597 a() # E: "list[Any]" not callable
1598 [builtins fixtures/list.pyi]
1599
1600 [case testInferListInitializedToEmptyAndMultipleAssignment]
1601 a, b = [], []
1602 a.append(1)
1603 b.append('')
1604 a() # E: "list[int]" not callable
1605 b() # E: "list[str]" not callable
1606 [builtins fixtures/list.pyi]
1607
1608 [case testInferListInitializedToEmptyInFunction]
1609 def f() -> None:
1610 a = []
1611 a.append(1)
1612 a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
1613 [builtins fixtures/list.pyi]
1614
1615 [case testInferListInitializedToEmptyAndNotAnnotatedInFunction]
1616 def f() -> None:
1617 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1618
1619 def g() -> None: pass
1620
1621 a = []
1622 a.append(1)
1623 [builtins fixtures/list.pyi]
1624
1625 [case testInferListInitializedToEmptyAndReadBeforeAppendInFunction]
1626 def f() -> None:
1627 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1628 if a: pass
1629 a.xyz # E: "list[Any]" has no attribute "xyz"
1630 a.append('')
1631 [builtins fixtures/list.pyi]
1632
1633 [case testInferListInitializedToEmptyInClassBody]
1634 class A:
1635 a = []
1636 a.append(1)
1637 a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
1638 [builtins fixtures/list.pyi]
1639
1640 [case testInferListInitializedToEmptyAndNotAnnotatedInClassBody]
1641 class A:
1642 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1643
1644 class B:
1645 a = []
1646 a.append(1)
1647 [builtins fixtures/list.pyi]
1648
1649 [case testInferListInitializedToEmptyInMethod]
1650 class A:
1651 def f(self) -> None:
1652 a = []
1653 a.append(1)
1654 a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
1655 [builtins fixtures/list.pyi]
1656
1657 [case testInferListInitializedToEmptyAndNotAnnotatedInMethod]
1658 class A:
1659 def f(self) -> None:
1660 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1661 [builtins fixtures/list.pyi]
1662
1663 [case testInferListInitializedToEmptyInMethodViaAttribute]
1664 class A:
1665 def f(self) -> None:
1666 # Attributes aren't supported right now.
1667 self.a = []
1668 self.a.append(1)
1669 self.a.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
1670 [builtins fixtures/list.pyi]
1671
1672 [case testInferListInitializedToEmptyInClassBodyAndOverridden]
1673 from typing import List
1674
1675 class A:
1676 def __init__(self) -> None:
1677 self.x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
1678
1679 class B(A):
1680 @property
1681 def x(self) -> List[int]: # E: Cannot override writeable attribute with read-only property
1682 return [123]
1683 [builtins fixtures/list.pyi]
1684
1685 [case testInferSetInitializedToEmpty]
1686 a = set()
1687 a.add(1)
1688 a.add('') # E: Argument 1 to "add" of "set" has incompatible type "str"; expected "int"
1689 [builtins fixtures/set.pyi]
1690
1691 [case testInferSetInitializedToEmptyUsingDiscard]
1692 a = set()
1693 a.discard('')
1694 a.add(0) # E: Argument 1 to "add" of "set" has incompatible type "int"; expected "str"
1695 [builtins fixtures/set.pyi]
1696
1697 [case testInferSetInitializedToEmptyUsingUpdate]
1698 a = set()
1699 a.update({0})
1700 a.add('') # E: Argument 1 to "add" of "set" has incompatible type "str"; expected "int"
1701 [builtins fixtures/set.pyi]
1702
1703 [case testInferDictInitializedToEmpty]
1704 a = {}
1705 a[1] = ''
1706 a() # E: "dict[int, str]" not callable
1707 [builtins fixtures/dict.pyi]
1708
1709 [case testInferDictInitializedToEmptyUsingUpdate]
1710 a = {}
1711 a.update({'': 42})
1712 a() # E: "dict[str, int]" not callable
1713 [builtins fixtures/dict.pyi]
1714
1715 [case testInferDictInitializedToEmptyUsingUpdateError]
1716 a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
1717 a.update([1, 2]) # E: Argument 1 to "update" of "dict" has incompatible type "list[int]"; expected "SupportsKeysAndGetItem[Any, Any]" \
1718 # N: "list" is missing following "SupportsKeysAndGetItem" protocol member: \
1719 # N: keys
1720 a() # E: "dict[Any, Any]" not callable
1721 [builtins fixtures/dict.pyi]
1722
1723 [case testInferDictInitializedToEmptyAndIncompleteTypeInUpdate]
1724 a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
1725 a[1] = {}
1726 b = {} # E: Need type annotation for "b" (hint: "b: dict[<type>, <type>] = ...")
1727 b[{}] = 1
1728 [builtins fixtures/dict.pyi]
1729
1730 -- Parallel mode does not support --no-local-partial-types
1731 [case testInferDictInitializedToEmptyAndUpdatedFromMethod_no_parallel]
1732 # flags: --no-local-partial-types
1733 map = {}
1734 def add() -> None:
1735 map[1] = 2
1736 [builtins fixtures/dict.pyi]
1737
1738 -- Parallel mode does not support --no-local-partial-types
1739 [case testInferDictInitializedToEmptyAndUpdatedFromMethodUnannotated_no_parallel]
1740 # flags: --no-local-partial-types
1741 map = {}
1742 def add():
1743 map[1] = 2
1744 [builtins fixtures/dict.pyi]
1745
1746 [case testSpecialCaseEmptyListInitialization]
1747 def f(blocks: Any): # E: Name "Any" is not defined \
1748 # N: Did you forget to import it from "typing"? (Suggestion: "from typing import Any")
1749 to_process = []
1750 to_process = list(blocks)
1751 [builtins fixtures/list.pyi]
1752
1753 [case testSpecialCaseEmptyListInitialization2]
1754 def f(blocks: object):
1755 to_process = []
1756 to_process = list(blocks) # E: No overload variant of "list" matches argument type "object" \
1757 # N: Possible overload variants: \
1758 # N: def [T] list() -> list[T] \
1759 # N: def [T] list(x: Iterable[T]) -> list[T]
1760 [builtins fixtures/list.pyi]
1761
1762 [case testInferListInitializedToEmptyAndAssigned]
1763 a = []
1764 if bool():
1765 a = [1]
1766 reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
1767
1768 def f():
1769 return [1]
1770 b = []
1771 if bool():
1772 b = f()
1773 reveal_type(b) # N: Revealed type is "builtins.list[Any]"
1774
1775 d = {}
1776 if bool():
1777 d = {1: 'x'}
1778 reveal_type(d) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
1779
1780 dd = {} # E: Need type annotation for "dd" (hint: "dd: dict[<type>, <type>] = ...")
1781 if bool():
1782 dd = [1] # E: Incompatible types in assignment (expression has type "list[int]", variable has type "dict[Any, Any]")
1783 reveal_type(dd) # N: Revealed type is "builtins.dict[Any, Any]"
1784 [builtins fixtures/dict.pyi]
1785
1786 [case testInferOrderedDictInitializedToEmpty]
1787 from collections import OrderedDict
1788
1789 o = OrderedDict()
1790 o[1] = 'x'
1791 reveal_type(o) # N: Revealed type is "collections.OrderedDict[builtins.int, builtins.str]"
1792
1793 d = {1: 'x'}
1794 oo = OrderedDict()
1795 oo.update(d)
1796 reveal_type(oo) # N: Revealed type is "collections.OrderedDict[builtins.int, builtins.str]"
1797 [builtins fixtures/dict.pyi]
1798
1799 [case testEmptyCollectionAssignedToVariableTwiceIncremental]
1800 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
1801 y = x
1802 x = []
1803 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
1804 d = {} # E: Need type annotation for "d" (hint: "d: dict[<type>, <type>] = ...")
1805 z = d
1806 d = {}
1807 reveal_type(d) # N: Revealed type is "builtins.dict[Any, Any]"
1808 [builtins fixtures/dict.pyi]
1809 [out2]
1810 main:1: error: Need type annotation for "x" (hint: "x: list[<type>] = ...")
1811 main:4: note: Revealed type is "builtins.list[Any]"
1812 main:5: error: Need type annotation for "d" (hint: "d: dict[<type>, <type>] = ...")
1813 main:8: note: Revealed type is "builtins.dict[Any, Any]"
1814
1815 [case testEmptyCollectionAssignedToVariableTwiceNoReadIncremental]
1816 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
1817 x = []
1818 [builtins fixtures/list.pyi]
1819 [out2]
1820 main:1: error: Need type annotation for "x" (hint: "x: list[<type>] = ...")
1821
1822 [case testInferAttributeInitializedToEmptyAndAssigned]
1823 class C:
1824 def __init__(self) -> None:
1825 self.a = []
1826 if bool():
1827 self.a = [1]
1828 reveal_type(C().a) # N: Revealed type is "builtins.list[builtins.int]"
1829 [builtins fixtures/list.pyi]
1830
1831 [case testInferAttributeInitializedToEmptyAndAppended]
1832 class C:
1833 def __init__(self) -> None:
1834 self.a = []
1835 if bool():
1836 self.a.append(1)
1837 reveal_type(C().a) # N: Revealed type is "builtins.list[builtins.int]"
1838 [builtins fixtures/list.pyi]
1839
1840 [case testInferAttributeInitializedToEmptyAndAssignedItem]
1841 class C:
1842 def __init__(self) -> None:
1843 self.a = {}
1844 if bool():
1845 self.a[0] = 'yes'
1846 reveal_type(C().a) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
1847 [builtins fixtures/dict.pyi]
1848
1849 [case testInferAttributeInitializedToNoneAndAssigned]
1850 class C:
1851 def __init__(self) -> None:
1852 self.a = None
1853 if bool():
1854 self.a = 1
1855 reveal_type(C().a) # N: Revealed type is "builtins.int | None"
1856
1857 [case testInferAttributeInitializedToEmptyNonSelf]
1858 class C:
1859 def __init__(self) -> None:
1860 self.a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1861 if bool():
1862 a = self
1863 a.a = [1]
1864 a.a.append(1)
1865 reveal_type(C().a) # N: Revealed type is "builtins.list[Any]"
1866 [builtins fixtures/list.pyi]
1867
1868 [case testInferAttributeInitializedToEmptyAndAssignedOtherMethod]
1869 class C:
1870 def __init__(self) -> None:
1871 self.a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1872 def meth(self) -> None:
1873 self.a = [1]
1874 reveal_type(C().a) # N: Revealed type is "builtins.list[Any]"
1875 [builtins fixtures/list.pyi]
1876
1877 [case testInferAttributeInitializedToEmptyAndAppendedOtherMethod]
1878 class C:
1879 def __init__(self) -> None:
1880 self.a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1881 def meth(self) -> None:
1882 self.a.append(1)
1883 reveal_type(C().a) # N: Revealed type is "builtins.list[Any]"
1884 [builtins fixtures/list.pyi]
1885
1886 [case testInferAttributeInitializedToEmptyAndAssignedItemOtherMethod]
1887 class C:
1888 def __init__(self) -> None:
1889 self.a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
1890 def meth(self) -> None:
1891 self.a[0] = 'yes'
1892 reveal_type(C().a) # N: Revealed type is "builtins.dict[Any, Any]"
1893 [builtins fixtures/dict.pyi]
1894
1895 [case testInferAttributeInitializedToNoneAndAssignedOtherMethod]
1896 class C:
1897 def __init__(self) -> None:
1898 self.a = None
1899 def meth(self) -> None:
1900 self.a = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "None")
1901 reveal_type(C().a) # N: Revealed type is "None"
1902
1903 [case testInferAttributeInitializedToEmptyAndAssignedClassBody]
1904 class C:
1905 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1906 def __init__(self) -> None:
1907 self.a = [1]
1908 reveal_type(C().a) # N: Revealed type is "builtins.list[Any]"
1909 [builtins fixtures/list.pyi]
1910
1911 [case testInferAttributeInitializedToEmptyAndAppendedClassBody]
1912 class C:
1913 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
1914 def __init__(self) -> None:
1915 self.a.append(1)
1916 reveal_type(C().a) # N: Revealed type is "builtins.list[Any]"
1917 [builtins fixtures/list.pyi]
1918
1919 [case testInferAttributeInitializedToEmptyAndAssignedItemClassBody]
1920 class C:
1921 a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
1922 def __init__(self) -> None:
1923 self.a[0] = 'yes'
1924 reveal_type(C().a) # N: Revealed type is "builtins.dict[Any, Any]"
1925 [builtins fixtures/dict.pyi]
1926
1927 [case testInferAttributeInitializedToNoneAndAssignedClassBody]
1928 # flags: --no-local-partial-types
1929 class C:
1930 a = None
1931 def __init__(self) -> None:
1932 self.a = 1
1933 reveal_type(C().a) # N: Revealed type is "builtins.int | None"
1934
1935 [case testInferListTypeFromEmptyListAndAny]
1936 def f():
1937 return []
1938
1939 def g() -> None:
1940 x = []
1941 if bool():
1942 x = f()
1943 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
1944
1945 y = []
1946 y.extend(f())
1947 reveal_type(y) # N: Revealed type is "builtins.list[Any]"
1948 [builtins fixtures/list.pyi]
1949
1950 [case testInferFromEmptyDictWhenUsingIn]
1951 d = {}
1952 if 'x' in d:
1953 d['x'] = 1
1954 reveal_type(d) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
1955
1956 dd = {}
1957 if 'x' not in dd:
1958 dd['x'] = 1
1959 reveal_type(dd) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
1960 [builtins fixtures/dict.pyi]
1961
1962 [case testInferFromEmptyDictWhenUsingInSpecialCase]
1963 # flags: --no-strict-optional
1964 d = None
1965 if 'x' in d: # E: "None" has no attribute "__iter__" (not iterable)
1966 pass
1967 reveal_type(d) # N: Revealed type is "None"
1968 [builtins fixtures/dict.pyi]
1969
1970 [case testNoWrongUnreachableWarningWithNoStrictOptionalAndFinalInstance]
1971 # flags: --no-strict-optional --warn-unreachable
1972 from typing import final, Optional
1973
1974 @final
1975 class C: ...
1976
1977 x: Optional[C]
1978 if not x:
1979 x = C()
1980 [builtins fixtures/dict.pyi]
1981
1982 [case testNoWrongUnreachableWarningWithNoStrictOptionalAndEnumLiteral]
1983 # flags: --no-strict-optional --warn-unreachable
1984 from enum import Enum
1985 from typing import Literal, Optional
1986
1987 class E(Enum):
1988 a = 1
1989
1990 x: Optional[Literal[E.a]]
1991 if not x:
1992 x = E.a
1993 [builtins fixtures/dict.pyi]
1994
1995 [case testInferFromEmptyListWhenUsingInWithStrictEquality]
1996 # flags: --strict-equality
1997 def f() -> None:
1998 a = []
1999 if 1 in a: # TODO: This should be an error
2000 a.append('x')
2001 [builtins fixtures/list.pyi]
2002 [typing fixtures/typing-full.pyi]
2003
2004 [case testInferListTypeFromInplaceAdd]
2005 a = []
2006 a += [1]
2007 reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
2008 [builtins fixtures/list.pyi]
2009
2010 [case testInferSetTypeFromInplaceOr]
2011 # flags: --no-strict-optional
2012 a = set()
2013 a |= {'x'}
2014 reveal_type(a) # N: Revealed type is "builtins.set[builtins.str]"
2015 [builtins fixtures/set.pyi]
2016
2017
2018 -- Inferring types of variables first initialized to None (partial types)
2019 -- ----------------------------------------------------------------------
2020
2021
2022 [case testLocalVariablePartiallyInitializedToNone]
2023 def f() -> None:
2024 if object():
2025 x = None
2026 else:
2027 x = 1
2028 x() # E: "int" not callable \
2029 # E: "None" not callable
2030 [out]
2031
2032 [case testLocalVariablePartiallyTwiceInitializedToNone]
2033 def f() -> None:
2034 if object():
2035 x = None
2036 elif object():
2037 x = None
2038 else:
2039 x = 1
2040 x() # E: "int" not callable \
2041 # E: "None" not callable
2042 [out]
2043
2044 [case testLvarInitializedToNoneWithoutType]
2045 import typing
2046 def f() -> None:
2047 a = None
2048 a.x() # E: "None" has no attribute "x"
2049 [out]
2050
2051 [case testGvarPartiallyInitializedToNone]
2052 x = None
2053 if object():
2054 x = 1
2055 x() # E: "int" not callable \
2056 # E: "None" not callable
2057
2058 [case testPartiallyInitializedToNoneAndThenToPartialList]
2059 x = None
2060 if object():
2061 # Promote from partial None to partial list.
2062 x = []
2063 x.append(1)
2064 x.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
2065 [builtins fixtures/list.pyi]
2066
2067 [case testPartiallyInitializedToNoneAndThenReadPartialList]
2068 x = None
2069 if object():
2070 # Promote from partial None to partial list.
2071 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
2072 x
2073 [builtins fixtures/list.pyi]
2074
2075 [case testPartiallyInitializedToNoneAndPartialListAndLeftPartial]
2076 def f() -> None:
2077 x = None
2078 if object():
2079 # Promote from partial None to partial list.
2080 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
2081 [builtins fixtures/list.pyi]
2082 [out]
2083
2084 [case testPartiallyInitializedToNoneAndThenToIncompleteType-skip]
2085 # TODO(ddfisher): fix partial type bug and re-enable
2086 from typing import TypeVar, Dict
2087 T = TypeVar('T')
2088 def f(*x: T) -> Dict[int, T]: pass
2089 x = None # E: Need type annotation for "x"
2090 if object():
2091 x = f()
2092 [builtins fixtures/dict.pyi]
2093
2094 [case testPartiallyInitializedVariableDoesNotEscapeScope1]
2095 def f() -> None:
2096 x = None
2097 reveal_type(x) # N: Revealed type is "None"
2098 x = 1
2099 [out]
2100
2101 [case testPartiallyInitializedVariableDoesNotEscapeScope2]
2102 # flags: --no-local-partial-types
2103 x = None
2104 def f() -> None:
2105 x = None
2106 x = 1
2107 x() # E: "None" not callable
2108
2109 [case testAttributePartiallyInitializedToNone]
2110 class A:
2111 def f(self) -> None:
2112 self.x = None
2113 self.x = 1
2114 self.x() # E: "int" not callable
2115 [out]
2116
2117 [case testAttributePartiallyInitializedToNoneWithMissingAnnotation]
2118 class A:
2119 def f(self) -> None:
2120 self.x = None
2121
2122 def g(self) -> None:
2123 self.x = 1
2124 self.x()
2125 [out]
2126 main:6: error: Incompatible types in assignment (expression has type "int", variable has type "None")
2127 main:7: error: "None" not callable
2128
2129 [case testGlobalInitializedToNoneSetFromFunction]
2130 # flags: --no-local-partial-types
2131 a = None
2132 def f() -> None:
2133 global a
2134 a = 42
2135 reveal_type(a) # N: Revealed type is "builtins.int"
2136 reveal_type(a) # N: Revealed type is "builtins.int | None"
2137
2138 b = None
2139 def unchecked():
2140 global b
2141 b = 42
2142 reveal_type(b) # N: Revealed type is "Any | None"
2143
2144 [case testGlobalInitializedToNoneSetFromFunctionLocalPartialTypes]
2145 # flags: --local-partial-types
2146 a = None
2147 def f() -> None:
2148 global a
2149 a = 42
2150 reveal_type(a) # N: Revealed type is "builtins.int"
2151 reveal_type(a) # N: Revealed type is "builtins.int | None"
2152
2153 b = None
2154 def unchecked():
2155 global b
2156 b = 42
2157 reveal_type(b) # N: Revealed type is "Any | None"
2158
2159 [case testGlobalInitializedToNoneSetFromMethod]
2160 # flags: --no-local-partial-types
2161 a = None
2162 class C:
2163 def m(self) -> None:
2164 global a
2165 a = 42
2166 reveal_type(a) # N: Revealed type is "builtins.int | None"
2167
2168 b = None
2169 class CC:
2170 def unchecked(self):
2171 global b
2172 b = 42
2173 reveal_type(b) # N: Revealed type is "Any | None"
2174
2175 [case testGlobalInitializedToNoneSetFromMethodLocalPartialTypes]
2176 # flags: --local-partial-types
2177 a = None
2178 class C:
2179 def m(self) -> None:
2180 global a
2181 a = 42
2182 reveal_type(a) # N: Revealed type is "builtins.int | None"
2183
2184 b = None
2185 class CC:
2186 def unchecked(self):
2187 global b
2188 b = 42
2189 reveal_type(b) # N: Revealed type is "Any | None"
2190
2191 [case testPartialTypeErrorSpecialCase1]
2192 # flags: --no-local-partial-types
2193 # This used to crash.
2194 class A:
2195 x = None
2196 def f(self) -> None:
2197 for a in self.x: # E: "None" has no attribute "__iter__" (not iterable)
2198 pass
2199 [builtins fixtures/for.pyi]
2200
2201 [case testPartialTypeErrorSpecialCase2]
2202 # This used to crash.
2203 class A:
2204 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
2205 def f(self) -> None:
2206 for a in self.x:
2207 pass
2208 [builtins fixtures/for.pyi]
2209
2210 [case testPartialTypeErrorSpecialCase3]
2211 # flags: --no-local-partial-types
2212 class A:
2213 x = None
2214 def f(self) -> None:
2215 for a in A.x: # E: "None" has no attribute "__iter__" (not iterable)
2216 pass
2217 [builtins fixtures/for.pyi]
2218
2219 [case testPartialTypeErrorSpecialCase4]
2220 # This used to crash.
2221 arr = []
2222 arr.append(arr.append(1))
2223 [builtins fixtures/list.pyi]
2224 [out]
2225 main:3: error: "append" of "list" does not return a value (it only ever returns None)
2226 main:3: error: Argument 1 to "append" of "list" has incompatible type "None"; expected "int"
2227
2228 -- Multipass
2229 -- ---------
2230
2231
2232 [case testMultipassAndAccessVariableBeforeDefinition]
2233 def f() -> None:
2234 y = x
2235 y() # E: "int" not callable
2236 x = 1
2237 [out]
2238
2239 [case testMultipassAndAccessInstanceVariableBeforeDefinition]
2240 class A:
2241 def f(self) -> None:
2242 y = self.x
2243 y() # E: "int" not callable
2244
2245 def g(self) -> None:
2246 self.x = 1
2247 [out]
2248
2249 [case testMultipassAndTopLevelVariable]
2250 y = x # E: Cannot determine type of "x" # E: Name "x" is used before definition
2251 y()
2252 x = 1+int()
2253 [out]
2254
2255 [case testMultipassAndDecoratedMethod]
2256 from typing import Callable, TypeVar
2257
2258 T = TypeVar('T')
2259
2260 class A:
2261 def f(self) -> None:
2262 self.g() # E: Too few arguments for "g" of "A"
2263 self.g(1)
2264 @dec
2265 def g(self, x: str) -> None: pass
2266
2267 def dec(f: Callable[[A, str], T]) -> Callable[[A, int], T]: pass
2268 [out]
2269
2270 [case testMultipassAndDefineAttributeBasedOnNotReadyAttribute]
2271 class A:
2272 def f(self) -> None:
2273 self.y = self.x
2274
2275 def g(self) -> None:
2276 self.x = 1
2277
2278 def h(self) -> None:
2279 self.y() # E: "int" not callable
2280 [out]
2281
2282 [case testMultipassAndDefineAttributeBasedOnNotReadyAttribute2]
2283 class A:
2284 def f(self) -> None:
2285 self.y = self.x
2286 self.z = self.y
2287 self.z() # E
2288 self.y() # E
2289
2290 def g(self) -> None:
2291 self.x = 1
2292
2293 def h(self) -> None:
2294 self.y() # E
2295 [out]
2296 main:5: error: "int" not callable
2297 main:6: error: "int" not callable
2298 main:12: error: "int" not callable
2299
2300 [case testMultipassAndPartialTypes]
2301 def f() -> None:
2302 x = []
2303 y
2304 x.append(1)
2305 x.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
2306 x.append(y) # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
2307 y = ''
2308 [builtins fixtures/list.pyi]
2309 [out]
2310
2311 [case testMultipassAndPartialTypes2]
2312 s = ''
2313 n = 0
2314 def f() -> None:
2315 global s, n
2316 x = []
2317 x.append(y)
2318 s = x[0]
2319 n = x[0] # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2320 x.append(1) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
2321 y = ''
2322 [builtins fixtures/list.pyi]
2323 [out]
2324
2325 [case testMultipassAndPartialTypes3]
2326 from typing import Dict
2327 def g(d: Dict[str, int]) -> None: pass
2328 def f() -> None:
2329 x = {}
2330 x[1] = y
2331 g(x) # E: Argument 1 to "g" has incompatible type "dict[int, str]"; expected "dict[str, int]"
2332 x[1] = 1 # E: Incompatible types in assignment (expression has type "int", target has type "str")
2333 x[1] = ''
2334 y = ''
2335 [builtins fixtures/dict.pyi]
2336 [out]
2337
2338 [case testMultipassAndPartialTypes4]
2339 from typing import Dict
2340 def g(d: Dict[str, int]) -> None: pass
2341 def f() -> None:
2342 x = {}
2343 y
2344 x[1] = 1
2345 g(x) # E: Argument 1 to "g" has incompatible type "dict[int, int]"; expected "dict[str, int]"
2346 y = ''
2347 [builtins fixtures/dict.pyi]
2348 [out]
2349
2350 [case testMultipassAndCircularDependency]
2351 class A:
2352 def f(self) -> None:
2353 self.x = self.y # E: Cannot determine type of "y"
2354
2355 def g(self) -> None:
2356 self.y = self.x
2357 [out]
2358
2359 [case testMultipassAndPartialTypesSpecialCase1]
2360 def f() -> None:
2361 y = o
2362 x = []
2363 x.append(y)
2364 x() # E: "list[int]" not callable
2365 o = 1
2366 [builtins fixtures/list.pyi]
2367 [out]
2368
2369 [case testMultipassAndPartialTypesSpecialCase2]
2370 def f() -> None:
2371 y = o
2372 x = {}
2373 x[''] = y
2374 x() # E: "dict[str, int]" not callable
2375 o = 1
2376 [builtins fixtures/dict.pyi]
2377 [out]
2378
2379 [case testMultipassAndPartialTypesSpecialCase3]
2380 def f() -> None:
2381 x = {} # E: Need type annotation for "x" (hint: "x: dict[<type>, <type>] = ...")
2382 y = o
2383 z = {} # E: Need type annotation for "z" (hint: "z: dict[<type>, <type>] = ...")
2384 o = 1
2385 [builtins fixtures/dict.pyi]
2386 [out]
2387
2388 [case testMultipassAndPartialTypesSpecialCase4]
2389 def f() -> None:
2390 y = o
2391 x = None
2392 x = y
2393 x() # E: "int" not callable
2394 o = 1
2395 [out]
2396
2397 [case testMultipassAndPartialTypesSpecialCase5]
2398 def f() -> None:
2399 x = None
2400 y = o
2401 x = y
2402 x() # E: "int" not callable
2403 o = 1
2404 [out]
2405
2406 [case testMultipassAndClassAttribute]
2407 class S:
2408 def foo(self) -> int:
2409 return R.X
2410
2411 class R:
2412 X = 2
2413
2414 [case testMultipassAndMultipleFiles]
2415 import m
2416 def f() -> None:
2417 x() # E: "int" not callable
2418 x = 0
2419 [file m.py]
2420 def g() -> None:
2421 y() # E: "int" not callable
2422 y = 0
2423
2424 [case testForwardReferenceToDecoratedClassMethod]
2425 from typing import TypeVar, Callable
2426
2427 T = TypeVar('T')
2428 def dec() -> Callable[[T], T]: pass
2429
2430 A.g # E: Cannot determine type of "g" # E: Name "A" is used before definition
2431
2432 class A:
2433 @classmethod
2434 def f(cls) -> None:
2435 reveal_type(cls.g) # N: Revealed type is "def (x: builtins.str)"
2436
2437 @classmethod
2438 @dec()
2439 def g(cls, x: str) -> None:
2440 pass
2441
2442 @classmethod
2443 def h(cls) -> None:
2444 reveal_type(cls.g) # N: Revealed type is "def (x: builtins.str)"
2445
2446 reveal_type(A.g) # N: Revealed type is "def (x: builtins.str)"
2447 [builtins fixtures/classmethod.pyi]
2448
2449
2450 -- Tests for special cases of unification
2451 -- --------------------------------------
2452
2453
2454 [case testUnificationRedundantUnion]
2455 from typing import Union
2456 a: Union[int, str]
2457 b: Union[str, tuple]
2458 def f(): pass
2459 def g(x: Union[int, str]): pass
2460 c = a if f() else b
2461 g(c) # E: Argument 1 to "g" has incompatible type "int | str | tuple[Any, ...]"; expected "int | str"
2462 [builtins fixtures/tuple.pyi]
2463
2464 [case testUnificationMultipleInheritance]
2465 class A: pass
2466 class B:
2467 def foo(self): pass
2468 class C(A, B): pass
2469 def f(): pass
2470 a1 = B() if f() else C()
2471 a1.foo()
2472 a2 = C() if f() else B()
2473 a2.foo()
2474
2475 [case testUnificationMultipleInheritanceAmbiguous]
2476 # Show that join_instances_via_supertype() breaks ties using the first base class.
2477 class A1: pass
2478 class B1:
2479 def foo1(self): pass
2480 class C1(A1, B1): pass
2481
2482 class A2: pass
2483 class B2:
2484 def foo2(self): pass
2485 class C2(A2, B2): pass
2486
2487 class D1(C1, C2): pass
2488 class D2(C2, C1): pass
2489
2490 def f(): pass
2491
2492 a1 = D1() if f() else D2()
2493 a1.foo1()
2494 a2 = D2() if f() else D1()
2495 a2.foo2()
2496
2497 [case testUnificationEmptyListLeft]
2498 def f(): pass
2499 a = [] if f() else [0]
2500 a() # E: "list[int]" not callable
2501 [builtins fixtures/list.pyi]
2502
2503 [case testUnificationEmptyListRight]
2504 def f(): pass
2505 a = [0] if f() else []
2506 a() # E: "list[int]" not callable
2507 [builtins fixtures/list.pyi]
2508
2509 [case testUnificationEmptyListLeftInContext]
2510 from typing import List
2511 def f(): pass
2512 a = [] if f() else [0] # type: list[int]
2513 a() # E: "list[int]" not callable
2514 [builtins fixtures/list.pyi]
2515
2516 [case testUnificationEmptyListRightInContext]
2517 # TODO Find an example that really needs the context
2518 from typing import List
2519 def f(): pass
2520 a = [0] if f() else [] # type: list[int]
2521 a() # E: "list[int]" not callable
2522 [builtins fixtures/list.pyi]
2523
2524 [case testUnificationEmptySetLeft]
2525 def f(): pass
2526 a = set() if f() else {0}
2527 a() # E: "set[int]" not callable
2528 [builtins fixtures/set.pyi]
2529
2530 [case testUnificationEmptyDictLeft]
2531 def f(): pass
2532 a = {} if f() else {0: 0}
2533 a() # E: "dict[int, int]" not callable
2534 [builtins fixtures/dict.pyi]
2535
2536 [case testUnificationEmptyDictRight]
2537 def f(): pass
2538 a = {0: 0} if f() else {}
2539 a() # E: "dict[int, int]" not callable
2540 [builtins fixtures/dict.pyi]
2541
2542 [case testUnificationDictWithEmptyListLeft]
2543 def f(): pass
2544 a = {0: []} if f() else {0: [0]}
2545 a() # E: "dict[int, list[int]]" not callable
2546 [builtins fixtures/dict.pyi]
2547
2548 [case testUnificationDictWithEmptyListRight]
2549 def f(): pass
2550 a = {0: [0]} if f() else {0: []}
2551 a() # E: "dict[int, list[int]]" not callable
2552 [builtins fixtures/dict.pyi]
2553
2554 [case testMisguidedSetItem]
2555 from typing import Generic, Sequence, TypeVar
2556 T = TypeVar('T')
2557 class C(Sequence[T], Generic[T]): pass
2558 C[0] = 0
2559 [out]
2560 main:4: error: Unsupported target for indexed assignment ("type[C[T]]")
2561 main:4: error: Invalid type: try using Literal[0] instead?
2562
2563 [case testNoCrashOnPartialMember]
2564 # flags: --no-local-partial-types
2565 class C:
2566 x = None
2567 def __init__(self) -> None:
2568 self.x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
2569 [builtins fixtures/list.pyi]
2570
2571 [case testNoCrashOnPartialVariable]
2572 from typing import Tuple, TypeVar
2573 T = TypeVar('T', bound=str)
2574
2575 def f(x: T) -> Tuple[T]:
2576 ...
2577 x = None
2578 (x,) = f('')
2579 reveal_type(x) # N: Revealed type is "builtins.str"
2580 [builtins fixtures/tuple.pyi]
2581
2582 [case testNoCrashOnPartialVariable2]
2583 # flags: --no-local-partial-types
2584 from typing import Tuple, TypeVar
2585 T = TypeVar('T', bound=str)
2586
2587 def f() -> Tuple[T]:
2588 ...
2589 x = None # E: Need type annotation for "x"
2590 if int():
2591 (x,) = f()
2592 [builtins fixtures/tuple.pyi]
2593
2594 [case testNoCrashOnPartialVariable3]
2595 from typing import Tuple, TypeVar
2596 T = TypeVar('T')
2597
2598 def f(x: T) -> Tuple[T, T]:
2599 ...
2600 x = None
2601 (x, x) = f('')
2602 reveal_type(x) # N: Revealed type is "builtins.str"
2603 [builtins fixtures/tuple.pyi]
2604
2605 [case testRejectsPartialWithUninhabited]
2606 from typing import Generic, TypeVar
2607 T = TypeVar('T')
2608
2609 class Foo(Generic[T]): ...
2610
2611 def check() -> None:
2612 x = None # E: Need type annotation for "x"
2613 if int():
2614 x = Foo()
2615 reveal_type(x) # N: Revealed type is "__main__.Foo[Any]"
2616 reveal_type(x) # N: Revealed type is "__main__.Foo[Any] | None"
2617
2618 [case testRejectsPartialWithUninhabited2]
2619 from typing import Generic, TypeVar
2620 T = TypeVar('T')
2621
2622 class Foo(Generic[T]): ...
2623
2624 x = None # E: Need type annotation for "x"
2625
2626 def check() -> None:
2627 global x
2628 x = Foo()
2629 reveal_type(x) # N: Revealed type is "__main__.Foo[Any]"
2630
2631 reveal_type(x) # N: Revealed type is "__main__.Foo[Any] | None"
2632
2633 [case testRejectsPartialWithUninhabited3]
2634 # Without force-rejecting Partial<None>, this crashes:
2635 # https://github.com/python/mypy/issues/16573
2636 from typing import Generic, TypeVar
2637 T = TypeVar('T')
2638
2639 class Foo(Generic[T]): ...
2640
2641 def check() -> None:
2642 client = None # E: Need type annotation for "client"
2643
2644 if client := Foo():
2645 reveal_type(client) # N: Revealed type is "__main__.Foo[Any]"
2646
2647 reveal_type(client) # N: Revealed type is "__main__.Foo[Any] | None"
2648
2649 client = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "Foo[Any] | None")
2650 reveal_type(client) # N: Revealed type is "__main__.Foo[Any] | None"
2651
2652 [case testRejectsPartialWithUninhabitedIndependently]
2653 from typing import Generic, TypeVar
2654 T = TypeVar('T')
2655
2656 class Foo(Generic[T]): ...
2657
2658 client = None # E: Need type annotation for "client"
2659
2660 def bad() -> None:
2661 global client
2662 client = Foo()
2663 reveal_type(client) # N: Revealed type is "__main__.Foo[Any]"
2664
2665 def good() -> None:
2666 global client
2667 client = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Foo[Any] | None")
2668 reveal_type(client) # N: Revealed type is "__main__.Foo[Any] | None"
2669
2670 def bad2() -> None:
2671 global client
2672 client = Foo()
2673 reveal_type(client) # N: Revealed type is "__main__.Foo[Any]"
2674
2675 [case testInferenceNestedTuplesFromGenericIterable]
2676 from typing import Tuple, TypeVar
2677
2678 T = TypeVar('T')
2679
2680 def make_tuple(elem: T) -> Tuple[T]:
2681 return (elem,)
2682
2683 def main() -> None:
2684 ((a, b),) = make_tuple((1, 2))
2685 reveal_type(a) # N: Revealed type is "builtins.int"
2686 reveal_type(b) # N: Revealed type is "builtins.int"
2687 [builtins fixtures/tuple.pyi]
2688
2689 [case testDontMarkUnreachableAfterInferenceUninhabited]
2690 from typing import TypeVar
2691 T = TypeVar('T')
2692 def f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
2693
2694 class C:
2695 x = f() # E: Need type annotation for "x"
2696 def m(self) -> str:
2697 return 42 # E: Incompatible return value type (got "int", expected "str")
2698
2699 if bool():
2700 f()
2701 1() # E: "int" not callable
2702 [builtins fixtures/list.pyi]
2703 [out]
2704
2705 [case testDontMarkUnreachableAfterInferenceUninhabited2]
2706 from typing import TypeVar, Optional
2707 T = TypeVar('T')
2708 def f(x: Optional[T] = None) -> T: pass
2709
2710 class C:
2711 x = f() # E: Need type annotation for "x"
2712 def m(self) -> str:
2713 return 42 # E: Incompatible return value type (got "int", expected "str")
2714
2715 if bool():
2716 f()
2717 1() # E: "int" not callable
2718 [builtins fixtures/list.pyi]
2719 [out]
2720
2721 [case testDontMarkUnreachableAfterInferenceUninhabited3]
2722 from typing import TypeVar, List
2723 T = TypeVar('T')
2724 def f(x: List[T]) -> T: pass
2725
2726 class C:
2727 x = f([]) # E: Need type annotation for "x"
2728 def m(self) -> str:
2729 return 42 # E: Incompatible return value type (got "int", expected "str")
2730
2731 if bool():
2732 f([])
2733 1() # E: "int" not callable
2734 [builtins fixtures/list.pyi]
2735 [out]
2736
2737
2738 -- --local-partial-types
2739 -- ---------------------
2740
2741
2742 [case testLocalPartialTypesWithGlobalInitializedToNone]
2743 # flags: --local-partial-types
2744 x = None
2745
2746 def f() -> None:
2747 global x
2748 x = 1
2749
2750 reveal_type(x) # N: Revealed type is "builtins.int | None"
2751
2752 [case testLocalPartialTypesWithGlobalInitializedToNone2]
2753 # flags: --local-partial-types
2754 x = None
2755
2756 def f():
2757 global x
2758 x = 1
2759
2760 reveal_type(x) # N: Revealed type is "Any | None"
2761
2762 [case testLocalPartialTypesWithGlobalInitializedToNone3]
2763 # flags: --local-partial-types --no-strict-optional
2764 x = None
2765
2766 def f() -> None:
2767 global x
2768 x = 1
2769
2770 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2771 reveal_type(x) # N: Revealed type is "builtins.int"
2772
2773 [case testLocalPartialTypesWithGlobalInitializedToNoneStrictOptional]
2774 # flags: --local-partial-types
2775 x = None
2776
2777 def f() -> None:
2778 global x
2779 x = 1
2780
2781 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int | None")
2782 def g() -> None:
2783 reveal_type(x) # N: Revealed type is "builtins.int | None"
2784
2785 -- TODO: combine 4 tests below back into 2 when possible.
2786 [case testLocalPartialTypesWithGlobalInitializedToNone4_no_parallel]
2787 # flags: --local-partial-types --no-strict-optional
2788 a = None
2789
2790 def f() -> None:
2791 reveal_type(a) # N: Revealed type is "None"
2792
2793 reveal_type(a) # N: Revealed type is "None"
2794 a = ''
2795 reveal_type(a) # N: Revealed type is "builtins.str"
2796 [builtins fixtures/list.pyi]
2797
2798 [case testLocalPartialTypesWithGlobalInitializedToNone5_no_parallel]
2799 # flags: --local-partial-types
2800 a = None
2801
2802 def f() -> None:
2803 reveal_type(a) # N: Revealed type is "None"
2804
2805 reveal_type(a) # N: Revealed type is "None"
2806 a = ''
2807 reveal_type(a) # N: Revealed type is "builtins.str"
2808 [builtins fixtures/list.pyi]
2809
2810 [case testLocalPartialTypesWithGlobalInitializedToNone4_parallel_only]
2811 # flags: --local-partial-types --no-strict-optional
2812 a = None
2813
2814 def f() -> None:
2815 reveal_type(a) # N: Revealed type is "builtins.str"
2816
2817 reveal_type(a) # N: Revealed type is "None"
2818 a = ''
2819 reveal_type(a) # N: Revealed type is "builtins.str"
2820 [builtins fixtures/list.pyi]
2821
2822 [case testLocalPartialTypesWithGlobalInitializedToNone5_parallel_only]
2823 # flags: --local-partial-types
2824 a = None
2825
2826 def f() -> None:
2827 reveal_type(a) # N: Revealed type is "builtins.str | None"
2828
2829 reveal_type(a) # N: Revealed type is "None"
2830 a = ''
2831 reveal_type(a) # N: Revealed type is "builtins.str"
2832 [builtins fixtures/list.pyi]
2833
2834 [case testLocalPartialTypesWithClassAttributeInitializedToNone]
2835 # flags: --local-partial-types
2836 class A:
2837 x = None
2838
2839 def f(self) -> None:
2840 self.x = 1
2841
2842 [case testLocalPartialTypesWithClassAttributeInitializedToEmptyDict]
2843 # flags: --local-partial-types
2844 class A:
2845 x = {} # E: Need type annotation for "x" (hint: "x: dict[<type>, <type>] = ...")
2846
2847 def f(self) -> None:
2848 self.x[0] = ''
2849
2850 reveal_type(A().x) # N: Revealed type is "builtins.dict[Any, Any]"
2851 reveal_type(A.x) # N: Revealed type is "builtins.dict[Any, Any]"
2852 [builtins fixtures/dict.pyi]
2853
2854 [case testLocalPartialTypesWithGlobalInitializedToEmptyList]
2855 # flags: --local-partial-types
2856 a = []
2857
2858 def f() -> None:
2859 a[0]
2860 reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
2861
2862 a.append(1)
2863 reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
2864 [builtins fixtures/list.pyi]
2865
2866 [case testLocalPartialTypesWithGlobalInitializedToEmptyList2]
2867 # flags: --local-partial-types
2868 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
2869
2870 def f() -> None:
2871 a.append(1)
2872 reveal_type(a) # N: Revealed type is "builtins.list[Any]"
2873
2874 reveal_type(a) # N: Revealed type is "builtins.list[Any]"
2875 [builtins fixtures/list.pyi]
2876
2877 [case testLocalPartialTypesWithGlobalInitializedToEmptyList3]
2878 # flags: --local-partial-types
2879 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
2880
2881 def f():
2882 a.append(1)
2883
2884 reveal_type(a) # N: Revealed type is "builtins.list[Any]"
2885 [builtins fixtures/list.pyi]
2886
2887 [case testLocalPartialTypesWithGlobalInitializedToEmptyDict]
2888 # flags: --local-partial-types
2889 a = {}
2890
2891 def f() -> None:
2892 a[0]
2893 reveal_type(a) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
2894
2895 a[0] = ''
2896 reveal_type(a) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
2897 [builtins fixtures/dict.pyi]
2898
2899 [case testLocalPartialTypesWithGlobalInitializedToEmptyDict2]
2900 # flags: --local-partial-types
2901 a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
2902
2903 def f() -> None:
2904 a[0] = ''
2905 reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]"
2906
2907 reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]"
2908 [builtins fixtures/dict.pyi]
2909
2910 [case testLocalPartialTypesWithGlobalInitializedToEmptyDict3]
2911 # flags: --local-partial-types
2912 a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
2913
2914 def f():
2915 a[0] = ''
2916
2917 reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]"
2918 [builtins fixtures/dict.pyi]
2919
2920 [case testLocalPartialTypesWithNestedFunction]
2921 # flags: --local-partial-types
2922 def f() -> None:
2923 a = {}
2924 def g() -> None:
2925 a[0] = ''
2926 reveal_type(a) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
2927 [builtins fixtures/dict.pyi]
2928
2929 [case testLocalPartialTypesWithNestedFunction2]
2930 # flags: --local-partial-types
2931 def f() -> None:
2932 a = []
2933 def g() -> None:
2934 a.append(1)
2935 reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
2936 [builtins fixtures/list.pyi]
2937
2938 [case testLocalPartialTypesWithNestedFunction3]
2939 # flags: --local-partial-types --no-strict-optional
2940 def f() -> None:
2941 a = None
2942 def g() -> None:
2943 nonlocal a
2944 a = ''
2945 reveal_type(a) # N: Revealed type is "builtins.str"
2946 [builtins fixtures/dict.pyi]
2947
2948 [case testLocalPartialTypesWithInheritance]
2949 # flags: --local-partial-types
2950 from typing import Optional
2951
2952 class A:
2953 x: Optional[str]
2954
2955 class B(A):
2956 x = None
2957
2958 reveal_type(B.x) # N: Revealed type is "None"
2959
2960 [case testLocalPartialTypesWithInheritance2]
2961 # flags: --local-partial-types
2962 class A:
2963 x: str
2964
2965 class B(A):
2966 x = None # E: Incompatible types in assignment (expression has type "None", base class "A" defined the type as "str")
2967
2968 [case testLocalPartialTypesWithAnyBaseClass]
2969 # flags: --local-partial-types
2970 from typing import Any
2971
2972 A: Any
2973
2974 class B(A):
2975 x = None
2976
2977 class C(B):
2978 y = None
2979
2980 [case testLocalPartialTypesInMultipleMroItems]
2981 # flags: --local-partial-types
2982 from typing import Optional
2983
2984 class A:
2985 x: Optional[str]
2986
2987 class B(A):
2988 x = None
2989
2990 class C(B):
2991 x = None
2992
2993 # TODO: Inferring None below is unsafe (https://github.com/python/mypy/issues/3208)
2994 reveal_type(B.x) # N: Revealed type is "None"
2995 reveal_type(C.x) # N: Revealed type is "None"
2996
2997 [case testLocalPartialTypesWithInheritance3]
2998 # flags: --local-partial-types
2999 from typing import Optional
3000
3001 class X: pass
3002 class Y(X): pass
3003
3004 class A:
3005 x: Optional[X]
3006
3007 class B(A):
3008 x = None
3009 x = Y()
3010
3011 reveal_type(B.x) # N: Revealed type is "__main__.Y | None"
3012
3013 [case testLocalPartialTypesBinderSpecialCase]
3014 # flags: --local-partial-types
3015 from typing import List
3016
3017 def f(x): pass
3018
3019 class A:
3020 x = None
3021
3022 def f(self, p: List[str]) -> None:
3023 self.x = f(p)
3024 f(z for z in p)
3025 [builtins fixtures/list.pyi]
3026
3027 [case testLocalPartialTypesAccessPartialNoneAttribute]
3028 # flags: --local-partial-types
3029 class C:
3030 a = None
3031
3032 def f(self, x) -> None:
3033 C.a.y # E: "None" has no attribute "y"
3034
3035 [case testLocalPartialTypesAccessPartialNoneAttribute2]
3036 # flags: --local-partial-types
3037 class C:
3038 a = None
3039
3040 def f(self, x) -> None:
3041 self.a.y # E: "None" has no attribute "y"
3042
3043 [case testUnusedTargetLocal]
3044 def foo() -> None:
3045 _ = 0
3046 _ = ''
3047
3048 [case testUnusedTargetNotGlobal]
3049 _ = 0
3050 _ = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3051
3052 [case testUnusedTargetNotClass]
3053 # flags: --allow-redefinition-old
3054 class C:
3055 _, _ = 0, 0
3056 _ = ''
3057 reveal_type(C._) # N: Revealed type is "builtins.str"
3058
3059 [case testUnusedTargetNotClass2]
3060 # flags: --disallow-redefinition-old
3061 class C:
3062 _, _ = 0, 0
3063 _ = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3064 reveal_type(C._) # N: Revealed type is "builtins.int"
3065
3066 [case testUnusedTargetTupleUnpacking]
3067 def foo() -> None:
3068 _, _ = (0, '')
3069 _ = 0
3070 _ = ''
3071 def bar() -> None:
3072 t = (0, '')
3073 _, _ = t
3074 _ = 0
3075 _ = ''
3076 [builtins fixtures/tuple.pyi]
3077
3078 [case testUnusedTargetMultipleTargets]
3079 def foo() -> None:
3080 _ = x = 0
3081 _ = y = ''
3082 _ = 0
3083 _ = ''
3084 def bar() -> None:
3085 x = _ = 0
3086 y = _ = ''
3087 _ = 0
3088 _ = ''
3089 x + 0
3090 y + ''
3091 x + '' # E: Unsupported operand types for + ("int" and "str")
3092 y + 0 # E: Unsupported operand types for + ("str" and "int")
3093 [builtins fixtures/primitives.pyi]
3094
3095 [case testUnusedTargetNotImport]
3096 import d, c, b, a
3097 [file _.py]
3098 def f(): pass
3099 [file m.py]
3100 def f(): pass
3101 _ = f
3102 _ = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "Callable[[], Any]")
3103 [file a.py]
3104 def foo() -> None:
3105 import _
3106 _.f()
3107 _ = 0 # E: Incompatible types in assignment (expression has type "int", variable has type Module)
3108 [file b.py]
3109 def foo() -> None:
3110 import m as _
3111 _.f()
3112 _ = 0 # E: Incompatible types in assignment (expression has type "int", variable has type Module)
3113 [file c.py]
3114 def foo() -> None:
3115 from m import _
3116 _()
3117 _ = '' # E: Incompatible types in assignment (expression has type "str", variable has type "Callable[[], Any]")
3118 [file d.py]
3119 def foo() -> None:
3120 from m import f as _
3121 _()
3122 _ = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "Callable[[], Any]")
3123 [builtins fixtures/module.pyi]
3124
3125 [case testUnderscoreClass]
3126 def foo() -> None:
3127 class _:
3128 pass
3129 _().method() # E: "_" has no attribute "method"
3130
3131 [case testUnusedTargetForLoop]
3132 def f() -> None:
3133 a = [(0, '', 0)]
3134 for _, _, x in a:
3135 x = 0
3136 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3137 _ = 0
3138 _ = ''
3139 [builtins fixtures/list.pyi]
3140
3141 [case testUnusedTargetWithClause]
3142 class C:
3143 def __enter__(self) -> int: pass
3144 def __exit__(self, *args): pass
3145 def f() -> None:
3146 with C() as _: pass
3147 _ = 0
3148 _ = ''
3149 [builtins fixtures/tuple.pyi]
3150
3151 [case testUnusedTargetNotExceptClause]
3152 # Things don't work for except clauses.
3153 # This is due to the implementation, but it's just as well.
3154 def f() -> None:
3155 try: pass
3156 except BaseException as _:
3157 _ = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "BaseException")
3158 _ = '' # E: Incompatible types in assignment (expression has type "str", variable has type "BaseException")
3159 [builtins fixtures/exception.pyi]
3160
3161 -- Tests for permissive toplevel checking
3162 -- --------------
3163
3164 [case testPermissiveAttributeOverride1]
3165 # flags: --allow-untyped-globals
3166
3167 class A:
3168 x = None
3169
3170 class B(A):
3171 x = 12
3172
3173 class C(A):
3174 x = '12'
3175
3176 reveal_type(A.x) # N: Revealed type is "Any | None"
3177 reveal_type(B.x) # N: Revealed type is "builtins.int"
3178 reveal_type(C.x) # N: Revealed type is "builtins.str"
3179
3180 [case testPermissiveAttributeOverride2]
3181 # flags: --allow-untyped-globals
3182
3183 class A:
3184 x = []
3185
3186 class B(A):
3187 x = [12]
3188
3189 class C(A):
3190 x = ['12']
3191
3192 reveal_type(A.x) # N: Revealed type is "builtins.list[Any]"
3193 reveal_type(B.x) # N: Revealed type is "builtins.list[builtins.int]"
3194 reveal_type(C.x) # N: Revealed type is "builtins.list[builtins.str]"
3195
3196 [builtins fixtures/list.pyi]
3197
3198 [case testPermissiveAttribute]
3199 # flags: --allow-untyped-globals
3200
3201 class A:
3202 x = []
3203 def f(self) -> None:
3204 reveal_type(self.x) # N: Revealed type is "builtins.list[Any]"
3205
3206 [builtins fixtures/list.pyi]
3207
3208 [case testPermissiveGlobalContainer1]
3209 # flags: --allow-untyped-globals --local-partial-types
3210
3211 import a
3212
3213 [file b.py]
3214 x = []
3215 y = {}
3216
3217 def foo() -> None:
3218 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3219 reveal_type(y) # N: Revealed type is "builtins.dict[Any, Any]"
3220
3221 [file a.py]
3222 from b import x, y
3223 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3224 reveal_type(y) # N: Revealed type is "builtins.dict[Any, Any]"
3225
3226 [builtins fixtures/dict.pyi]
3227
3228 [case testPermissiveGlobalContainer2]
3229 # flags: --allow-untyped-globals
3230
3231 import a
3232
3233 [file b.py]
3234 x = []
3235 y = {}
3236
3237 def foo() -> None:
3238 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3239 reveal_type(y) # N: Revealed type is "builtins.dict[Any, Any]"
3240
3241 [file a.py]
3242 from b import x, y
3243 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3244 reveal_type(y) # N: Revealed type is "builtins.dict[Any, Any]"
3245
3246 [builtins fixtures/dict.pyi]
3247
3248 [case testPermissiveGlobalContainer3]
3249 # flags: --allow-untyped-globals --local-partial-types
3250
3251 import a
3252
3253 [file b.py]
3254 x = []
3255 y = {}
3256 z = y
3257
3258
3259 [file a.py]
3260 from b import x, y
3261 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3262 reveal_type(y) # N: Revealed type is "builtins.dict[Any, Any]"
3263
3264 [builtins fixtures/dict.pyi]
3265 [case testPermissiveGlobalContainer4]
3266 # flags: --allow-untyped-globals
3267
3268 import a
3269
3270 [file b.py]
3271 x = []
3272 y = {}
3273 z = y
3274
3275
3276 [file a.py]
3277 from b import x, y
3278 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3279 reveal_type(y) # N: Revealed type is "builtins.dict[Any, Any]"
3280
3281 [builtins fixtures/dict.pyi]
3282
3283 [case testInheritedAttributeNoStrictOptional]
3284 # flags: --no-strict-optional
3285 class A:
3286 x: str
3287
3288 class B(A):
3289 x = None
3290 x = ''
3291 reveal_type(x) # N: Revealed type is "builtins.str"
3292
3293 [case testIncompatibleInheritedAttributeNoStrictOptional]
3294 # flags: --no-strict-optional
3295 class A:
3296 x: str
3297
3298 class B(A):
3299 x = None
3300 x = 2 # E: Incompatible types in assignment (expression has type "int", base class "A" defined the type as "str")
3301
3302 [case testInheritedAttributeStrictOptional]
3303 class A:
3304 x: str
3305
3306 class B(A):
3307 x = None # E: Incompatible types in assignment (expression has type "None", base class "A" defined the type as "str")
3308 x = ''
3309
3310 [case testNeedAnnotationForCallable]
3311 from typing import TypeVar, Optional, Callable
3312
3313 T = TypeVar('T')
3314
3315 def f(x: Optional[T] = None) -> Callable[..., T]: ...
3316
3317 x = f() # E: Need type annotation for "x"
3318 y = x
3319
3320 [case testDontNeedAnnotationForCallable]
3321 from typing import TypeVar, Optional, Callable, NoReturn
3322
3323 T = TypeVar('T')
3324
3325 def f() -> Callable[..., NoReturn]: ...
3326
3327 x = f()
3328 reveal_type(x) # N: Revealed type is "def (*Any, **Any) -> Never"
3329
3330 [case testDeferralInNestedScopes]
3331
3332
3333 def g() -> None:
3334 def f() -> None:
3335 x + 'no way' # E: Unsupported operand types for + ("int" and "str")
3336 x = int()
3337 f()
3338
3339 [case testDeferralOfMemberNested]
3340 from typing import Tuple
3341
3342 def f() -> None:
3343 c: C
3344 t: Tuple[str, Tuple[str, str]]
3345 x, (y, c.a) = t # E: Incompatible types in assignment (expression has type "str", variable has type "int")
3346
3347 class C:
3348 def __init__(self, a: int) -> None:
3349 self.a = a
3350 [builtins fixtures/tuple.pyi]
3351
3352 [case testUnionGenericWithBoundedVariable]
3353 from typing import Generic, TypeVar, Union
3354
3355 class A: ...
3356 class B(A): ...
3357
3358 T = TypeVar('T', bound=A)
3359 class Z(Generic[T]):
3360 def __init__(self, y: T) -> None:
3361 self.y = y
3362
3363 F = TypeVar('F', bound=A)
3364
3365 def q1(x: Union[F, Z[F]]) -> F:
3366 if isinstance(x, Z):
3367 return x.y
3368 else:
3369 return x
3370
3371 def q2(x: Union[Z[F], F]) -> F:
3372 if isinstance(x, Z):
3373 return x.y
3374 else:
3375 return x
3376
3377 b: B
3378 reveal_type(q1(b)) # N: Revealed type is "__main__.B"
3379 reveal_type(q2(b)) # N: Revealed type is "__main__.B"
3380
3381 z: Z[B]
3382 reveal_type(q1(z)) # N: Revealed type is "__main__.B"
3383 reveal_type(q2(z)) # N: Revealed type is "__main__.B"
3384
3385 reveal_type(q1(Z(b))) # N: Revealed type is "__main__.B"
3386 reveal_type(q2(Z(b))) # N: Revealed type is "__main__.B"
3387 [builtins fixtures/isinstancelist.pyi]
3388
3389 [case testUnionInvariantSubClassAndCovariantBase]
3390 from typing import Union, Generic, TypeVar
3391
3392 T = TypeVar('T')
3393 T_co = TypeVar('T_co', covariant=True)
3394
3395 class Cov(Generic[T_co]): ...
3396 class Inv(Cov[T]): ...
3397
3398 X = Union[Cov[T], Inv[T]]
3399
3400 def f(x: X[T]) -> T: ...
3401 x: Inv[int]
3402 reveal_type(f(x)) # N: Revealed type is "builtins.int"
3403
3404 [case testOptionalTypeVarAgainstOptional]
3405 from typing import Optional, TypeVar, Iterable, Iterator, List
3406
3407 _T = TypeVar('_T')
3408
3409 def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> List[_T]: ...
3410
3411 x: Optional[str]
3412
3413 y = filter(None, [x])
3414 reveal_type(y) # N: Revealed type is "builtins.list[builtins.str]"
3415 [builtins fixtures/list.pyi]
3416
3417 [case testPartialDefaultDict]
3418 from collections import defaultdict
3419 x = defaultdict(int)
3420 x[''] = 1
3421 reveal_type(x) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.int]"
3422
3423 y = defaultdict(int) # E: Need type annotation for "y"
3424
3425 z = defaultdict(int) # E: Need type annotation for "z"
3426 z[''] = ''
3427 reveal_type(z) # N: Revealed type is "collections.defaultdict[Any, Any]"
3428 [builtins fixtures/dict.pyi]
3429
3430 [case testPartialDefaultDictInconsistentValueTypes]
3431 from collections import defaultdict
3432 a = defaultdict(int) # E: Need type annotation for "a"
3433 a[''] = ''
3434 a[''] = 1
3435 reveal_type(a) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.int]"
3436 [builtins fixtures/dict.pyi]
3437
3438 [case testPartialDefaultDictListValue]
3439 # flags: --no-strict-optional
3440 from collections import defaultdict
3441 a = defaultdict(list)
3442 a['x'].append(1)
3443 reveal_type(a) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
3444
3445 b = defaultdict(lambda: [])
3446 b[1].append('x')
3447 reveal_type(b) # N: Revealed type is "collections.defaultdict[builtins.int, builtins.list[builtins.str]]"
3448 [builtins fixtures/dict.pyi]
3449
3450 [case testPartialDefaultDictListValueStrictOptional]
3451 from collections import defaultdict
3452 a = defaultdict(list)
3453 a['x'].append(1)
3454 reveal_type(a) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
3455
3456 b = defaultdict(lambda: [])
3457 b[1].append('x')
3458 reveal_type(b) # N: Revealed type is "collections.defaultdict[builtins.int, builtins.list[builtins.str]]"
3459 [builtins fixtures/dict.pyi]
3460
3461 [case testPartialDefaultDictSpecialCases]
3462 from collections import defaultdict
3463 class A:
3464 def f(self) -> None:
3465 self.x = defaultdict(list)
3466 self.x['x'].append(1)
3467 reveal_type(self.x) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
3468 self.y = defaultdict(list) # E: Need type annotation for "y"
3469 s = self
3470 s.y['x'].append(1)
3471
3472 x = {} # E: Need type annotation for "x" (hint: "x: dict[<type>, <type>] = ...")
3473 x['x'].append(1)
3474
3475 y = defaultdict(list) # E: Need type annotation for "y"
3476 y[[]].append(1)
3477 [builtins fixtures/dict.pyi]
3478
3479 [case testPartialDefaultDictSpecialCases2]
3480 from collections import defaultdict
3481
3482 x = defaultdict(lambda: [1]) # E: Need type annotation for "x"
3483 x[1].append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
3484 reveal_type(x) # N: Revealed type is "collections.defaultdict[Any, builtins.list[builtins.int]]"
3485
3486 xx = defaultdict(lambda: {'x': 1}) # E: Need type annotation for "xx"
3487 xx[1]['z'] = 3
3488 reveal_type(xx) # N: Revealed type is "collections.defaultdict[Any, builtins.dict[builtins.str, builtins.int]]"
3489
3490 y = defaultdict(dict) # E: Need type annotation for "y"
3491 y['x'][1] = [3]
3492
3493 z = defaultdict(int) # E: Need type annotation for "z"
3494 z[1].append('')
3495 reveal_type(z) # N: Revealed type is "collections.defaultdict[Any, Any]"
3496 [builtins fixtures/dict.pyi]
3497
3498 [case testPartialDefaultDictSpecialCase3]
3499 from collections import defaultdict
3500
3501 x = defaultdict(list)
3502 x['a'] = [1, 2, 3]
3503 reveal_type(x) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
3504
3505 y = defaultdict(list) # E: Need type annotation for "y"
3506 y['a'] = []
3507 reveal_type(y) # N: Revealed type is "collections.defaultdict[Any, Any]"
3508 [builtins fixtures/dict.pyi]
3509
3510 [case testInferCallableReturningNone1]
3511 # flags: --no-strict-optional
3512 from typing import Callable, TypeVar
3513
3514 T = TypeVar("T")
3515
3516 def f(x: Callable[[], T]) -> T:
3517 return x()
3518
3519 reveal_type(f(lambda: None)) # N: Revealed type is "None"
3520 reveal_type(f(lambda: 1)) # N: Revealed type is "builtins.int"
3521
3522 def g() -> None: pass
3523
3524 reveal_type(f(g)) # N: Revealed type is "None"
3525
3526 [case testInferCallableReturningNone2]
3527 from typing import Callable, TypeVar
3528
3529 T = TypeVar("T")
3530
3531 def f(x: Callable[[], T]) -> T:
3532 return x()
3533
3534 reveal_type(f(lambda: None)) # N: Revealed type is "None"
3535 reveal_type(f(lambda: 1)) # N: Revealed type is "builtins.int"
3536
3537 def g() -> None: pass
3538
3539 reveal_type(f(g)) # N: Revealed type is "None"
3540
3541 [case testInferredTypeIsSimpleNestedList]
3542 from typing import Any, Union, List
3543
3544 y: Union[List[Any], Any]
3545 x: Union[List[Any], Any]
3546 x = [y]
3547 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3548 [builtins fixtures/list.pyi]
3549
3550 [case testInferredTypeIsSimpleNestedIterable]
3551 from typing import Any, Union, Iterable
3552
3553 y: Union[Iterable[Any], Any]
3554 x: Union[Iterable[Any], Any]
3555 x = [y]
3556 reveal_type(x) # N: Revealed type is "builtins.list[Any]"
3557 [builtins fixtures/list.pyi]
3558
3559 [case testInferredTypeIsSimpleNestedListLoop]
3560 from typing import Any, Union, List
3561
3562 def test(seq: List[Union[List, Any]]) -> None:
3563 k: Union[List, Any]
3564 for k in seq:
3565 if bool():
3566 k = [k]
3567 reveal_type(k) # N: Revealed type is "builtins.list[Any]"
3568 [builtins fixtures/list.pyi]
3569
3570 [case testInferredTypeIsSimpleNestedIterableLoop]
3571 from typing import Any, Union, List, Iterable
3572
3573 def test(seq: List[Union[Iterable, Any]]) -> None:
3574 k: Union[Iterable, Any]
3575 for k in seq:
3576 if bool():
3577 k = [k]
3578 reveal_type(k) # N: Revealed type is "builtins.list[Any]"
3579 [builtins fixtures/list.pyi]
3580
3581 [case testErasedTypeRuntimeCoverage]
3582 # https://github.com/python/mypy/issues/11913
3583 from typing import TypeVar, Type, Generic, Callable, Iterable
3584
3585 class DataType: ...
3586
3587 T1 = TypeVar('T1')
3588 T2 = TypeVar("T2", bound=DataType)
3589
3590 def map(__func: T1) -> None: ...
3591
3592 def collection_from_dict_value(model: Type[T2]) -> None:
3593 map(lambda i: i if isinstance(i, model) else i)
3594 [builtins fixtures/isinstancelist.pyi]
3595
3596 [case testRegression11705_Strict]
3597 # See: https://github.com/python/mypy/issues/11705
3598 from typing import Dict, Optional, NamedTuple
3599 class C(NamedTuple):
3600 x: int
3601
3602 t: Optional[C]
3603 d: Dict[C, bytes]
3604 x = t and d[t]
3605 reveal_type(x) # N: Revealed type is "None | builtins.bytes"
3606 if x:
3607 reveal_type(x) # N: Revealed type is "builtins.bytes"
3608 [builtins fixtures/dict.pyi]
3609
3610 [case testRegression11705_NoStrict]
3611 # flags: --no-strict-optional
3612 # See: https://github.com/python/mypy/issues/11705
3613 from typing import Dict, Optional, NamedTuple
3614 class C(NamedTuple):
3615 x: int
3616
3617 t: Optional[C]
3618 d: Dict[C, bytes]
3619 x = t and d[t]
3620 reveal_type(x) # N: Revealed type is "builtins.bytes"
3621 if x:
3622 reveal_type(x) # N: Revealed type is "builtins.bytes"
3623 [builtins fixtures/dict.pyi]
3624
3625 [case testAllowPlainNoneForPartialAtModuleScope]
3626 # flags: --local-partial-types
3627 x = None
3628 reveal_type(x) # N: Revealed type is "None"
3629
3630 [case testTupleContextFromIterable]
3631 from typing import TypeVar, Iterable, List, Union
3632
3633 T = TypeVar("T")
3634
3635 def foo(x: List[T]) -> List[T]: ...
3636 x: Iterable[List[Union[int, str]]] = (foo([1]), foo(["a"]))
3637 [builtins fixtures/tuple.pyi]
3638
3639 [case testTupleContextFromIterable2]
3640 from typing import Dict, Iterable, Tuple, Union
3641
3642 def foo(x: Union[Tuple[str, Dict[str, int], str], Iterable[object]]) -> None: ...
3643 foo(("a", {"a": "b"}, "b"))
3644 [builtins fixtures/dict.pyi]
3645
3646 [case testUseSupertypeAsInferenceContext]
3647 from typing import List, Optional
3648
3649 class B:
3650 x: List[Optional[int]]
3651
3652 class C(B):
3653 x = [1]
3654
3655 reveal_type(C().x) # N: Revealed type is "builtins.list[builtins.int | None]"
3656 [builtins fixtures/list.pyi]
3657
3658 [case testUseSupertypeAsInferenceContextInvalidType]
3659 from typing import List
3660 class P:
3661 x: List[int]
3662 class C(P):
3663 x = ['a'] # E: List item 0 has incompatible type "str"; expected "int"
3664 [builtins fixtures/list.pyi]
3665
3666 [case testUseSupertypeAsInferenceContextPartial]
3667 from typing import List
3668
3669 class A:
3670 x: List[str]
3671
3672 class B(A):
3673 x = []
3674
3675 reveal_type(B().x) # N: Revealed type is "builtins.list[builtins.str]"
3676 [builtins fixtures/list.pyi]
3677
3678 [case testUseSupertypeAsInferenceContextPartialError]
3679 class A:
3680 x = ['a', 'b']
3681
3682 class B(A):
3683 x = []
3684 x.append(2) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
3685 [builtins fixtures/list.pyi]
3686
3687 [case testUseSupertypeAsInferenceContextPartialErrorProperty]
3688 from typing import List
3689
3690 class P:
3691 @property
3692 def x(self) -> List[int]: ...
3693 class C(P):
3694 x = []
3695
3696 C.x.append("no") # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
3697 [builtins fixtures/list.pyi]
3698
3699 [case testUseSupertypeAsInferenceContextConflict]
3700 from typing import List
3701 class P:
3702 x: List[int]
3703 class M:
3704 x: List[str]
3705 class C(P, M):
3706 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
3707 reveal_type(C.x) # N: Revealed type is "builtins.list[Any]"
3708 [builtins fixtures/list.pyi]
3709
3710 [case testNoPartialInSupertypeAsContext]
3711 class A:
3712 args = {} # E: Need type annotation for "args" (hint: "args: dict[<type>, <type>] = ...")
3713 def f(self) -> None:
3714 value = {1: "Hello"}
3715 class B(A):
3716 args = value
3717 [builtins fixtures/dict.pyi]
3718
3719 [case testInferSimpleLiteralInClassBodyCycle]
3720 import a
3721 [file a.py]
3722 import b
3723 reveal_type(b.B.x) # N: Revealed type is "builtins.int"
3724 class A:
3725 x = 42
3726 [file b.py]
3727 import a
3728 reveal_type(a.A.x) # N: Revealed type is "builtins.int"
3729 class B:
3730 x = 42
3731
3732 [case testUnionTypeCallableInference]
3733 from typing import Callable, Type, TypeVar, Union
3734
3735 class A:
3736 def __init__(self, x: str) -> None: ...
3737
3738 T = TypeVar("T")
3739 def type_or_callable(value: T, tp: Union[Type[T], Callable[[int], T]]) -> T: ...
3740 reveal_type(type_or_callable(A("test"), A)) # N: Revealed type is "__main__.A"
3741
3742 [case testUpperBoundAsInferenceFallback]
3743 from typing import Callable, TypeVar, Any, Mapping, Optional
3744 T = TypeVar("T", bound=Mapping[str, Any])
3745 def raises(opts: Optional[T]) -> T: pass
3746 def assertRaises(cb: Callable[..., object]) -> None: pass
3747 assertRaises(raises) # OK
3748 [builtins fixtures/dict.pyi]
3749
3750 [case testJoinWithAnyFallback]
3751 from unknown import X # type: ignore[import]
3752
3753 class A: ...
3754 class B(X, A): ...
3755 class C(B): ...
3756 class D(C): ...
3757 class E(D): ...
3758
3759 reveal_type([E(), D()]) # N: Revealed type is "builtins.list[__main__.D]"
3760 reveal_type([D(), E()]) # N: Revealed type is "builtins.list[__main__.D]"
3761
3762 [case testCallableInferenceAgainstCallablePosVsStar]
3763 from typing import TypeVar, Callable, Tuple
3764
3765 T = TypeVar('T')
3766 S = TypeVar('S')
3767
3768 def f(x: Callable[[T, S], None]) -> Tuple[T, S]: ...
3769 def g(*x: int) -> None: ...
3770 reveal_type(f(g)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
3771 [builtins fixtures/list.pyi]
3772
3773 [case testCallableInferenceAgainstCallableStarVsPos]
3774 from typing import TypeVar, Callable, Tuple, Protocol
3775
3776 T = TypeVar('T', contravariant=True)
3777 S = TypeVar('S', contravariant=True)
3778
3779 class Call(Protocol[T, S]):
3780 def __call__(self, __x: T, *args: S) -> None: ...
3781
3782 def f(x: Call[T, S]) -> Tuple[T, S]: ...
3783 def g(*x: int) -> None: ...
3784 reveal_type(f(g)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
3785 [builtins fixtures/list.pyi]
3786
3787 [case testCallableInferenceAgainstCallableNamedVsStar]
3788 from typing import TypeVar, Callable, Tuple, Protocol
3789
3790 T = TypeVar('T', contravariant=True)
3791 S = TypeVar('S', contravariant=True)
3792
3793 class Call(Protocol[T, S]):
3794 def __call__(self, *, x: T, y: S) -> None: ...
3795
3796 def f(x: Call[T, S]) -> Tuple[T, S]: ...
3797 def g(**kwargs: int) -> None: ...
3798 reveal_type(f(g)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
3799 [builtins fixtures/list.pyi]
3800
3801 [case testCallableInferenceAgainstCallableStarVsNamed]
3802 from typing import TypeVar, Callable, Tuple, Protocol
3803
3804 T = TypeVar('T', contravariant=True)
3805 S = TypeVar('S', contravariant=True)
3806
3807 class Call(Protocol[T, S]):
3808 def __call__(self, *, x: T, **kwargs: S) -> None: ...
3809
3810 def f(x: Call[T, S]) -> Tuple[T, S]: ...
3811 def g(**kwargs: int) -> None: pass
3812 reveal_type(f(g)) # N: Revealed type is "tuple[builtins.int, builtins.int]"
3813 [builtins fixtures/list.pyi]
3814
3815 [case testCallableInferenceAgainstCallableNamedVsNamed]
3816 from typing import TypeVar, Callable, Tuple, Protocol
3817
3818 T = TypeVar('T', contravariant=True)
3819 S = TypeVar('S', contravariant=True)
3820
3821 class Call(Protocol[T, S]):
3822 def __call__(self, *, x: T, y: S) -> None: ...
3823
3824 def f(x: Call[T, S]) -> Tuple[T, S]: ...
3825
3826 # Note: order of names is different w.r.t. protocol
3827 def g(*, y: int, x: str) -> None: pass
3828 reveal_type(f(g)) # N: Revealed type is "tuple[builtins.str, builtins.int]"
3829 [builtins fixtures/list.pyi]
3830
3831 [case testCallableInferenceAgainstCallablePosOnlyVsNamed]
3832 from typing import TypeVar, Callable, Tuple, Protocol
3833
3834 T = TypeVar('T', contravariant=True)
3835 S = TypeVar('S', contravariant=True)
3836
3837 class Call(Protocol[T]):
3838 def __call__(self, *, x: T) -> None: ...
3839
3840 def f(x: Call[T]) -> Tuple[T, T]: ...
3841
3842 def g(__x: str) -> None: pass
3843 reveal_type(f(g)) # N: Revealed type is "tuple[Never, Never]" \
3844 # E: Argument 1 to "f" has incompatible type "Callable[[str], None]"; expected "Call[Never]" \
3845 # N: "Call[Never].__call__" has type "def __call__(self, *, x: Never) -> None"
3846 [builtins fixtures/list.pyi]
3847
3848 [case testCallableInferenceAgainstCallableNamedVsPosOnly]
3849 from typing import TypeVar, Callable, Tuple, Protocol
3850
3851 T = TypeVar('T', contravariant=True)
3852 S = TypeVar('S', contravariant=True)
3853
3854 class Call(Protocol[T]):
3855 def __call__(self, __x: T) -> None: ...
3856
3857 def f(x: Call[T]) -> Tuple[T, T]: ...
3858
3859 def g(*, x: str) -> None: pass
3860 reveal_type(f(g)) # N: Revealed type is "tuple[Never, Never]" \
3861 # E: Argument 1 to "f" has incompatible type "def g(*, x: str) -> None"; expected "Call[Never]" \
3862 # N: "Call[Never].__call__" has type "Callable[[Never], None]"
3863 [builtins fixtures/list.pyi]
3864
3865 [case testCallableInferenceAgainstCallablePosOnlyVsKwargs]
3866 from typing import TypeVar, Callable, Tuple, Protocol
3867
3868 T = TypeVar('T', contravariant=True)
3869 S = TypeVar('S', contravariant=True)
3870
3871 class Call(Protocol[T]):
3872 def __call__(self, __x: T) -> None: ...
3873
3874 def f(x: Call[T]) -> Tuple[T, T]: ...
3875
3876 def g(**x: str) -> None: pass
3877 reveal_type(f(g)) # N: Revealed type is "tuple[Never, Never]" \
3878 # E: Argument 1 to "f" has incompatible type "def g(**x: str) -> None"; expected "Call[Never]" \
3879 # N: "Call[Never].__call__" has type "Callable[[Never], None]"
3880 [builtins fixtures/list.pyi]
3881
3882 [case testCallableInferenceAgainstCallableNamedVsArgs]
3883 from typing import TypeVar, Callable, Tuple, Protocol
3884
3885 T = TypeVar('T', contravariant=True)
3886 S = TypeVar('S', contravariant=True)
3887
3888 class Call(Protocol[T]):
3889 def __call__(self, *, x: T) -> None: ...
3890
3891 def f(x: Call[T]) -> Tuple[T, T]: ...
3892
3893 def g(*args: str) -> None: pass
3894 reveal_type(f(g)) # N: Revealed type is "tuple[Never, Never]" \
3895 # E: Argument 1 to "f" has incompatible type "def g(*args: str) -> None"; expected "Call[Never]" \
3896 # N: "Call[Never].__call__" has type "def __call__(self, *, x: Never) -> None"
3897 [builtins fixtures/list.pyi]
3898
3899 [case testInferenceAgainstTypeVarActualBound]
3900 from typing import Callable, TypeVar
3901
3902 T = TypeVar("T")
3903 S = TypeVar("S")
3904 def test(f: Callable[[T], S]) -> Callable[[T], S]: ...
3905
3906 F = TypeVar("F", bound=Callable[..., object])
3907 def dec(f: F) -> F:
3908 reveal_type(test(f)) # N: Revealed type is "def (Any) -> builtins.object"
3909 return f
3910
3911 [case testInferenceAgainstTypeVarActualUnionBound]
3912 from typing import Protocol, TypeVar, Union
3913
3914 T_co = TypeVar("T_co", covariant=True)
3915 class SupportsFoo(Protocol[T_co]):
3916 def foo(self) -> T_co: ...
3917
3918 class A:
3919 def foo(self) -> A: ...
3920 class B:
3921 def foo(self) -> B: ...
3922
3923 def foo(f: SupportsFoo[T_co]) -> T_co: ...
3924
3925 ABT = TypeVar("ABT", bound=Union[A, B])
3926 def simpler(k: ABT):
3927 foo(k)
3928
3929 [case testInferenceWorksWithEmptyCollectionsNested]
3930 from typing import List, TypeVar, NoReturn
3931 T = TypeVar('T')
3932 def f(a: List[T], b: List[T]) -> T: pass
3933 x = ["yes"]
3934 reveal_type(f(x, [])) # N: Revealed type is "builtins.str"
3935 reveal_type(f(["yes"], [])) # N: Revealed type is "builtins.str"
3936
3937 empty: List[NoReturn]
3938 f(x, empty) # E: Cannot infer value of type parameter "T" of "f"
3939 f(["no"], empty) # E: Cannot infer value of type parameter "T" of "f"
3940 [builtins fixtures/list.pyi]
3941
3942 [case testInferenceWorksWithEmptyCollectionsUnion]
3943 from typing import Any, Dict, NoReturn, NoReturn, Union
3944
3945 def foo() -> Union[Dict[str, Any], Dict[int, Any]]:
3946 return {}
3947 [builtins fixtures/dict.pyi]
3948
3949 [case testExistingEmptyCollectionDoesNotUpcast]
3950 from typing import Any, Dict, NoReturn, NoReturn, Union
3951
3952 empty: Dict[NoReturn, NoReturn]
3953
3954 def foo() -> Dict[str, Any]:
3955 return empty # E: Incompatible return value type (got "dict[Never, Never]", expected "dict[str, Any]")
3956
3957 def bar() -> Union[Dict[str, Any], Dict[int, Any]]:
3958 return empty # E: Incompatible return value type (got "dict[Never, Never]", expected "dict[str, Any] | dict[int, Any]")
3959 [builtins fixtures/dict.pyi]
3960
3961 [case testUpperBoundInferenceFallbackNotOverused]
3962 from typing import TypeVar, Protocol, List
3963
3964 S = TypeVar("S", covariant=True)
3965 class Foo(Protocol[S]):
3966 def foo(self) -> S: ...
3967 def foo(x: Foo[S]) -> S: ...
3968
3969 T = TypeVar("T", bound="Base")
3970 class Base:
3971 def foo(self: T) -> T: ...
3972 class C(Base):
3973 pass
3974
3975 def f(values: List[T]) -> T: ...
3976 x = foo(f([C()]))
3977 reveal_type(x) # N: Revealed type is "__main__.C"
3978 [builtins fixtures/list.pyi]
3979
3980 [case testInferenceAgainstGenericCallableUnion]
3981 from typing import Callable, TypeVar, List, Union
3982
3983 T = TypeVar("T")
3984 S = TypeVar("S")
3985
3986 def dec(f: Callable[[S], T]) -> Callable[[S], List[T]]: ...
3987 @dec
3988 def func(arg: T) -> Union[T, str]:
3989 ...
3990 reveal_type(func) # N: Revealed type is "def [S] (S`1) -> builtins.list[S`1 | builtins.str]"
3991 reveal_type(func(42)) # N: Revealed type is "builtins.list[builtins.int | builtins.str]"
3992
3993 def dec2(f: Callable[[S], List[T]]) -> Callable[[S], T]: ...
3994 @dec2
3995 def func2(arg: T) -> List[Union[T, str]]:
3996 ...
3997 reveal_type(func2) # N: Revealed type is "def [S] (S`4) -> S`4 | builtins.str"
3998 reveal_type(func2(42)) # N: Revealed type is "builtins.int | builtins.str"
3999 [builtins fixtures/list.pyi]
4000
4001 [case testInferenceAgainstGenericCallbackProtoMultiple]
4002 from typing import Callable, Protocol, TypeVar
4003 from typing_extensions import Concatenate, ParamSpec
4004
4005 V_co = TypeVar("V_co", covariant=True)
4006 class Metric(Protocol[V_co]):
4007 def __call__(self) -> V_co: ...
4008
4009 T = TypeVar("T")
4010 P = ParamSpec("P")
4011 def simple_metric(func: Callable[Concatenate[int, P], T]) -> Callable[P, T]: ...
4012
4013 @simple_metric
4014 def Negate(count: int, /, metric: Metric[float]) -> float: ...
4015 @simple_metric
4016 def Combine(count: int, m1: Metric[T], m2: Metric[T], /, *more: Metric[T]) -> T: ...
4017
4018 reveal_type(Negate) # N: Revealed type is "def (metric: __main__.Metric[builtins.float]) -> builtins.float"
4019 reveal_type(Combine) # N: Revealed type is "def [T] (def () -> T`5, def () -> T`5, *more: def () -> T`5) -> T`5"
4020
4021 def m1() -> float: ...
4022 def m2() -> float: ...
4023 reveal_type(Combine(m1, m2)) # N: Revealed type is "builtins.float"
4024 [builtins fixtures/list.pyi]
4025
4026 [case testInferenceWithUninhabitedType]
4027 from typing import Dict, Generic, List, Never, TypeVar
4028
4029 T = TypeVar("T")
4030
4031 class A(Generic[T]): ...
4032 class B(Dict[T, T]): ...
4033
4034 def func1(a: A[T], b: T) -> T: ...
4035 def func2(a: T, b: A[T]) -> T: ...
4036
4037 def a1(a: A[Dict[str, int]]) -> None:
4038 reveal_type(func1(a, {})) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
4039 reveal_type(func2({}, a)) # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
4040
4041 def a2(check: bool, a: B[str]) -> None:
4042 reveal_type(a if check else {}) # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"
4043
4044 def a3() -> None:
4045 a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
4046 b = {1: {}} # E: Need type annotation for "b"
4047 c = {1: {}, 2: {"key": {}}} # E: Need type annotation for "c"
4048 reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]"
4049 reveal_type(b) # N: Revealed type is "builtins.dict[builtins.int, builtins.dict[Any, Any]]"
4050 reveal_type(c) # N: Revealed type is "builtins.dict[builtins.int, builtins.dict[builtins.str, builtins.dict[Any, Any]]]"
4051
4052 def a4(x: List[str], y: List[Never]) -> None:
4053 z1 = [x, y]
4054 z2 = [y, x]
4055 reveal_type(z1) # N: Revealed type is "builtins.list[builtins.object]"
4056 reveal_type(z2) # N: Revealed type is "builtins.list[builtins.object]"
4057 z1[1].append("asdf") # E: "object" has no attribute "append"
4058 [builtins fixtures/dict.pyi]
4059
4060
4061 [case testDeterminismCommutativityWithJoinInvolvingProtocolBaseAndPromotableType]
4062 # flags: --python-version 3.11
4063 # Regression test for https://github.com/python/mypy/issues/16979#issuecomment-1982246306
4064 from __future__ import annotations
4065
4066 from typing import Any, Generic, Protocol, TypeVar, overload, cast
4067 from typing_extensions import Never
4068
4069 T = TypeVar("T")
4070 U = TypeVar("U")
4071
4072 class _SupportsCompare(Protocol):
4073 def __lt__(self, other: Any, /) -> bool:
4074 return True
4075
4076 class Comparable(_SupportsCompare):
4077 pass
4078
4079 comparable: Comparable = Comparable()
4080
4081 from typing import _promote
4082
4083 class floatlike:
4084 def __lt__(self, other: floatlike, /) -> bool: ...
4085
4086 @_promote(floatlike)
4087 class intlike:
4088 def __lt__(self, other: intlike, /) -> bool: ...
4089
4090
4091 class A(Generic[T, U]):
4092 @overload
4093 def __init__(self: A[T, T], a: T, b: T, /) -> None: ... # type: ignore[overload-overlap]
4094 @overload
4095 def __init__(self: A[T, U], a: T, b: U, /) -> Never: ...
4096 def __init__(self, *a) -> None: ...
4097
4098 def join(a: T, b: T) -> T: ...
4099
4100 reveal_type(join(intlike(), comparable)) # N: Revealed type is "__main__._SupportsCompare"
4101 reveal_type(join(comparable, intlike())) # N: Revealed type is "__main__._SupportsCompare"
4102 reveal_type(A(intlike(), comparable)) # N: Revealed type is "__main__.A[__main__._SupportsCompare, __main__._SupportsCompare]"
4103 reveal_type(A(comparable, intlike())) # N: Revealed type is "__main__.A[__main__._SupportsCompare, __main__._SupportsCompare]"
4104 [builtins fixtures/tuple.pyi]
4105 [typing fixtures/typing-medium.pyi]
4106
4107 [case testTupleJoinFallbackInference]
4108 foo = [
4109 (1, ("a", "b")),
4110 (2, []),
4111 ]
4112 reveal_type(foo) # N: Revealed type is "builtins.list[tuple[builtins.int, typing.Sequence[builtins.str]]]"
4113 [builtins fixtures/tuple.pyi]
4114
4115 [case testForLoopIndexVaribaleNarrowing1]
4116 # flags: --local-partial-types
4117 from typing import Union
4118 x: Union[int, str]
4119 x = "abc"
4120 for x in list[int]():
4121 reveal_type(x) # N: Revealed type is "builtins.int"
4122 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
4123
4124 [case testForLoopIndexVaribaleNarrowing2]
4125 # flags: --enable-error-code=redundant-expr
4126 from typing import Union
4127 x: Union[int, str]
4128 x = "abc"
4129 for x in list[int]():
4130 reveal_type(x) # N: Revealed type is "builtins.int"
4131 reveal_type(x) # N: Revealed type is "builtins.int | builtins.str"
4132
4133 [case testNarrowInFunctionDefer]
4134 from typing import Optional, Callable, TypeVar
4135
4136 def top() -> None:
4137 x: Optional[int]
4138 assert x is not None
4139
4140 def foo() -> None:
4141 defer()
4142 reveal_type(x) # N: Revealed type is "builtins.int"
4143
4144 T = TypeVar("T")
4145 def deco(fn: Callable[[], T]) -> Callable[[], T]: ...
4146
4147 @deco
4148 def defer() -> int: ...
4149
4150 [case testDeferMethodOfNestedClass]
4151 from typing import Optional, Callable, TypeVar
4152
4153 class Out:
4154 def meth(self) -> None:
4155 class In:
4156 def meth(self) -> None:
4157 reveal_type(defer()) # N: Revealed type is "builtins.int"
4158
4159 T = TypeVar("T")
4160 def deco(fn: Callable[[], T]) -> Callable[[], T]: ...
4161
4162 @deco
4163 def defer() -> int: ...
4164
4165 [case testVariableDeferredWithNestedFunction]
4166 from typing import Callable, TypeVar
4167
4168 T = TypeVar("T")
4169 def deco(fn: Callable[[], T]) -> Callable[[], T]: ...
4170
4171 @deco
4172 def f() -> None:
4173 x = 1
4174 f() # defer current node
4175 x = x
4176
4177 def nested() -> None:
4178 ...
4179
4180 # The type below should not be Any.
4181 reveal_type(x) # N: Revealed type is "builtins.int"
4182
4183 [case testInferenceMappingTypeVarGet]
4184 from typing import Generic, TypeVar, Union
4185
4186 _T = TypeVar("_T")
4187 _K = TypeVar("_K")
4188 _V = TypeVar("_V")
4189
4190 class Mapping(Generic[_K, _V]):
4191 def get(self, key: _K, default: Union[_V, _T]) -> Union[_V, _T]: ...
4192
4193 def check(mapping: Mapping[str, _T]) -> None:
4194 ok1 = mapping.get("", "")
4195 reveal_type(ok1) # N: Revealed type is "_T`-1 | builtins.str"
4196 ok2: Union[_T, str] = mapping.get("", "")
4197 [builtins fixtures/tuple.pyi]
4198
4199 [case testInferWalrusAssignmentAttrInCondition]
4200 class Foo:
4201 def __init__(self, value: bool) -> None:
4202 self.value = value
4203
4204 def check_and(maybe: bool) -> None:
4205 foo = None
4206 if maybe and (foo := Foo(True)).value:
4207 reveal_type(foo) # N: Revealed type is "__main__.Foo"
4208 else:
4209 reveal_type(foo) # N: Revealed type is "__main__.Foo | None"
4210
4211 def check_and_nested(maybe: bool) -> None:
4212 foo = None
4213 bar = None
4214 baz = None
4215 if maybe and (foo := (bar := (baz := Foo(True)))).value:
4216 reveal_type(foo) # N: Revealed type is "__main__.Foo"
4217 reveal_type(bar) # N: Revealed type is "__main__.Foo"
4218 reveal_type(baz) # N: Revealed type is "__main__.Foo"
4219 else:
4220 reveal_type(foo) # N: Revealed type is "__main__.Foo | None"
4221 reveal_type(bar) # N: Revealed type is "__main__.Foo | None"
4222 reveal_type(baz) # N: Revealed type is "__main__.Foo | None"
4223
4224 def check_or(maybe: bool) -> None:
4225 foo = None
4226 if maybe or (foo := Foo(True)).value:
4227 reveal_type(foo) # N: Revealed type is "__main__.Foo | None"
4228 else:
4229 reveal_type(foo) # N: Revealed type is "__main__.Foo"
4230
4231 def check_or_nested(maybe: bool) -> None:
4232 foo = None
4233 bar = None
4234 baz = None
4235 if maybe and (foo := (bar := (baz := Foo(True)))).value:
4236 reveal_type(foo) # N: Revealed type is "__main__.Foo"
4237 reveal_type(bar) # N: Revealed type is "__main__.Foo"
4238 reveal_type(baz) # N: Revealed type is "__main__.Foo"
4239 else:
4240 reveal_type(foo) # N: Revealed type is "__main__.Foo | None"
4241 reveal_type(bar) # N: Revealed type is "__main__.Foo | None"
4242 reveal_type(baz) # N: Revealed type is "__main__.Foo | None"
4243
4244 [case testInferWalrusAssignmentIndexInCondition]
4245 def check_and(maybe: bool) -> None:
4246 foo = None
4247 bar = None
4248 if maybe and (foo := [1])[(bar := 0)]:
4249 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]"
4250 reveal_type(bar) # N: Revealed type is "builtins.int"
4251 else:
4252 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int] | None"
4253 reveal_type(bar) # N: Revealed type is "builtins.int | None"
4254
4255 def check_and_nested(maybe: bool) -> None:
4256 foo = None
4257 bar = None
4258 baz = None
4259 if maybe and (foo := (bar := (baz := [1])))[0]:
4260 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]"
4261 reveal_type(bar) # N: Revealed type is "builtins.list[builtins.int]"
4262 reveal_type(baz) # N: Revealed type is "builtins.list[builtins.int]"
4263 else:
4264 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int] | None"
4265 reveal_type(bar) # N: Revealed type is "builtins.list[builtins.int] | None"
4266 reveal_type(baz) # N: Revealed type is "builtins.list[builtins.int] | None"
4267
4268 def check_or(maybe: bool) -> None:
4269 foo = None
4270 bar = None
4271 if maybe or (foo := [1])[(bar := 0)]:
4272 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int] | None"
4273 reveal_type(bar) # N: Revealed type is "builtins.int | None"
4274 else:
4275 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]"
4276 reveal_type(bar) # N: Revealed type is "builtins.int"
4277
4278 def check_or_nested(maybe: bool) -> None:
4279 foo = None
4280 bar = None
4281 baz = None
4282 if maybe or (foo := (bar := (baz := [1])))[0]:
4283 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int] | None"
4284 reveal_type(bar) # N: Revealed type is "builtins.list[builtins.int] | None"
4285 reveal_type(baz) # N: Revealed type is "builtins.list[builtins.int] | None"
4286 else:
4287 reveal_type(foo) # N: Revealed type is "builtins.list[builtins.int]"
4288 reveal_type(bar) # N: Revealed type is "builtins.list[builtins.int]"
4289 reveal_type(baz) # N: Revealed type is "builtins.list[builtins.int]"
4290
4291 [case testInferOptionalAgainstAny]
4292 from typing import Any, Optional, TypeVar
4293
4294 a: Any
4295 oa: Optional[Any]
4296 T = TypeVar("T")
4297 def f(x: Optional[T]) -> T: ...
4298 reveal_type(f(a)) # N: Revealed type is "Any"
4299 reveal_type(f(oa)) # N: Revealed type is "Any"
4300
4301 [case testNoCrashOnPartialTypeAsContext]
4302 from typing import overload, TypeVar, Optional, Protocol
4303
4304 T = TypeVar("T")
4305 class DbManager(Protocol):
4306 @overload
4307 def get(self, key: str) -> Optional[T]:
4308 pass
4309
4310 @overload
4311 def get(self, key: str, default: T) -> T:
4312 pass
4313
4314 class Foo:
4315 def __init__(self, db: DbManager, bar: bool) -> None:
4316 if bar:
4317 self.qux = db.get("qux")
4318 else:
4319 self.qux = {} # E: Need type annotation for "qux" (hint: "qux: dict[<type>, <type>] = ...")
4320 [builtins fixtures/dict.pyi]
4321
4322 [case testConstraintSolvingFailureShowsCorrectArgument]
4323 from typing import Callable, TypeVar
4324
4325 T1 = TypeVar('T1')
4326 T2 = TypeVar('T2')
4327 def foo(
4328 a: T1,
4329 b: T2,
4330 c: Callable[[T2], T2],
4331 ) -> tuple[T1, T2]: ...
4332
4333 def bar(y: float) -> float: ...
4334
4335 foo(1, None, bar) # E: Cannot infer value of type parameter "T2" of "foo"
4336 [builtins fixtures/tuple.pyi]
4337
4338 [case testGlobalVariableNoneInitMultipleFuncs]
4339 x = None
4340
4341 def f() -> None:
4342 global x
4343 reveal_type(x) # N: Revealed type is "None"
4344 x = 1
4345 reveal_type(x) # N: Revealed type is "builtins.int"
4346
4347 def g() -> None:
4348 global x
4349 reveal_type(x) # N: Revealed type is "builtins.int | None"
4350 x = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int | None")
4351 reveal_type(x) # N: Revealed type is "builtins.int | None"
4352
4353 reveal_type(x) # N: Revealed type is "builtins.int | None"
4354
4355 [case testGlobalVariableNoneInitMultipleFuncsRedefine]
4356 # flags: --allow-redefinition
4357
4358 # Widening None is supported, as a special case
4359 x = None
4360
4361 def f() -> None:
4362 global x
4363 reveal_type(x) # N: Revealed type is "None"
4364 x = 1
4365 reveal_type(x) # N: Revealed type is "builtins.int"
4366
4367 def g() -> None:
4368 global x
4369 reveal_type(x) # N: Revealed type is "None | builtins.int"
4370 x = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int | None")
4371 reveal_type(x) # N: Revealed type is "None | builtins.int"
4372
4373 [case testLocalPartialTypesWithGlobalInitializedToEmptyListAndRedefine1]
4374 # flags: --allow-redefinition
4375 a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
4376
4377 def f() -> None:
4378 a.append(1)
4379
4380 reveal_type(a) # N: Revealed type is "builtins.list[Any]"
4381 [builtins fixtures/list.pyi]
4382
4383 [case testLocalPartialTypesWithGlobalInitializedToEmptyListAndRedefine2]
4384 # flags: --allow-redefinition
4385 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
4386
4387 # This used to crash.
4388 def f() -> None:
4389 global x
4390 x