Debian Codegraph @

test-data/unit/check-statements.test

raw
1 -- Return statement
2 -- ----------------
3
4
5 [case testReturnValue]
6 import typing
7 def f() -> 'A':
8 return A()
9 def g() -> 'B':
10 return A()
11 class A:
12 pass
13 class B:
14 pass
15 [out]
16 main:5: error: Incompatible return value type (got "A", expected "B")
17
18 [case testReturnSubtype]
19 import typing
20 def f() -> 'B':
21 return A()
22 def g() -> 'A':
23 return B()
24 class A:
25 pass
26 class B(A):
27 pass
28 [out]
29 main:3: error: Incompatible return value type (got "A", expected "B")
30
31 [case testReturnWithoutAValue]
32 import typing
33 def f() -> 'A':
34 return
35 def g() -> None:
36 return
37 class A:
38 pass
39 [out]
40 main:3: error: Return value expected
41
42 [case testReturnNoneInFunctionReturningNone]
43 import typing
44 def f() -> None:
45 return None
46 def g() -> None:
47 return f()
48 [out]
49
50 [case testReturnInGenerator]
51 from typing import Generator
52 def f() -> Generator[int, None, str]:
53 yield 1
54 return "foo"
55 [out]
56
57 [case testEmptyReturnInGenerator]
58 from typing import Generator
59 def f() -> Generator[int, None, str]:
60 yield 1
61 return # E: Return value expected
62 [out]
63
64 [case testNoReturnInGenerator]
65 from typing import Generator
66 def f() -> Generator[int, None, str]: # E: Missing return statement
67 yield 1
68 [out]
69
70 [case testEmptyReturnInNoneTypedGenerator]
71 from typing import Generator
72 def f() -> Generator[int, None, None]:
73 yield 1
74 return
75 [out]
76
77 [case testNonEmptyReturnInNoneTypedGenerator]
78 from typing import Generator
79 def f() -> Generator[int, None, None]:
80 yield 1
81 return 42 # E: No return value expected
82 [out]
83
84 [case testReturnInIterator]
85 from typing import Iterator
86 def f() -> Iterator[int]:
87 yield 1
88 return "foo" # E: No return value expected
89 [out]
90
91
92 -- If statement
93 -- ------------
94
95
96 [case testIfStatement]
97
98 a: A
99 a2: A
100 a3: A
101 b: bool
102 if a:
103 a = b # E: Incompatible types in assignment (expression has type "bool", variable has type "A")
104 elif a2:
105 a = b # E: Incompatible types in assignment (expression has type "bool", variable has type "A")
106 elif a3:
107 a = b # E: Incompatible types in assignment (expression has type "bool", variable has type "A")
108 else:
109 a = b # E: Incompatible types in assignment (expression has type "bool", variable has type "A")
110 if b:
111 pass
112 elif b:
113 pass
114 if b:
115 pass
116
117 class A: pass
118 [builtins fixtures/bool.pyi]
119
120
121 -- Loops
122 -- -----
123
124
125 [case testWhileStatement]
126
127 a: A
128 b: bool
129 while a:
130 a = b # Fail
131 else:
132 a = b # Fail
133 while b:
134 b = b
135
136 class A: pass
137 [builtins fixtures/bool.pyi]
138 [out]
139 main:5: error: Incompatible types in assignment (expression has type "bool", variable has type "A")
140 main:7: error: Incompatible types in assignment (expression has type "bool", variable has type "A")
141
142 [case testForStatement]
143 class A: pass
144
145 a: A
146 b: object
147 for a in [A()]:
148 a = b # E: Incompatible types in assignment (expression has type "object", variable has type "A")
149 else:
150 a = b # E: Incompatible types in assignment (expression has type "object", variable has type "A")
151 [builtins fixtures/list.pyi]
152
153 [case testBreakStatement]
154 import typing
155 while None:
156 break
157 [builtins fixtures/bool.pyi]
158 [out]
159
160 [case testContinueStatement]
161 import typing
162 while None:
163 continue
164 [builtins fixtures/bool.pyi]
165 [out]
166
167 [case testForStatementTypeComments_no_native_parse]
168
169 from typing import List, Union
170 x = [] # type: List[int]
171
172 for y in x: # type: str # E: Incompatible types in assignment (expression has type "int", variable has type "str")
173 pass
174
175 for z in x: # type: int
176 pass
177
178 for w in x: # type: Union[int, str]
179 reveal_type(w) # N: Revealed type is "builtins.int | builtins.str"
180
181 for v in x: # type: int, int # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)
182 pass
183 [builtins fixtures/list.pyi]
184
185 [case testForStatementMultipleTypeComments_no_native_parse]
186
187 from typing import List, Tuple
188 x = [] # type: List[Tuple[int, int]]
189
190 for y in x: # type: int, int # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)
191 pass
192
193 for z in x: # type: Tuple[int, int]
194 pass
195
196 for w,v in x: # type: int, str # E: Incompatible types in assignment (expression has type "int", variable has type "str")
197 pass
198
199 for a, b in x: # type: int, int, int # E: Incompatible number of tuple items
200 pass
201 [builtins fixtures/list.pyi]
202
203
204 -- Operator assignment
205 -- -------------------
206
207
208 [case testPlusAssign]
209 a: A
210 b: B
211 c: C
212 a += b # Fail
213 b += a # Fail
214 c += a # Fail
215 a += c
216
217 class A:
218 def __add__(self, x: 'C') -> 'A': pass
219
220 class B:
221 def __add__(self, x: A) -> 'C': pass
222
223 class C: pass
224 [builtins fixtures/tuple.pyi]
225 [out]
226 main:4: error: Unsupported operand types for + ("A" and "B")
227 main:5: error: Incompatible types in assignment (expression has type "C", variable has type "B")
228 main:6: error: Unsupported left operand type for + ("C")
229
230 [case testMinusAssign]
231 a: A
232 b: B
233 c: C
234 a -= b # Fail
235 b -= a # Fail
236 c -= a # Fail
237 a -= c
238
239 class A:
240 def __sub__(self, x: 'C') -> 'A': pass
241
242 class B:
243 def __sub__(self, x: A) -> 'C': pass
244
245 class C: pass
246 [builtins fixtures/tuple.pyi]
247 [out]
248 main:4: error: Unsupported operand types for - ("A" and "B")
249 main:5: error: Incompatible types in assignment (expression has type "C", variable has type "B")
250 main:6: error: Unsupported left operand type for - ("C")
251
252 [case testMulAssign]
253 a: A
254 c: C
255 a *= a # Fail
256 c *= a # Fail
257 a *= c
258
259 class A:
260 def __mul__(self, x: 'C') -> 'A': pass
261
262 class C: pass
263 [builtins fixtures/tuple.pyi]
264 [out]
265 main:3: error: Unsupported operand types for * ("A" and "A")
266 main:4: error: Unsupported left operand type for * ("C")
267
268 [case testMatMulAssign]
269 a: A
270 c: C
271 a @= a # E: Unsupported operand types for @ ("A" and "A")
272 c @= a # E: Unsupported left operand type for @ ("C")
273 a @= c
274
275 class A:
276 def __matmul__(self, x: 'C') -> 'A': pass
277
278 class C: pass
279 [builtins fixtures/tuple.pyi]
280
281 [case testDivAssign]
282 a: A
283 c: C
284 a /= a # Fail
285 c /= a # Fail
286 a /= c
287
288 class A:
289 def __truediv__(self, x: 'C') -> 'A': pass
290
291 class C: pass
292 [builtins fixtures/tuple.pyi]
293 [out]
294 main:3: error: Unsupported operand types for / ("A" and "A")
295 main:4: error: Unsupported left operand type for / ("C")
296
297 [case testPowAssign]
298 a: A
299 c: C
300 a **= a # Fail
301 c **= a # Fail
302 a **= c
303
304 class A:
305 def __pow__(self, x: 'C') -> 'A': pass
306
307 class C: pass
308 [builtins fixtures/tuple.pyi]
309 [out]
310 main:3: error: Unsupported operand types for ** ("A" and "A")
311 main:4: error: Unsupported left operand type for ** ("C")
312
313 [case testSubtypesInOperatorAssignment]
314 a: A
315 b: B
316 b += b
317 b += a
318 a += b
319
320 class A:
321 def __add__(self, x: 'A') -> 'B': pass
322
323 class B(A): pass
324 [builtins fixtures/tuple.pyi]
325 [out]
326
327 [case testAdditionalOperatorsInOpAssign]
328 a: A
329 c: C
330 a &= a # Fail
331 a >>= a # Fail
332 a //= a # Fail
333 a &= c
334 a >>= c
335 a //= c
336 class A:
337 def __and__(self, x: 'C') -> 'A': pass
338 def __rshift__(self, x: 'C') -> 'A': pass
339 def __floordiv__(self, x: 'C') -> 'A': pass
340 class C: pass
341 [builtins fixtures/tuple.pyi]
342 [out]
343 main:3: error: Unsupported operand types for & ("A" and "A")
344 main:4: error: Unsupported operand types for >> ("A" and "A")
345 main:5: error: Unsupported operand types for // ("A" and "A")
346
347 [case testInplaceOperatorMethods]
348 import typing
349 class A:
350 def __iadd__(self, x: int) -> 'A': pass
351 def __imul__(self, x: str) -> 'A': pass
352 def __imatmul__(self, x: str) -> 'A': pass
353 a = A()
354 a += 1
355 a *= ''
356 a @= ''
357 a += '' # E: Argument 1 to "__iadd__" of "A" has incompatible type "str"; expected "int"
358 a *= 1 # E: Argument 1 to "__imul__" of "A" has incompatible type "int"; expected "str"
359 a @= 1 # E: Argument 1 to "__imatmul__" of "A" has incompatible type "int"; expected "str"
360
361 [case testInplaceSetitem]
362 class A(object):
363 def __init__(self) -> None:
364 self.a = [1]
365
366 def __iadd__(self, a):
367 # type: (int) -> A
368 self.a += [2]
369 return self
370
371 a = A()
372 b = [a]
373 b[0] += 1
374 [builtins fixtures/list.pyi]
375 [out]
376
377
378 -- Assert statement
379 -- ----------------
380
381
382 [case testAssert]
383 import typing
384 assert None + None # Fail
385 assert None
386 [out]
387 main:2: error: Unsupported left operand type for + ("None")
388
389
390 -- Exception handling
391 -- ------------------
392
393
394 [case testRaiseStatement]
395
396 e: BaseException
397 f: MyError
398 a: A
399 raise a # Fail
400 raise e
401 raise f
402 class A: pass
403 class MyError(BaseException): pass
404 [builtins fixtures/exception.pyi]
405 [out]
406 main:5: error: Exception must be derived from BaseException
407
408 [case testRaiseClassObject]
409 class A: pass
410 class MyError(BaseException): pass
411 def f(): pass
412 if object():
413 raise BaseException
414 if object():
415 raise MyError
416 if object():
417 raise A # E: Exception must be derived from BaseException
418 if object():
419 raise object # E: Exception must be derived from BaseException
420 if object():
421 raise f # E: Exception must be derived from BaseException
422 [builtins fixtures/exception.pyi]
423
424 [case testRaiseClassObjectCustomInit]
425 class MyBaseError(BaseException):
426 def __init__(self, required) -> None:
427 ...
428 class MyError(Exception):
429 def __init__(self, required1, required2) -> None:
430 ...
431 class MyKwError(Exception):
432 def __init__(self, *, kwonly) -> None:
433 ...
434 class MyErrorWithDefault(Exception):
435 def __init__(self, optional=1) -> None:
436 ...
437 if object():
438 raise BaseException
439 if object():
440 raise Exception
441 if object():
442 raise BaseException(1)
443 if object():
444 raise Exception(2)
445 if object():
446 raise MyBaseError(4)
447 if object():
448 raise MyError(5, 6)
449 if object():
450 raise MyKwError(kwonly=7)
451 if object():
452 raise MyErrorWithDefault(8)
453 if object():
454 raise MyErrorWithDefault
455 if object():
456 raise MyBaseError # E: Too few arguments for "MyBaseError"
457 if object():
458 raise MyError # E: Too few arguments for "MyError"
459 if object():
460 raise MyKwError # E: Missing named argument "kwonly" for "MyKwError"
461 [builtins fixtures/exception.pyi]
462
463 [case testRaiseExceptionType]
464 import typing
465 x: typing.Type[BaseException]
466 raise x
467 [builtins fixtures/exception.pyi]
468
469 [case testRaiseNonExceptionTypeFails]
470 import typing
471 x = int # type: typing.Type[int]
472 raise x # E: Exception must be derived from BaseException
473 [builtins fixtures/exception.pyi]
474
475 [case testRaiseUnion]
476 import typing
477 x: typing.Union[BaseException, typing.Type[BaseException]]
478 raise x
479 [builtins fixtures/exception.pyi]
480
481 [case testRaiseNonExceptionUnionFails]
482 import typing
483 x: typing.Union[BaseException, int]
484 raise x # E: Exception must be derived from BaseException
485 [builtins fixtures/exception.pyi]
486
487 [case testRaiseFromStatement]
488 e: BaseException
489 f: MyError
490 a: A
491 x: BaseException
492 del x
493 if object():
494 raise e from a # E: Exception must be derived from BaseException
495 if object():
496 raise e from e
497 if object():
498 raise e from f
499 if object():
500 raise e from x # E: Trying to read deleted variable "x"
501 class A: pass
502 class MyError(BaseException): pass
503 [builtins fixtures/exception.pyi]
504
505 [case testRaiseFromClassobject]
506 import typing
507 class A: pass
508 class MyError(BaseException): pass
509 def f(): pass
510 if object():
511 raise BaseException from BaseException
512 if object():
513 raise BaseException from MyError
514 if object():
515 raise BaseException from A # E: Exception must be derived from BaseException
516 if object():
517 raise BaseException from object # E: Exception must be derived from BaseException
518 if object():
519 raise BaseException from f # E: Exception must be derived from BaseException
520 [builtins fixtures/exception.pyi]
521
522 [case testRaiseNotImplementedFails]
523 if object():
524 raise NotImplemented # E: Exception must be derived from BaseException \
525 # E: Exception must be derived from BaseException; did you mean "NotImplementedError"?
526 if object():
527 raise NotImplemented() # E: Exception must be derived from BaseException; did you mean "NotImplementedError"? \
528 # E: "NotImplementedType" not callable
529 [builtins fixtures/notimplemented.pyi]
530
531 [case testTryFinallyStatement]
532 import typing
533 try:
534 b = object() # type: A # Fail
535 finally:
536 c = object() # type: A # Fail
537 class A: pass
538 [out]
539 main:3: error: Incompatible types in assignment (expression has type "object", variable has type "A")
540 main:5: error: Incompatible types in assignment (expression has type "object", variable has type "A")
541
542 [case testSimpleTryExcept]
543
544 try:
545 pass
546 except BaseException as e:
547 a: BaseException
548 o: object
549 e = a
550 e = o # Fail
551 class A: pass
552 class B: pass
553 [builtins fixtures/exception.pyi]
554 [out]
555 main:8: error: Incompatible types in assignment (expression has type "object", variable has type "BaseException")
556
557 [case testTypeErrorInBlock]
558 class A: pass
559 class B: pass
560 while int():
561 x: A
562 if int():
563 x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
564 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
565
566 [case testTypeErrorInvolvingBaseException]
567 class A: pass
568
569 x: BaseException
570 a: A
571 if int():
572 a = BaseException() # E: Incompatible types in assignment (expression has type "BaseException", variable has type "A")
573 if int():
574 a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
575 if int():
576 x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "BaseException")
577 if int():
578 x = A() # E: Incompatible types in assignment (expression has type "A", variable has type "BaseException")
579 if int():
580 x = BaseException()
581 [builtins fixtures/exception.pyi]
582
583 [case testSimpleTryExcept2]
584 import typing
585 try:
586 pass
587 except BaseException as e:
588 e = object() # Fail
589 e = BaseException()
590 [builtins fixtures/exception.pyi]
591 [out]
592 main:5: error: Incompatible types in assignment (expression has type "object", variable has type "BaseException")
593
594 [case testBaseClassAsExceptionTypeInExcept]
595 import typing
596 class Err(BaseException): pass
597 try:
598 pass
599 except Err as e:
600 e = BaseException() # E: Incompatible types in assignment (expression has type "BaseException", variable has type "Err")
601 e = Err()
602 [builtins fixtures/exception.pyi]
603 [case testMultipleExceptHandlers]
604 import typing
605 class Err(BaseException): pass
606 try:
607 pass
608 except BaseException as e:
609 pass
610 except Err as f:
611 f = BaseException() # E: Incompatible types in assignment (expression has type "BaseException", variable has type "Err")
612 f = Err()
613 [builtins fixtures/exception.pyi]
614 [case testTryExceptStatement]
615 import typing
616 class A: pass
617 class B: pass
618 class Err(BaseException): pass
619 try:
620 a = B() # type: A # E: Incompatible types in assignment (expression has type "B", variable has type "A")
621 except BaseException as e:
622 e = A() # E: Incompatible types in assignment (expression has type "A", variable has type "BaseException")
623 e = Err()
624 except Err as f:
625 f = BaseException() # E: Incompatible types in assignment (expression has type "BaseException", variable has type "Err")
626 f = Err()
627 [builtins fixtures/exception.pyi]
628 [case testTryExceptWithinFunction]
629 import typing
630 def f() -> None:
631 try: pass
632 except BaseException as e:
633 e = object() # Fail
634 e = BaseException()
635 except Err as f:
636 f = BaseException() # Fail
637 f = Err()
638 class Err(BaseException): pass
639 [builtins fixtures/exception.pyi]
640 [out]
641 main:5: error: Incompatible types in assignment (expression has type "object", variable has type "BaseException")
642 main:8: error: Incompatible types in assignment (expression has type "BaseException", variable has type "Err")
643
644 [case testTryExceptFlow]
645 def f() -> None:
646 x = 1
647 try:
648 pass
649 except:
650 raise
651 x + 'a' # E: Unsupported left operand type for + ("int")
652 [builtins fixtures/exception.pyi]
653 [out]
654
655 [case testTryWithElse]
656 import typing
657 try: pass
658 except BaseException: pass
659 else:
660 object(None) # E: Too many arguments for "object"
661 [builtins fixtures/exception.pyi]
662
663 [case testRedefinedFunctionInTryWithElse]
664 def f() -> None: pass
665 try:
666 pass
667 except BaseException:
668 f2 = f
669 else:
670 def f2() -> str: pass
671 try:
672 pass
673 except BaseException:
674 f3 = f
675 else:
676 def f3() -> None: pass
677 [builtins fixtures/exception.pyi]
678 [out]
679 main:7: error: Incompatible redefinition (redefinition with type "Callable[[], str]", original type "Callable[[], None]")
680
681 [case testExceptWithoutType]
682 import typing
683 try:
684 -None # E: Unsupported operand type for unary - ("None")
685 except:
686 ~None # E: Unsupported operand type for ~ ("None")
687 [builtins fixtures/exception.pyi]
688
689 [case testRaiseWithoutArgument]
690 import typing
691 try:
692 None
693 except:
694 raise
695 [builtins fixtures/exception.pyi]
696
697 [case testExceptWithMultipleTypes]
698 import typing
699 class E1(BaseException): pass
700 class E2(E1): pass
701 try:
702 pass
703 except (E1, E2): pass
704 except (E1, object): pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
705 except (object, E2): pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
706 except (E1, (E2,)): pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
707
708 except (E1, E2): pass
709 except ((E1, E2)): pass
710 except (((E1, E2))): pass
711 [builtins fixtures/exception.pyi]
712
713 [case testExceptWithTypeType]
714 import typing
715 E = BaseException # type: typing.Type[BaseException]
716
717 try:
718 pass
719 except E:
720 pass
721 [builtins fixtures/exception.pyi]
722
723 [case testExceptWithMultipleTypes2]
724 import typing
725 class E1(BaseException): pass
726 class E2(E1): pass
727 try:
728 pass
729 except (E1, E2) as e1:
730 x = e1 # type: E1
731 y = e1 # type: E2 # E: Incompatible types in assignment (expression has type "E1", variable has type "E2")
732 except (E2, E1) as e2:
733 a = e2 # type: E1
734 b = e2 # type: E2 # E: Incompatible types in assignment (expression has type "E1", variable has type "E2")
735 except (E1, E2, int) as e3: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
736 pass
737 [builtins fixtures/exception.pyi]
738
739 [case testExceptWithMultipleTypes3]
740 import typing
741 class E1(BaseException): pass
742 class E1_1(E1): pass
743 class E1_2(E1): pass
744 try: pass
745 except (E1, E1_1, E1_2) as e1:
746 x = e1 # type: E1
747 y = e1 # type: E1_1 # E: Incompatible types in assignment (expression has type "E1", variable has type "E1_1")
748 z = e1 # type: E1_2 # E: Incompatible types in assignment (expression has type "E1", variable has type "E1_2")
749 except (E1_1, E1_2) as e2:
750 a = e2 # type: E1
751 b = e2 # type: E1_1 # E: Incompatible types in assignment (expression has type "E1_1 | E1_2", variable has type "E1_1")
752 c = e2 # type: E1_2 # E: Incompatible types in assignment (expression has type "E1_1 | E1_2", variable has type "E1_2")
753 [builtins fixtures/exception.pyi]
754
755 [case testExceptWithMultipleTypes4]
756 from typing import Tuple, Type, Union
757
758 class E1(BaseException): pass
759 class E2(BaseException): pass
760 class E3(BaseException): pass
761
762 def variadic(exc: Tuple[Type[E1], ...]) -> None:
763 try:
764 pass
765 except exc as e:
766 reveal_type(e) # N: Revealed type is "__main__.E1"
767
768 def union(exc: Union[Type[E1], Type[E2]]) -> None:
769 try:
770 pass
771 except exc as e:
772 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2"
773
774 def tuple_in_union(exc: Union[Type[E1], Tuple[Type[E2], Type[E3]]]) -> None:
775 try:
776 pass
777 except exc as e:
778 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2 | __main__.E3"
779
780 def variadic_in_union(exc: Union[Type[E1], Tuple[Type[E2], ...]]) -> None:
781 try:
782 pass
783 except exc as e:
784 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2"
785
786 def nested_union(exc: Union[Type[E1], Union[Type[E2], Type[E3]]]) -> None:
787 try:
788 pass
789 except exc as e:
790 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2 | __main__.E3"
791
792 def error_in_union(exc: Union[Type[E1], int]) -> None:
793 try:
794 pass
795 except exc as e: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
796 pass
797
798 def error_in_variadic(exc: Tuple[int, ...]) -> None:
799 try:
800 pass
801 except exc as e: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
802 pass
803
804 [builtins fixtures/tuple.pyi]
805
806 [case testExceptWithMultipleTypes5]
807 from typing import Tuple, Type, Union, Never
808
809 class E1(BaseException): pass
810 class E2(BaseException): pass
811 class E3(BaseException): pass
812
813 def union_in_variadic(exc: Tuple[Union[Type[E1], Type[E2]], ...]) -> None:
814 try:
815 pass
816 except exc as e:
817 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2"
818
819 def nested_union_in_variadic(exc: Tuple[Union[Type[E1], Union[Type[E2], Type[E3]]], ...]) -> None:
820 try:
821 pass
822 except exc as e:
823 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2 | __main__.E3"
824
825 def union_in_tuple(exc: Tuple[Union[Type[E1], Type[E2]], Type[E3]]) -> None:
826 try:
827 pass
828 except exc as e:
829 reveal_type(e) # N: Revealed type is "__main__.E1 | __main__.E2 | __main__.E3"
830
831 def error_in_variadic_union(exc: Tuple[Union[Type[E1], int], ...]) -> None:
832 try:
833 pass
834 except exc as e: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
835 pass
836
837 def error_in_variadic_nested_union(exc: Tuple[Union[Type[E1], Union[Type[E2], int]], ...]) -> None:
838 try:
839 pass
840 except exc as e: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
841 pass
842
843 def error_in_tuple_inside_variadic_nested_union(exc: Tuple[Union[Type[E1], Union[Type[E2], Tuple[Type[E3]]]], ...]) -> None:
844 try:
845 pass
846 except exc as e: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
847 pass
848
849 def error_in_tuple_union(exc: Tuple[Union[Type[E1], Type[E2]], Union[Type[E3], int]]) -> None:
850 try:
851 pass
852 except exc as e: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
853 pass
854 [builtins fixtures/tuple.pyi]
855
856 [case testExceptWithMultipleTypes6]
857 from typing import Never
858
859 def random() -> bool: ...
860
861 def error_in_empty_tuple() -> None:
862 try:
863 pass
864 except () as e: # E: Need type annotation for "e"
865 pass
866
867 def error_in_empty_tuple_annotated(exc: tuple[()]) -> None:
868 try:
869 pass
870 except exc as e: # E: Need type annotation for "e"
871 pass
872
873 def error_in_conditional_empty_tuple() -> None:
874 try:
875 pass
876 except (BaseException if random() else ()) as e:
877 pass
878
879 def error_in_never(exc: Never) -> None:
880 try:
881 pass
882 except exc as e: # E: Need type annotation for "e"
883 pass
884 [builtins fixtures/tuple.pyi]
885
886 [case testExceptWithAnyTypes]
887 from typing import Any
888
889 E1 = None # type: Any
890 class E2(BaseException): pass
891 class NotBaseDerived: pass
892
893 try:
894 pass
895 except BaseException as e1:
896 reveal_type(e1) # N: Revealed type is "builtins.BaseException"
897 except (E1, BaseException) as e2:
898 reveal_type(e2) # N: Revealed type is "Any | builtins.BaseException"
899 except (E1, E2) as e3:
900 reveal_type(e3) # N: Revealed type is "Any | __main__.E2"
901 except (E1, E2, BaseException) as e4:
902 reveal_type(e4) # N: Revealed type is "Any | builtins.BaseException"
903
904 try: pass
905 except E1 as e1:
906 reveal_type(e1) # N: Revealed type is "Any"
907 except E2 as e2:
908 reveal_type(e2) # N: Revealed type is "__main__.E2"
909 except NotBaseDerived as e3: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
910 pass
911 except (NotBaseDerived, E1) as e4: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
912 pass
913 except (NotBaseDerived, E2) as e5: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
914 pass
915 except (NotBaseDerived, E1, E2) as e6: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
916 pass
917 except (E1, E2, NotBaseDerived) as e6: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
918 pass
919 [builtins fixtures/exception.pyi]
920
921 [case testReuseTryExceptionVariable]
922 import typing
923 class E1(BaseException): pass
924 class E2(BaseException): pass
925 try: pass
926 except E1 as e: pass
927 try: pass
928 except E1 as e: pass
929 try: pass
930 except E2 as e: pass
931 e + 1 # E: Trying to read deleted variable "e" # E: Name "e" is used before definition
932 e = E1() # E: Assignment to variable "e" outside except: block
933 [builtins fixtures/exception.pyi]
934
935 [case testReuseDefinedTryExceptionVariable]
936 import typing
937 class E1(BaseException): pass
938 class E2(BaseException): pass
939 e = 1
940 def f(): e # Prevent redefinition
941 e = 1
942 try: pass
943 except E1 as e: pass
944 e = 1 # E: Assignment to variable "e" outside except: block
945 e = E1() # E: Assignment to variable "e" outside except: block
946 [builtins fixtures/exception.pyi]
947
948 [case testExceptionVariableReuseInDeferredNode1]
949 def f(*a: BaseException) -> int:
950 x
951 try: pass
952 except BaseException as err: pass
953 try: pass
954 except BaseException as err: f(err)
955 return 0
956 x = f()
957 [builtins fixtures/exception.pyi]
958
959 [case testExceptionVariableReuseInDeferredNode2]
960 def f(*a: BaseException) -> int:
961 try: pass
962 except BaseException as err: pass
963 x
964 try: pass
965 except BaseException as err: f(err)
966 return 0
967 x = f()
968 [builtins fixtures/exception.pyi]
969
970 [case testExceptionVariableReuseInDeferredNode3]
971 def f(*a: BaseException) -> int:
972 try: pass
973 except BaseException as err: pass
974 try: pass
975 except BaseException as err: f(err)
976 x
977 return 0
978 x = f()
979 [builtins fixtures/exception.pyi]
980
981 [case testExceptionVariableReuseInDeferredNode4]
982 class EA(BaseException):
983 a: int
984 class EB(BaseException):
985 b: str
986 def f(*arg: BaseException) -> int:
987 x
988 try: pass
989 except EA as err:
990 f(err)
991 a = err.a
992 reveal_type(a)
993 try: pass
994 except EB as err:
995 f(err)
996 b = err.b
997 reveal_type(b)
998 return 0
999 x = f()
1000 [builtins fixtures/exception.pyi]
1001 [out]
1002 main:11: note: Revealed type is "builtins.int"
1003 main:16: note: Revealed type is "builtins.str"
1004
1005 [case testExceptionVariableReuseInDeferredNode5]
1006 class EA(BaseException):
1007 a: int
1008 class EB(BaseException):
1009 b: str
1010 def f(*arg: BaseException) -> int:
1011 try: pass
1012 except EA as err:
1013 f(err)
1014 a = err.a
1015 reveal_type(a)
1016 x
1017 try: pass
1018 except EB as err:
1019 f(err)
1020 b = err.b
1021 reveal_type(b)
1022 return 0
1023 x = f()
1024 [builtins fixtures/exception.pyi]
1025 [out]
1026 main:10: note: Revealed type is "builtins.int"
1027 main:16: note: Revealed type is "builtins.str"
1028
1029 [case testExceptionVariableReuseInDeferredNode6]
1030 class EA(BaseException):
1031 a: int
1032 class EB(BaseException):
1033 b: str
1034 def f(*arg: BaseException) -> int:
1035 try: pass
1036 except EA as err:
1037 f(err)
1038 a = err.a
1039 reveal_type(a)
1040 try: pass
1041 except EB as err:
1042 f(err)
1043 b = err.b
1044 reveal_type(b)
1045 x
1046 return 0
1047 x = f()
1048 [builtins fixtures/exception.pyi]
1049 [out]
1050 main:10: note: Revealed type is "builtins.int"
1051 main:15: note: Revealed type is "builtins.str"
1052
1053 [case testExceptionVariableWithDisallowAnyExprInDeferredNode]
1054 # flags: --disallow-any-expr
1055 def f() -> int:
1056 x
1057 try:
1058 pass
1059 except Exception as ex:
1060 pass
1061 return 0
1062 x = f()
1063 [builtins fixtures/exception.pyi]
1064
1065 [case testArbitraryExpressionAsExceptionType]
1066 import typing
1067 a = BaseException
1068 try: pass
1069 except a as b:
1070 b = BaseException()
1071 b = object() # E: Incompatible types in assignment (expression has type "object", variable has type "BaseException")
1072 [builtins fixtures/exception.pyi]
1073
1074 [case testInvalidExceptionCallable]
1075 import typing
1076 def exc() -> BaseException: pass
1077 try: pass
1078 except exc as e: pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
1079 except BaseException() as b: pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
1080 [builtins fixtures/exception.pyi]
1081
1082 [case testTupleValueAsExceptionType]
1083 import typing
1084 def exc() -> BaseException: pass
1085 class E1(BaseException): pass
1086 class E1_1(E1): pass
1087 class E1_2(E1): pass
1088
1089 exs1 = (E1, E1_1, E1_2)
1090 try: pass
1091 except exs1 as e1:
1092 x = e1 # type: E1
1093 y = e1 # type: E1_1 # E: Incompatible types in assignment (expression has type "E1", variable has type "E1_1")
1094 z = e1 # type: E1_2 # E: Incompatible types in assignment (expression has type "E1", variable has type "E1_2")
1095
1096 exs2 = (E1_1, E1_2)
1097 try: pass
1098 except exs2 as e2:
1099 a = e2 # type: E1
1100 b = e2 # type: E1_1 # E: Incompatible types in assignment (expression has type "E1_1 | E1_2", variable has type "E1_1")
1101 c = e2 # type: E1_2 # E: Incompatible types in assignment (expression has type "E1_1 | E1_2", variable has type "E1_2")
1102
1103 exs3 = (E1, (E1_1, (E1_2,)))
1104 try: pass
1105 except exs3 as e3: pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
1106 [builtins fixtures/exception.pyi]
1107
1108 [case testInvalidTupleValueAsExceptionType]
1109 import typing
1110 def exc() -> BaseException: pass
1111 class E1(BaseException): pass
1112 class E2(E1): pass
1113
1114 exs1 = (E1, E2, int)
1115 try: pass
1116 except exs1 as e: pass # E: Exception type must be derived from BaseException (or be a tuple of exception classes)
1117 [builtins fixtures/exception.pyi]
1118
1119 [case testOverloadedExceptionType]
1120 from foo import *
1121 [file foo.pyi]
1122 from typing import overload
1123 class E(BaseException):
1124 @overload
1125 def __init__(self) -> None: pass
1126 @overload
1127 def __init__(self, x) -> None: pass
1128 try:
1129 pass
1130 except E as e:
1131 e = E()
1132 e = BaseException() # E: Incompatible types in assignment (expression has type "BaseException", variable has type "E")
1133 [builtins fixtures/exception.pyi]
1134
1135 [case testExceptionWithAnyBaseClass]
1136 from typing import Any
1137 E = None # type: Any
1138 class EE(E): pass
1139 raise EE()
1140 raise EE
1141 [builtins fixtures/exception.pyi]
1142
1143 [case testExceptionIsType]
1144 from typing import Type
1145 class B(BaseException): pass
1146 def f(e: Type[B]):
1147 try: pass
1148 except e: pass
1149 def g(e: Type[BaseException]):
1150 try: pass
1151 except e as err:
1152 reveal_type(err)
1153 def h(e: Type[int]):
1154 try: pass
1155 except e: pass
1156 [builtins fixtures/exception.pyi]
1157 [out]
1158 main:9: note: Revealed type is "builtins.BaseException"
1159 main:12: error: Exception type must be derived from BaseException (or be a tuple of exception classes)
1160
1161
1162 -- Del statement
1163 -- -------------
1164
1165
1166 [case testDelStmtWithIndex]
1167 a: A
1168 b: B
1169 del b[a]
1170 del b[b] # E: Argument 1 to "__delitem__" of "B" has incompatible type "B"; expected "A"
1171 del a[a] # E: "A" has no attribute "__delitem__"
1172 del a[b] # E: "A" has no attribute "__delitem__"
1173 class B:
1174 def __delitem__(self, index: 'A'): pass
1175 class A: pass
1176 [builtins fixtures/tuple.pyi]
1177
1178 [case testDelStmtWithAttribute]
1179 class A:
1180 def f(self): pass
1181 x = 0
1182 a = A()
1183 del a.f
1184 del a.x
1185 del a.z # E: "A" has no attribute "z"
1186
1187 [case testDelStatementWithTuple]
1188 class A:
1189 x = 0
1190 a = A()
1191 del a.x, a.y # E: "A" has no attribute "y"
1192 [builtins fixtures/tuple.pyi]
1193
1194 [case testDelStmtWithTypeInfo]
1195 class Foo: ...
1196 del Foo
1197 Foo + 1 # E: Trying to read deleted variable "Foo"
1198
1199 [case testDelStatementWithAssignmentSimple]
1200 a = 1
1201 a + 1
1202 del a
1203 a + 1 # E: Trying to read deleted variable "a"
1204 [builtins fixtures/ops.pyi]
1205
1206 [case testDelStatementWithAssignmentTuple]
1207 a = 1
1208 b = 1
1209 del (a, b)
1210 b + 1 # E: Trying to read deleted variable "b"
1211 [builtins fixtures/ops.pyi]
1212
1213 [case testDelStatementWithAssignmentList]
1214 a = 1
1215 b = 1
1216 del [a, b]
1217 b + 1 # E: Trying to read deleted variable "b"
1218 [builtins fixtures/list.pyi]
1219
1220 [case testDelStatementWithAssignmentClass]
1221 class C:
1222 a = 1
1223
1224 c = C()
1225 c.a = 1
1226 c.a + 1
1227 del c.a
1228 c.a + 1
1229 [builtins fixtures/ops.pyi]
1230
1231 [case testDelStatementWithConditions]
1232 x = 5
1233 del x
1234 if x: ... # E: Trying to read deleted variable "x"
1235
1236 def f(x):
1237 return x
1238
1239 if 0: ...
1240 elif f(x): ... # E: Trying to read deleted variable "x"
1241
1242 while x == 5: ... # E: Trying to read deleted variable "x"
1243
1244 -- Yield statement
1245 -- ---------------
1246
1247
1248 [case testSimpleYield]
1249 from typing import Iterator
1250 def f() -> Iterator[int]:
1251 yield 1
1252 yield '' # E: Incompatible types in "yield" (actual type "str", expected type "int")
1253 [builtins fixtures/for.pyi]
1254 [out]
1255
1256 [case testYieldInFunctionReturningGenerator]
1257 from typing import Generator
1258 def f() -> Generator[int, None, None]:
1259 yield 1
1260 [builtins fixtures/for.pyi]
1261 [out]
1262
1263 [case testYieldInFunctionReturningIterable]
1264 from typing import Iterable
1265 def f() -> Iterable[int]:
1266 yield 1
1267 [builtins fixtures/for.pyi]
1268 [out]
1269
1270 [case testYieldInFunctionReturningObject]
1271 def f() -> object:
1272 yield 1
1273 [builtins fixtures/for.pyi]
1274 [out]
1275
1276 [case testYieldInFunctionReturningAny]
1277 from typing import Any
1278 def f() -> Any:
1279 yield object()
1280 [out]
1281
1282 [case testYieldInFunctionReturningFunction]
1283 from typing import Callable
1284 def f() -> Callable[[], None]: # E: The return type of a generator function should be "Generator" or one of its supertypes
1285 yield object()
1286 [out]
1287
1288 [case testYieldInDynamicallyTypedFunction]
1289 import typing
1290 def f():
1291 yield f
1292
1293 [case testWithInvalidInstanceReturnType]
1294 import typing
1295 def f() -> int: # E: The return type of a generator function should be "Generator" or one of its supertypes
1296 yield 1
1297 [builtins fixtures/for.pyi]
1298 [out]
1299
1300 [case testTypeInferenceContextAndYield]
1301 from typing import List, Iterator
1302 def f() -> 'Iterator[List[int]]':
1303 yield []
1304 yield [object()] # E: List item 0 has incompatible type "object"; expected "int"
1305 [builtins fixtures/for.pyi]
1306 [out]
1307
1308 [case testYieldAndReturnWithoutValue]
1309 from typing import Iterator
1310 def f() -> Iterator[int]:
1311 yield 1
1312 return
1313 [builtins fixtures/for.pyi]
1314
1315 [case testYieldWithNoValue]
1316 from typing import Iterator
1317 def f() -> Iterator[None]:
1318 yield
1319 [builtins fixtures/for.pyi]
1320
1321 [case testYieldWithNoValueWhenValueRequired]
1322 from typing import Iterator
1323 def f() -> Iterator[int]:
1324 yield # E: Yield value expected
1325 [builtins fixtures/for.pyi]
1326 [out]
1327
1328 [case testYieldWithExplicitNone]
1329 from typing import Iterator
1330 def f() -> Iterator[None]:
1331 yield None
1332 [builtins fixtures/for.pyi]
1333 [out]
1334
1335
1336 -- Yield from statement
1337 -- --------------------
1338 --
1339 -- (It's not really a statement, but don't want to move the tests.)
1340
1341 [case testSimpleYieldFromWithIterator]
1342 from typing import Iterator
1343 def g() -> Iterator[str]:
1344 yield '42'
1345 def h() -> Iterator[int]:
1346 yield 42
1347 def f() -> Iterator[str]:
1348 yield from g()
1349 yield from h() # E: Incompatible types in "yield from" (actual type "int", expected type "str")
1350 [out]
1351
1352 [case testYieldFromAppliedToAny]
1353 from typing import Any
1354 def g() -> Any:
1355 yield object()
1356 def f() -> Any:
1357 yield from g()
1358 [out]
1359
1360 [case testYieldFromInFunctionReturningFunction]
1361 from typing import Iterator, Callable
1362 def g() -> Iterator[int]:
1363 yield 42
1364 def f() -> Callable[[], None]: # E: The return type of a generator function should be "Generator" or one of its supertypes
1365 yield from g()
1366 [out]
1367
1368 [case testYieldFromNotIterableReturnType]
1369 from typing import Iterator
1370 def g() -> Iterator[int]:
1371 yield 42
1372 def f() -> int: # E: The return type of a generator function should be "Generator" or one of its supertypes
1373 yield from g()
1374 [out]
1375
1376 [case testYieldFromNotAppliedIterator]
1377 from typing import Iterator
1378 def g() -> int:
1379 return 42
1380 def f() -> Iterator[int]:
1381 yield from g() # E: "yield from" can't be applied to "int"
1382 [out]
1383
1384 [case testYieldFromCheckIncompatibleTypesTwoIterables]
1385 from typing import List, Iterator
1386 def g() -> Iterator[List[int]]:
1387 yield [2, 3, 4]
1388 def f() -> Iterator[List[int]]:
1389 yield from g()
1390 yield from [1, 2, 3] # E: Incompatible types in "yield from" (actual type "int", expected type "list[int]")
1391 [builtins fixtures/for.pyi]
1392 [out]
1393
1394 [case testYieldFromNotAppliedToNothing_no_native_parse]
1395 def h():
1396 yield from # E: Invalid syntax
1397 [out]
1398
1399 [case testYieldFromAndYieldTogether]
1400 from typing import Iterator
1401 def f() -> Iterator[str]:
1402 yield "g1 ham"
1403 yield from g()
1404 yield "g1 eggs"
1405 def g() -> Iterator[str]:
1406 yield "g2 spam"
1407 yield "g2 more spam"
1408 [out]
1409
1410 [case testYieldFromAny]
1411 from typing import Iterator
1412 def f(a):
1413 b = yield from a
1414 return b
1415 [out]
1416
1417 [case testYieldFromGenericCall]
1418 from typing import Generator, TypeVar
1419 T = TypeVar('T')
1420 def f(a: T) -> Generator[int, str, T]: pass
1421 def g() -> Generator[int, str, float]:
1422 r = yield from f('')
1423 reveal_type(r) # N: Revealed type is "builtins.str"
1424 return 3.14
1425
1426 [case testYieldFromTupleStatement]
1427 from typing import Generator
1428 def g() -> Generator[int, None, None]:
1429 yield from ()
1430 yield from (0, 1, 2)
1431 yield from (0, "ERROR") # E: Incompatible types in "yield from" (actual type "int | str", expected type "int")
1432 yield from ("ERROR",) # E: Incompatible types in "yield from" (actual type "str", expected type "int")
1433 [builtins fixtures/tuple.pyi]
1434
1435 -- With statement
1436 -- --------------
1437
1438
1439 [case testSimpleWith]
1440 import typing
1441 class A:
1442 def __enter__(self) -> None: pass
1443 def __exit__(self, x, y, z) -> None: pass
1444 with A():
1445 object(A) # E: Too many arguments for "object"
1446
1447 [case testWithStmtAndInvalidExit]
1448 import typing
1449 class A:
1450 def __enter__(self) -> None: pass
1451 def __exit__(self, x, y) -> None: pass
1452 with A(): # E: Too many arguments for "__exit__" of "A"
1453 pass
1454
1455 [case testWithStmtAndMissingExit]
1456 import typing
1457 class A:
1458 def __enter__(self) -> None: pass
1459 with A(): # E: "A" has no attribute "__exit__"
1460 pass
1461
1462 [case testWithStmtAndInvalidEnter]
1463 import typing
1464 class A:
1465 def __enter__(self, x) -> None: pass
1466 def __exit__(self, x, y, z) -> None: pass
1467 with A(): # E: Too few arguments for "__enter__" of "A"
1468 pass
1469
1470 [case testWithStmtAndMissingEnter]
1471 import typing
1472 class A:
1473 def __exit__(self, x, y, z) -> None: pass
1474 with A(): # E: "A" has no attribute "__enter__"
1475 pass
1476
1477 [case testWithStmtAndMultipleExprs]
1478 import typing
1479 class A:
1480 def __enter__(self) -> None: pass
1481 def __exit__(self, x, y, z) -> None: pass
1482 class B:
1483 def __enter__(self) -> None: pass
1484 with A(), B(): # E: "B" has no attribute "__exit__"
1485 pass
1486 with B(), A(): # E: "B" has no attribute "__exit__"
1487 pass
1488
1489 [case testWithStmtAndResult]
1490 import typing
1491 class B: pass
1492 class A:
1493 def __enter__(self) -> B: pass
1494 def __exit__(self, x, y, z): pass
1495 with A() as b:
1496 b = B()
1497 b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1498
1499 [case testWithStmtAndMultipleResults]
1500 from typing import TypeVar, Generic
1501 t = TypeVar('t')
1502 class B: pass
1503 class C: pass
1504 class A(Generic[t]):
1505 def __enter__(self) -> t: pass
1506 def __exit__(self, x, y, z): pass
1507 a_b = A() # type: A[B]
1508 a_c = A() # type: A[C]
1509 with a_b as b, a_c as c:
1510 b = B()
1511 c = C()
1512 b = c # E: Incompatible types in assignment (expression has type "C", variable has type "B")
1513 c = b # E: Incompatible types in assignment (expression has type "B", variable has type "C")
1514
1515 [case testWithStmtAndComplexTarget]
1516 from typing import Tuple
1517 class A:
1518 def __enter__(self) -> Tuple[int, str]: pass
1519 def __exit__(self, x, y, z): pass
1520 with A() as (a, b):
1521 a = 1
1522 b = ''
1523 a = b # E: Incompatible types in assignment (expression has type "str", variable has type "int")
1524 [builtins fixtures/tuple.pyi]
1525
1526 [case testWithStmtTypeComment_no_native_parse]
1527
1528 from typing import Union
1529 class A:
1530 def __enter__(self) -> int: pass
1531 def __exit__(self, x, y, z): pass
1532
1533 with A(): # type: int # E: Invalid type comment: "with" statement has no targets
1534 pass
1535
1536 with A() as a: # type: int
1537 pass
1538
1539 with A() as b: # type: str # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1540 pass
1541
1542 with A() as c: # type: int, int # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)
1543 pass
1544
1545 with A() as d: # type: Union[int, str]
1546 reveal_type(d) # N: Revealed type is "builtins.int | builtins.str"
1547
1548 [case testWithStmtTupleTypeComment_no_native_parse]
1549
1550 from typing import Tuple
1551 class A:
1552 def __enter__(self) -> Tuple[int, int]: pass
1553 def __exit__(self, x, y, z): pass
1554
1555 with A():
1556 pass
1557
1558 with A() as a: # type: Tuple[int, int]
1559 pass
1560
1561 with A() as b: # type: Tuple[int, str] # E: Incompatible types in assignment (expression has type "tuple[int, int]", variable has type "tuple[int, str]")
1562 pass
1563
1564 with A() as (c, d): # type: int, int
1565 pass
1566
1567 with A() as (e, f): # type: Tuple[int, int]
1568 pass
1569
1570 with A() as (g, h): # type: int # E: Tuple type expected for multiple variables
1571 pass
1572
1573 with A() as (i, j): # type: int, int, str # E: Incompatible number of tuple items
1574 pass
1575
1576 with A() as (k, l): # type: int, str # E: Incompatible types in assignment (expression has type "int", variable has type "str")
1577 pass
1578 [builtins fixtures/tuple.pyi]
1579
1580 [case testWithStmtComplexTypeComment_no_native_parse]
1581
1582 from typing import Tuple
1583 class A:
1584 def __enter__(self) -> Tuple[int, int]: pass
1585 def __exit__(self, x, y, z): pass
1586
1587 class B:
1588 def __enter__(self) -> str: pass
1589 def __exit__(self, x, y, z): pass
1590
1591 with A() as a, A() as (b, c), B() as d: # type: Tuple[int, int], (int, int), str
1592 pass
1593
1594 with A() as e, A() as (f, g), B() as h: # type: Tuple[int, int], Tuple[int, int], str
1595 pass
1596
1597 with A() as i, A() as (j, k), B() as l: # type: (int, int), (int, int), str # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)
1598 pass
1599
1600 with A(), A(), B() as m, A() as n, B(), B() as o: # type: int, Tuple[int, int] # E: Incompatible number of types for "with" targets
1601 pass
1602
1603 with A(), B(), B() as p, A(), A(): # type: str
1604 pass
1605 [builtins fixtures/tuple.pyi]
1606
1607 [case testWithStmtBoolExitReturnWithResultFalse]
1608 from typing import Optional
1609
1610 class InvalidReturn1:
1611 def __exit__(self, x, y, z) -> bool: # E: "bool" is invalid as return type for "__exit__" that always returns False \
1612 # N: Use "typing.Literal[False]" as the return type or change it to "None" \
1613 # N: If return type of "__exit__" implies that it may return True, the context manager may swallow exceptions
1614 return False
1615
1616 class InvalidReturn2:
1617 def __exit__(self, x, y, z) -> Optional[bool]: # E: "bool" is invalid as return type for "__exit__" that always returns False \
1618 # N: Use "typing.Literal[False]" as the return type or change it to "None" \
1619 # N: If return type of "__exit__" implies that it may return True, the context manager may swallow exceptions
1620 if int():
1621 return False
1622 else:
1623 return False
1624
1625 class InvalidReturn3:
1626 def __exit__(self, x, y, z) -> bool: # E: "bool" is invalid as return type for "__exit__" that always returns False \
1627 # N: Use "typing.Literal[False]" as the return type or change it to "None" \
1628 # N: If return type of "__exit__" implies that it may return True, the context manager may swallow exceptions
1629 def nested() -> bool:
1630 return True
1631 return False
1632 [builtins fixtures/bool.pyi]
1633
1634 [case testWithStmtBoolExitReturnOkay]
1635 from typing import Literal
1636
1637 class GoodReturn1:
1638 def __exit__(self, x, y, z) -> bool:
1639 if int():
1640 return True
1641 else:
1642 return False
1643
1644 class GoodReturn2:
1645 def __exit__(self, x, y, z) -> bool:
1646 if int():
1647 return False
1648 else:
1649 return True
1650
1651 class GoodReturn3:
1652 def __exit__(self, x, y, z) -> bool:
1653 return bool()
1654
1655 class GoodReturn4:
1656 def __exit__(self, x, y, z) -> None:
1657 return
1658
1659 class GoodReturn5:
1660 def __exit__(self, x, y, z) -> None:
1661 return None
1662
1663 class GoodReturn6:
1664 def exit(self, x, y, z) -> bool:
1665 return False
1666
1667 class GoodReturn7:
1668 def exit(self, x, y, z) -> bool:
1669 pass
1670
1671 class MissingReturn:
1672 def exit(self, x, y, z) -> bool: # E: Missing return statement
1673 x = 0
1674
1675 class LiteralReturn:
1676 def __exit__(self, x, y, z) -> Literal[False]:
1677 return False
1678 [builtins fixtures/bool.pyi]
1679
1680 [case testWithStmtBoolExitReturnInStub]
1681 import stub
1682
1683 [file stub.pyi]
1684 from typing import Optional
1685
1686 class C1:
1687 def __exit__(self, x, y, z) -> bool: ...
1688
1689 class C2:
1690 def __exit__(self, x, y, z) -> bool: pass
1691
1692 class C3:
1693 def __exit__(self, x, y, z) -> Optional[bool]: pass
1694 [builtins fixtures/bool.pyi]
1695
1696 [case testWithStmtScopeBasics]
1697 from m import A, B
1698
1699 def f1() -> None:
1700 with A() as x:
1701 reveal_type(x) # N: Revealed type is "m.A"
1702 with B() as x:
1703 reveal_type(x) # N: Revealed type is "m.B"
1704
1705 def f2() -> None:
1706 with A() as x:
1707 reveal_type(x) # N: Revealed type is "m.A"
1708 y = x # Use outside with makes the scope function-level
1709 with B() as x: \
1710 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1711 reveal_type(x) # N: Revealed type is "m.A"
1712
1713 [file m.pyi]
1714 class A:
1715 def __enter__(self) -> A: ...
1716 def __exit__(self, x, y, z) -> None: ...
1717 class B:
1718 def __enter__(self) -> B: ...
1719 def __exit__(self, x, y, z) -> None: ...
1720
1721 [case testWithStmtScopeAndFuncDef]
1722 from m import A, B
1723
1724 with A() as x:
1725 reveal_type(x) # N: Revealed type is "m.A"
1726
1727 def f() -> None:
1728 pass # Don't support function definition in the middle
1729
1730 with B() as x: \
1731 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1732 reveal_type(x) # N: Revealed type is "m.A"
1733
1734 [file m.pyi]
1735 class A:
1736 def __enter__(self) -> A: ...
1737 def __exit__(self, x, y, z) -> None: ...
1738 class B:
1739 def __enter__(self) -> B: ...
1740 def __exit__(self, x, y, z) -> None: ...
1741
1742 [case testWithStmtScopeAndFuncDef2]
1743 from m import A, B
1744
1745 def f() -> None:
1746 pass # function before with is unsupported
1747
1748 with A() as x:
1749 reveal_type(x) # N: Revealed type is "m.A"
1750
1751 with B() as x: \
1752 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1753 reveal_type(x) # N: Revealed type is "m.A"
1754
1755 [file m.pyi]
1756 class A:
1757 def __enter__(self) -> A: ...
1758 def __exit__(self, x, y, z) -> None: ...
1759 class B:
1760 def __enter__(self) -> B: ...
1761 def __exit__(self, x, y, z) -> None: ...
1762
1763 [case testWithStmtScopeAndFuncDef3]
1764 from m import A, B
1765
1766 with A() as x:
1767 reveal_type(x) # N: Revealed type is "m.A"
1768
1769 with B() as x: \
1770 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1771 reveal_type(x) # N: Revealed type is "m.A"
1772
1773 def f() -> None:
1774 pass # function after with is unsupported
1775
1776 [file m.pyi]
1777 class A:
1778 def __enter__(self) -> A: ...
1779 def __exit__(self, x, y, z) -> None: ...
1780 class B:
1781 def __enter__(self) -> B: ...
1782 def __exit__(self, x, y, z) -> None: ...
1783
1784 [case testWithStmtScopeAndFuncDef4]
1785 from m import A, B
1786
1787 with A() as x:
1788 def f() -> None:
1789 pass # Function within with is unsupported
1790
1791 reveal_type(x) # N: Revealed type is "m.A"
1792
1793 with B() as x: \
1794 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1795 reveal_type(x) # N: Revealed type is "m.A"
1796
1797 [file m.pyi]
1798 class A:
1799 def __enter__(self) -> A: ...
1800 def __exit__(self, x, y, z) -> None: ...
1801 class B:
1802 def __enter__(self) -> B: ...
1803 def __exit__(self, x, y, z) -> None: ...
1804
1805 [case testWithStmtScopeAndImport1]
1806 from m import A, B, x
1807
1808 with A() as x: \
1809 # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1810 reveal_type(x) # N: Revealed type is "m.B"
1811
1812 with B() as x:
1813 reveal_type(x) # N: Revealed type is "m.B"
1814
1815 [file m.pyi]
1816 x: B
1817
1818 class A:
1819 def __enter__(self) -> A: ...
1820 def __exit__(self, x, y, z) -> None: ...
1821 class B:
1822 def __enter__(self) -> B: ...
1823 def __exit__(self, x, y, z) -> None: ...
1824
1825 [case testWithStmtScopeAndImport2]
1826 from m import A, B
1827 import m as x
1828
1829 with A() as x: \
1830 # E: Incompatible types in assignment (expression has type "A", variable has type Module)
1831 pass
1832
1833 with B() as x: \
1834 # E: Incompatible types in assignment (expression has type "B", variable has type Module)
1835 pass
1836
1837 [file m.pyi]
1838 class A:
1839 def __enter__(self) -> A: ...
1840 def __exit__(self, x, y, z) -> None: ...
1841 class B:
1842 def __enter__(self) -> B: ...
1843 def __exit__(self, x, y, z) -> None: ...
1844 [builtins fixtures/module.pyi]
1845
1846 [case testWithStmtScopeAndImportStar]
1847 from m import A, B
1848 from m import *
1849
1850 with A() as x:
1851 pass
1852
1853 with B() as x: \
1854 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1855 pass
1856
1857 [file m.pyi]
1858 class A:
1859 def __enter__(self) -> A: ...
1860 def __exit__(self, x, y, z) -> None: ...
1861 class B:
1862 def __enter__(self) -> B: ...
1863 def __exit__(self, x, y, z) -> None: ...
1864
1865 [case testWithStmtScopeNestedWith1]
1866 from m import A, B
1867
1868 with A() as x:
1869 with B() as x: \
1870 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1871 reveal_type(x) # N: Revealed type is "m.A"
1872
1873 with B() as x:
1874 with A() as x: \
1875 # E: Incompatible types in assignment (expression has type "A", variable has type "B")
1876 reveal_type(x) # N: Revealed type is "m.B"
1877
1878 [file m.pyi]
1879 class A:
1880 def __enter__(self) -> A: ...
1881 def __exit__(self, x, y, z) -> None: ...
1882 class B:
1883 def __enter__(self) -> B: ...
1884 def __exit__(self, x, y, z) -> None: ...
1885
1886 [case testWithStmtScopeNestedWith2]
1887 from m import A, B
1888
1889 with A() as x:
1890 with A() as y:
1891 reveal_type(y) # N: Revealed type is "m.A"
1892 with B() as y:
1893 reveal_type(y) # N: Revealed type is "m.B"
1894
1895 [file m.pyi]
1896 class A:
1897 def __enter__(self) -> A: ...
1898 def __exit__(self, x, y, z) -> None: ...
1899 class B:
1900 def __enter__(self) -> B: ...
1901 def __exit__(self, x, y, z) -> None: ...
1902
1903 [case testWithStmtScopeInnerAndOuterScopes]
1904 from m import A, B
1905
1906 x = A() # Outer scope should have no impact
1907
1908 with A() as x:
1909 pass
1910
1911 def f() -> None:
1912 with A() as x:
1913 reveal_type(x) # N: Revealed type is "m.A"
1914 with B() as x:
1915 reveal_type(x) # N: Revealed type is "m.B"
1916
1917 y = x
1918
1919 with A() as x:
1920 pass
1921
1922 [file m.pyi]
1923 class A:
1924 def __enter__(self) -> A: ...
1925 def __exit__(self, x, y, z) -> None: ...
1926 class B:
1927 def __enter__(self) -> B: ...
1928 def __exit__(self, x, y, z) -> None: ...
1929
1930 [case testWithStmtScopeMultipleContextManagers]
1931 from m import A, B
1932
1933 with A() as x, B() as y:
1934 reveal_type(x) # N: Revealed type is "m.A"
1935 reveal_type(y) # N: Revealed type is "m.B"
1936 with B() as x, A() as y:
1937 reveal_type(x) # N: Revealed type is "m.B"
1938 reveal_type(y) # N: Revealed type is "m.A"
1939
1940 [file m.pyi]
1941 class A:
1942 def __enter__(self) -> A: ...
1943 def __exit__(self, x, y, z) -> None: ...
1944 class B:
1945 def __enter__(self) -> B: ...
1946 def __exit__(self, x, y, z) -> None: ...
1947
1948 [case testWithStmtScopeMultipleAssignment]
1949 from m import A, B
1950
1951 with A() as (x, y):
1952 reveal_type(x) # N: Revealed type is "m.A"
1953 reveal_type(y) # N: Revealed type is "builtins.int"
1954 with B() as [x, y]:
1955 reveal_type(x) # N: Revealed type is "m.B"
1956 reveal_type(y) # N: Revealed type is "builtins.str"
1957
1958 [file m.pyi]
1959 from typing import Tuple
1960
1961 class A:
1962 def __enter__(self) -> Tuple[A, int]: ...
1963 def __exit__(self, x, y, z) -> None: ...
1964 class B:
1965 def __enter__(self) -> Tuple[B, str]: ...
1966 def __exit__(self, x, y, z) -> None: ...
1967 [builtins fixtures/tuple.pyi]
1968
1969 [case testWithStmtScopeComplexAssignments]
1970 from m import A, B, f
1971
1972 with A() as x:
1973 pass
1974 with B() as x: \
1975 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1976 pass
1977 with B() as f(x).x:
1978 pass
1979
1980 with A() as y:
1981 pass
1982 with B() as y: \
1983 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
1984 pass
1985 with B() as f(y)[0]:
1986 pass
1987
1988 [file m.pyi]
1989 def f(x): ...
1990
1991 class A:
1992 def __enter__(self) -> A: ...
1993 def __exit__(self, x, y, z) -> None: ...
1994 class B:
1995 def __enter__(self) -> B: ...
1996 def __exit__(self, x, y, z) -> None: ...
1997
1998 [case testWithStmtScopeAndClass]
1999 from m import A, B
2000
2001 with A() as x:
2002 pass
2003
2004 class C:
2005 with A() as y:
2006 pass
2007 with B() as y:
2008 pass
2009
2010 with B() as x: \
2011 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2012 pass
2013
2014 [file m.pyi]
2015 class A:
2016 def __enter__(self) -> A: ...
2017 def __exit__(self, x, y, z) -> None: ...
2018 class B:
2019 def __enter__(self) -> B: ...
2020 def __exit__(self, x, y, z) -> None: ...
2021
2022 [case testWithStmtScopeInnerScopeReference]
2023 from m import A, B
2024
2025 with A() as x:
2026 def f() -> A:
2027 return x
2028 f()
2029
2030 with B() as x: \
2031 # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2032 pass
2033 [file m.pyi]
2034 class A:
2035 def __enter__(self) -> A: ...
2036 def __exit__(self, x, y, z) -> None: ...
2037 class B:
2038 def __enter__(self) -> B: ...
2039 def __exit__(self, x, y, z) -> None: ...
2040
2041 [case testWithStmtScopeAndLambda]
2042 from m import A, B
2043
2044 # This is technically not correct, since the lambda can outlive the with
2045 # statement, but this behavior seems more intuitive.
2046
2047 with A() as x:
2048 lambda: reveal_type(x) # N: Revealed type is "m.A"
2049
2050 with B() as x:
2051 pass
2052 [file m.pyi]
2053 class A:
2054 def __enter__(self) -> A: ...
2055 def __exit__(self, x, y, z) -> None: ...
2056 class B:
2057 def __enter__(self) -> B: ...
2058 def __exit__(self, x, y, z) -> None: ...
2059
2060
2061 -- Chained assignment
2062 -- ------------------
2063
2064
2065 [case testChainedAssignment]
2066 import typing
2067 class A: pass
2068 class B: pass
2069 x = y = A()
2070 if int():
2071 x = A()
2072 if int():
2073 y = A()
2074 if int():
2075 x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2076 if int():
2077 y = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2078
2079 [case testChainedAssignment2]
2080 import typing
2081 def f() -> None:
2082 x = 1
2083 y = 'x'
2084 if int():
2085 x = y = 'x' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2086 x = y = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2087 [builtins fixtures/primitives.pyi]
2088 [out]
2089
2090 [case testChainedAssignmentWithType]
2091 # flags: --no-strict-optional
2092 x = y = None # type: int
2093 if int():
2094 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2095 if int():
2096 y = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2097 if int():
2098 x = 1
2099 if int():
2100 y = 1
2101
2102
2103 -- Star assignment
2104 -- ---------------
2105
2106
2107 [case testAssignListToStarExpr]
2108 from typing import List
2109 bs: List[A]
2110 cs: List[B]
2111 if int():
2112 *bs, b = bs
2113 if int():
2114 *bs, c = cs # E: Incompatible types in assignment (expression has type "list[B]", variable has type "list[A]")
2115 if int():
2116 *ns, c = cs
2117 if int():
2118 nc = cs
2119
2120 class A: pass
2121 class B: pass
2122 [builtins fixtures/list.pyi]
2123
2124
2125 -- Type aliases
2126 -- ------------
2127
2128
2129 [case testSimpleTypeAlias]
2130 import typing
2131 foo = int
2132 def f(x: foo) -> None: pass
2133 f(1)
2134 f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
2135
2136 [case testTypeAliasDefinedInAModule]
2137 import typing
2138 import m
2139 def f(x: m.foo) -> None: pass
2140 f(1)
2141 f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
2142 [file m.py]
2143 import typing
2144 foo = int
2145
2146 [case testTypeAliasDefinedInAModule2]
2147 import typing
2148 from m import foo
2149 def f(x: foo) -> None: pass
2150 f(1)
2151 f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
2152 [file m.py]
2153 import typing
2154 foo = int
2155
2156
2157 -- nonlocal and global
2158 -- -------------------
2159
2160
2161 [case testTypeOfGlobalUsed]
2162 import typing
2163 class A(): pass
2164 class B(): pass
2165 g = A()
2166 def f() -> None:
2167 global g
2168 g = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
2169 [case testTypeOfNonlocalUsed]
2170 import typing
2171 def f() -> None:
2172 a = A()
2173 def g() -> None:
2174 nonlocal a
2175 a = B()
2176
2177 class A(): pass
2178 class B(): pass
2179 [out]
2180 main:6: error: Incompatible types in assignment (expression has type "B", variable has type "A")
2181
2182 [case testTypeOfOuterMostNonlocalUsed]
2183 import typing
2184 def f() -> None:
2185 a = A()
2186 def g() -> None:
2187 a = B()
2188 def h() -> None:
2189 nonlocal a
2190 a = A()
2191 a = B()
2192
2193 class A(): pass
2194 class B(): pass
2195 [out]
2196 main:8: error: Incompatible types in assignment (expression has type "A", variable has type "B")
2197
2198 [case testAugmentedAssignmentIntFloat]
2199 weight0 = 65.5
2200 reveal_type(weight0) # N: Revealed type is "builtins.float"
2201 if int():
2202 weight0 = 65
2203 reveal_type(weight0) # N: Revealed type is "builtins.int"
2204 weight0 *= 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "float")
2205 weight0 *= 0.5
2206 reveal_type(weight0) # N: Revealed type is "builtins.float"
2207 weight0 *= object() # E: Unsupported operand types for * ("float" and "object")
2208 reveal_type(weight0) # N: Revealed type is "builtins.float"
2209
2210 [builtins fixtures/float.pyi]
2211
2212 [case testAugmentedAssignmentIntFloatMember]
2213 class A:
2214 def __init__(self) -> None:
2215 self.weight0 = 65.5
2216 reveal_type(self.weight0) # N: Revealed type is "builtins.float"
2217 self.weight0 = 65
2218 reveal_type(self.weight0) # N: Revealed type is "builtins.int"
2219 self.weight0 *= 'a' # E: Incompatible types in assignment (expression has type "str", variable has type "float")
2220 self.weight0 *= 0.5
2221 reveal_type(self.weight0) # N: Revealed type is "builtins.float"
2222 self.weight0 *= object() # E: Unsupported operand types for * ("float" and "object")
2223 reveal_type(self.weight0) # N: Revealed type is "builtins.float"
2224
2225 [builtins fixtures/float.pyi]
2226
2227 [case testAugmentedAssignmentIntFloatDict]
2228 from typing import Dict
2229 d = {'weight0': 65.5}
2230 reveal_type(d['weight0']) # N: Revealed type is "builtins.float"
2231 d['weight0'] = 65
2232 reveal_type(d['weight0']) # N: Revealed type is "builtins.float"
2233 d['weight0'] *= 'a' # E: Unsupported operand types for * ("float" and "str")
2234 d['weight0'] *= 0.5
2235 reveal_type(d['weight0']) # N: Revealed type is "builtins.float"
2236 d['weight0'] *= object() # E: Unsupported operand types for * ("float" and "object")
2237 reveal_type(d['weight0']) # N: Revealed type is "builtins.float"
2238
2239 [builtins fixtures/floatdict.pyi]
2240
2241 [case testForwardRefsInForStatementImplicit]
2242 from typing import List, NamedTuple
2243 lst: List[N]
2244
2245 for i in lst:
2246 reveal_type(i.x) # N: Revealed type is "builtins.int"
2247 a: str = i[0] # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2248
2249 N = NamedTuple('N', [('x', int)])
2250 [builtins fixtures/list.pyi]
2251 [out]
2252
2253 [case testForwardRefsInForStatement]
2254 from typing import List, NamedTuple
2255 lst: List[M]
2256
2257 for i in lst: # type: N
2258 reveal_type(i.x) # N: Revealed type is "builtins.int"
2259 a: str = i[0] # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2260
2261 N = NamedTuple('N', [('x', int)])
2262 class M(N): pass
2263 [builtins fixtures/list.pyi]
2264 [out]
2265
2266 [case testForwardRefsInWithStatementImplicit]
2267 from typing import ContextManager, Any, TypedDict
2268 cm: ContextManager[N]
2269
2270 with cm as g:
2271 a: int = g['x']
2272
2273 N = TypedDict('N', {'x': int})
2274 [builtins fixtures/dict.pyi]
2275 [typing fixtures/typing-full.pyi]
2276 [out]
2277
2278 [case testForwardRefsInWithStatement_no_native_parse]
2279 from typing import ContextManager, Any, TypedDict
2280 cm: ContextManager[Any]
2281
2282 with cm as g: # type: N
2283 a: str = g['x'] # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2284
2285 N = TypedDict('N', {'x': int})
2286 [builtins fixtures/dict.pyi]
2287 [typing fixtures/typing-full.pyi]
2288 [out]
2289
2290 [case testGlobalWithoutInitialization]
2291 # flags: --disable-error-code=annotation-unchecked
2292 from typing import List
2293
2294 def foo() -> None:
2295 global bar
2296 # TODO: Confusing error message
2297 bar = [] # type: List[str] # E: Name "bar" already defined (possibly by an import)
2298 bar # E: Name "bar" is not defined
2299
2300 def foo2():
2301 global bar2
2302 bar2 = [] # type: List[str]
2303 bar2
2304 [builtins fixtures/list.pyi]
2305
2306 [case testNoteUncheckedAnnotation]
2307 def foo():
2308 x: int = "no" # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
2309 y = "no" # type: int # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
2310 z: int # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
2311
2312 [case testGeneratorUnion]
2313 from typing import Generator, Union
2314
2315 class A: pass
2316 class B: pass
2317
2318 def foo(x: int) -> Union[Generator[A, None, None], Generator[B, None, None]]:
2319 yield x # E: Incompatible types in "yield" (actual type "int", expected type "A | B")
2320
2321 [case testYieldFromUnionOfGenerators]
2322 from typing import Generator, Union
2323
2324 class T: pass
2325
2326 def foo(arg: Union[Generator[int, None, T], Generator[str, None, T]]) -> Generator[Union[int, str], None, T]:
2327 return (yield from arg)
2328
2329 [case testYieldFromInvalidUnionReturn]
2330 from typing import Generator, Union
2331
2332 class A: pass
2333 class B: pass
2334
2335 def foo(arg: Union[A, B]) -> Generator[Union[int, str], None, A]:
2336 return (yield from arg) # E: "yield from" can't be applied to "A | B"
2337
2338 [case testYieldFromUnionOfGeneratorWithIterableStr]
2339 from typing import Generator, Union, Iterable, Optional
2340
2341 def foo(arg: Union[Generator[int, None, bytes], Iterable[str]]) -> Generator[Union[int, str], None, Optional[bytes]]:
2342 return (yield from arg)
2343
2344 def bar(arg: Generator[str, None, str]) -> Generator[str, None, str]:
2345 return foo(arg) # E: Incompatible return value type (got "Generator[int | str, None, bytes | None]", expected "Generator[str, None, str]")
2346
2347 def launder(arg: Iterable[str]) -> Generator[Union[int, str], None, Optional[bytes]]:
2348 return foo(arg)
2349
2350 def baz(arg: Generator[str, None, str]) -> Generator[Union[int, str], None, Optional[bytes]]:
2351 # this is unsound, the Generator return type will actually be str
2352 return launder(arg)
2353 [builtins fixtures/tuple.pyi]
2354
2355 [case testYieldIteratorReturn]
2356 from typing import Iterator
2357
2358 def get_strings(foo: bool) -> Iterator[str]:
2359 if foo:
2360 return ["foo1", "foo2"] # E: No return value expected
2361 else:
2362 yield "bar1"
2363 yield "bar2"
2364 [builtins fixtures/tuple.pyi]
2365
2366 [case testYieldFromInvalidType]
2367 from collections.abc import Iterator
2368
2369 class A:
2370 def list(self) -> None: ...
2371
2372 def foo(self) -> list[int]: # E: Function "__main__.A.list" is not valid as a type \
2373 # N: Perhaps you need "Callable[...]" or a callback protocol?
2374 return []
2375
2376 def fn() -> Iterator[int]:
2377 yield from A().foo() # E: "list?[builtins.int]" has no attribute "__iter__" (not iterable)
2378 [builtins fixtures/tuple.pyi]
2379
2380 [case testNoCrashOnStarRightHandSide]
2381 x = *(1, 2, 3) # E: can't use starred expression here
2382 [builtins fixtures/tuple.pyi]
2383
2384
2385 [case testTypingExtensionsSuggestion]
2386 from typing import _FutureFeatureFixture
2387
2388 # This import is only needed in tests. In real life, mypy will always have typing_extensions in its
2389 # build due to its pervasive use in typeshed. This assumption may one day prove False, but when
2390 # that day comes this suggestion will also be less helpful than it is today.
2391 import typing_extensions
2392 [out]
2393 main:1: error: Module "typing" has no attribute "_FutureFeatureFixture"
2394 main:1: note: Use `from typing_extensions import _FutureFeatureFixture` instead
2395 main:1: note: See https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module
2396 [builtins fixtures/tuple.pyi]
2397
2398 [case testNoCrashOnBreakOutsideLoopFunction]
2399 def foo():
2400 for x in [1, 2]:
2401 def inner():
2402 break # E: "break" outside loop
2403 [builtins fixtures/list.pyi]
2404
2405 [case testNoCrashOnBreakOutsideLoopClass]
2406 class Outer:
2407 for x in [1, 2]:
2408 class Inner:
2409 break # E: "break" outside loop
2410 [builtins fixtures/list.pyi]
2411
2412 [case testCallableInstanceOverlapAllowed]
2413 # flags: --warn-unreachable
2414 from typing import Any, Callable, List
2415
2416 class CAny:
2417 def __call__(self) -> Any: ...
2418 class CNone:
2419 def __call__(self) -> None: ...
2420 class CWrong:
2421 def __call__(self, x: int) -> None: ...
2422
2423 def describe(func: Callable[[], None]) -> str:
2424 if isinstance(func, CAny):
2425 return "CAny"
2426 elif isinstance(func, CNone):
2427 return "CNone"
2428 elif isinstance(func, CWrong):
2429 return "CWrong" # E: Statement is unreachable
2430 else:
2431 return "other"
2432
2433 class C(CAny):
2434 def __call__(self) -> None: ...
2435
2436 def f():
2437 pass
2438
2439 describe(CAny())
2440 describe(C())
2441 describe(CNone())
2442 describe(CWrong()) # E: Argument 1 to "describe" has incompatible type "CWrong"; expected "Callable[[], None]" \
2443 # N: "CWrong.__call__" has type "def __call__(self, x: int) -> None"
2444 describe(f)
2445 [builtins fixtures/isinstancelist.pyi]