Debian Codegraph @

test-data/unit/check-flags.test

raw
1 [case testUnannotatedFunction]
2 # flags: --disallow-untyped-defs
3 def f(x): pass
4 [out]
5 main:2: error: Function is missing a type annotation
6
7 [case testUnannotatedArgument]
8 # flags: --disallow-untyped-defs
9 def f(x) -> int: pass
10 [out]
11 main:2: error: Function is missing a type annotation for one or more parameters
12
13 [case testNoArgumentFunction]
14 # flags: --disallow-untyped-defs
15 def f() -> int: pass
16 [out]
17
18 [case testUnannotatedReturn]
19 # flags: --disallow-untyped-defs
20 def f(x: int): pass
21 [out]
22 main:2: error: Function is missing a return type annotation
23
24 [case testUnannotatedReturnWithFastParser]
25 # flags: --disallow-untyped-defs
26 def f(x: int): pass
27 [out]
28 main:2: error: Function is missing a return type annotation
29
30 [case testLambda]
31 # flags: --disallow-untyped-defs
32 lambda x: x
33 [out]
34
35 [case testUntypedDef]
36 # flags: --disallow-untyped-defs
37 def f():
38 1 + "str"
39 [out]
40 main:2: error: Function is missing a return type annotation
41 main:2: note: Use "-> None" if function does not return a value
42
43 [case testUnannotatedReturnWithOnlySelfArgument]
44 # flags: --disallow-untyped-defs
45 def f(self): pass
46 [out]
47 main:2: error: Function is missing a return type annotation
48 main:2: note: Use "-> None" if function does not return a value
49
50 [case testUnannotatedReturnWithNontrivialReturn]
51 # flags: --disallow-untyped-defs
52 def f(): return 1
53 [out]
54 main:2: error: Function is missing a return type annotation
55
56 [case testUntypedAsyncDef]
57 # flags: --disallow-untyped-defs
58 async def f(): # E: Function is missing a return type annotation \
59 # N: Use "-> None" if function does not return a value
60 pass
61 [builtins fixtures/async_await.pyi]
62 [typing fixtures/typing-medium.pyi]
63
64 [case testAsyncUnannotatedArgument]
65 # flags: --disallow-untyped-defs
66 async def f(x) -> None: # E: Function is missing a type annotation for one or more parameters
67 pass
68 [builtins fixtures/async_await.pyi]
69 [typing fixtures/typing-async.pyi]
70
71 [case testAsyncUnannotatedReturn]
72 # flags: --disallow-untyped-defs
73 from typing import Any
74 async def f(x: int): # E: Function is missing a return type annotation
75 pass
76 # Make sure explicit Any is allowed.
77 async def g(x: int) -> Any:
78 pass
79 [builtins fixtures/async_await.pyi]
80 [typing fixtures/typing-async.pyi]
81
82 [case testDisallowUntypedDefsAndGeneric]
83 # flags: --disallow-untyped-defs --disallow-any-generics
84 def get_tasks(self):
85 return 'whatever'
86 [out]
87 main:2: error: Function is missing a return type annotation
88
89 [case testDisallowUntypedDefsUntypedDecorator]
90 # flags: --disallow-untyped-decorators
91 def d(p):
92 return p
93
94 @d # E: Untyped decorator makes function "f" untyped
95 def f(i: int) -> int:
96 return i
97
98 [case testDisallowUntypedDecoratorsUnresolvedDecorator]
99 # flags: --disallow-untyped-decorators --ignore-missing-imports
100 from nonexistent import d
101
102 @d # E: Untyped decorator makes function "f" untyped
103 def f(i: int) -> int:
104 return i
105
106 [case testDisallowUntypedDecoratorUntypedDef]
107 # flags: --disallow-untyped-decorators
108
109 def d(p):
110 return p
111
112 @d # no error
113 def f(): pass
114
115 [case testDisallowUntypedDecoratorsPartialFunction]
116 # flags: --disallow-untyped-decorators
117
118 def d(p):
119 return p
120
121 @d # E: Untyped decorator makes function "f" untyped
122 def f(x) -> None: pass
123
124 @d # E: Untyped decorator makes function "g" untyped
125 def g(x, y: int): pass
126
127 @d # E: Untyped decorator makes function "h" untyped
128 def h(x: int): pass
129
130 [case testDisallowUntypedDecoratorsImpreciseDecorator]
131 # flags: --disallow-untyped-decorators
132 from typing import Any
133
134 def d(p) -> Any:
135 return p
136
137 @d # no error
138 def f() -> None: pass
139
140 [case testDisallowUntypedDecoratorsMultipleDecorators]
141 # flags: --disallow-untyped-decorators
142 from typing import Any
143
144 def d1(p):
145 return p
146 def d2(p):
147 return p
148 def d3(p) -> Any:
149 return p
150
151 @d1 # E: Untyped decorator makes function "f" untyped
152 @d2 # E: Untyped decorator makes function "f" untyped
153 @d3 # no error
154 @d1 # E: Untyped decorator makes function "f" untyped
155 def f() -> None: pass
156
157 [case testDisallowUntypedDecoratorsCallableInstance]
158 # flags: --disallow-untyped-decorators
159 from typing import Callable
160
161 class TypedDecorator:
162 def __call__(self, c: Callable) -> Callable:
163 return function
164
165 class UntypedDecorator:
166 def __call__(self, c):
167 return function
168
169 @TypedDecorator()
170 def f() -> None: pass
171
172 @UntypedDecorator() # E: Untyped decorator makes function "g" untyped
173 def g() -> None: pass
174
175 @TypedDecorator()
176 @UntypedDecorator() # E: Untyped decorator makes function "h" untyped
177 def h() -> None: pass
178
179 @UntypedDecorator() # E: Untyped decorator makes function "i" untyped
180 @TypedDecorator()
181 def i() -> None: pass
182
183 reveal_type(f) # N: Revealed type is "def (*Any, **Any) -> Any"
184 reveal_type(g) # N: Revealed type is "Any"
185 reveal_type(h) # N: Revealed type is "def (*Any, **Any) -> Any"
186 reveal_type(i) # N: Revealed type is "Any"
187
188 [case testDisallowUntypedDecoratorsCallableInstanceDecoratedCall]
189 # flags: --disallow-untyped-decorators
190 from typing import Callable, TypeVar
191
192 C = TypeVar('C', bound=Callable)
193
194 def typed_decorator(c: C) -> C:
195 return c
196
197 def untyped_decorator(c):
198 return c
199
200 class TypedDecorator:
201 @typed_decorator
202 def __call__(self, c: Callable) -> Callable:
203 return function
204
205 class UntypedDecorator1:
206 @untyped_decorator
207 def __call__(self, c):
208 return function
209
210 class UntypedDecorator2:
211 @untyped_decorator # E: Untyped decorator makes function "__call__" untyped
212 def __call__(self, c: Callable) -> Callable:
213 return function
214
215 class UntypedDecorator3:
216 @typed_decorator
217 @untyped_decorator # E: Untyped decorator makes function "__call__" untyped
218 def __call__(self, c: Callable) -> Callable:
219 return function
220
221 class UntypedDecorator4:
222 @untyped_decorator # E: Untyped decorator makes function "__call__" untyped
223 @typed_decorator
224 def __call__(self, c: Callable) -> Callable:
225 return function
226
227 @TypedDecorator()
228 def f() -> None: pass
229
230 @UntypedDecorator1() # E: Untyped decorator makes function "g1" untyped
231 def g1() -> None: pass
232
233 @UntypedDecorator2() # E: Untyped decorator makes function "g2" untyped
234 def g2() -> None: pass
235
236 @UntypedDecorator3() # E: Untyped decorator makes function "g3" untyped
237 def g3() -> None: pass
238
239 @UntypedDecorator4() # E: Untyped decorator makes function "g4" untyped
240 def g4() -> None: pass
241
242 reveal_type(f) # N: Revealed type is "def (*Any, **Any) -> Any"
243 reveal_type(g1) # N: Revealed type is "Any"
244 reveal_type(g2) # N: Revealed type is "Any"
245 reveal_type(g3) # N: Revealed type is "Any"
246 reveal_type(g4) # N: Revealed type is "Any"
247 [builtins fixtures/bool.pyi]
248
249 [case testDisallowUntypedDecoratorsNonCallableInstance]
250 # flags: --disallow-untyped-decorators
251 class Decorator:
252 pass
253
254 @Decorator() # E: "Decorator" not callable
255 def f() -> None: pass
256
257 [case testSubclassingAny]
258 # flags: --disallow-subclassing-any
259 from typing import Any
260 FakeClass = None # type: Any
261 class Foo(FakeClass): pass # E: Class cannot subclass "FakeClass" (has type "Any")
262 [out]
263
264 [case testSubclassingAnyMultipleBaseClasses]
265 # flags: --disallow-subclassing-any
266 from typing import Any
267 FakeClass = None # type: Any
268 class ActualClass: pass
269 class Foo(ActualClass, FakeClass): pass # E: Class cannot subclass "FakeClass" (has type "Any")
270 [out]
271
272 [case testSubclassingAnySilentImports]
273 # flags: --disallow-subclassing-any --follow-imports=skip
274 # cmd: mypy -m main
275
276 [file main.py]
277 from ignored_module import BaseClass
278 class Foo(BaseClass): pass
279
280 [file ignored_module.py]
281 class BaseClass: pass
282
283 [out]
284 tmp/main.py:2: error: Class cannot subclass "BaseClass" (has type "Any")
285
286 [case testSubclassingAnySilentImports2]
287 # flags: --disallow-subclassing-any --follow-imports=skip
288 # cmd: mypy -m main
289
290 [file main.py]
291 import ignored_module
292 class Foo(ignored_module.BaseClass): pass
293
294 [file ignored_module.py]
295 class BaseClass: pass
296
297 [out]
298 tmp/main.py:2: error: Class cannot subclass "BaseClass" (has type "Any")
299
300 [case testWarnNoReturnIgnoresTrivialFunctions]
301 # flags: --warn-no-return
302 def f() -> int:
303 pass
304 def g() -> int:
305 ...
306 def h() -> int:
307 """with docstring"""
308 pass
309 def i() -> int:
310 """with docstring"""
311 ...
312 def j() -> int:
313 u"""with unicode docstring"""
314 pass
315 def k() -> int:
316 """docstring only"""
317
318 [case testWarnNoReturnWorksWithAlwaysTrue]
319 # flags: --warn-no-return
320 PY3 = True
321 def f() -> int:
322 if PY3:
323 return 0
324 else:
325 return 0
326 [builtins fixtures/bool.pyi]
327
328 [case testWarnNoReturnWorksWithAlwaysFalse]
329 # flags: --warn-no-return
330 PY2 = False
331 def f() -> int:
332 if PY2:
333 return 0
334 else:
335 return 0
336 [builtins fixtures/bool.pyi]
337
338 [case testWarnNoReturnWorksWithMypyTrue]
339 # flags: --warn-no-return
340 MYPY = False
341 def f() -> int:
342 if MYPY:
343 return 0
344 else:
345 return 0
346 [builtins fixtures/bool.pyi]
347
348 [case testNoReturnDisallowsReturn]
349 # flags: --warn-no-return
350 from typing import NoReturn
351
352 def f() -> NoReturn:
353 if bool():
354 return 5 # E: Return statement in function which does not return
355 else:
356 return # E: Return statement in function which does not return
357 [builtins fixtures/dict.pyi]
358
359 [case testNoReturnWithoutImplicitReturn]
360 # flags: --warn-no-return
361 from typing import NoReturn
362
363 def no_return() -> NoReturn: pass
364 def f() -> NoReturn:
365 no_return()
366 [builtins fixtures/dict.pyi]
367
368 [case testNoReturnDisallowsImplicitReturn]
369 # flags: --warn-no-return
370 from typing import NoReturn
371
372 def f() -> NoReturn: # E: Implicit return in function which does not return
373 non_trivial_function = 1
374 [builtins fixtures/dict.pyi]
375
376 [case testNoReturnImplicitReturnCheckInDeferredNode]
377 # flags: --warn-no-return
378 from typing import NoReturn
379
380 def exit() -> NoReturn: ...
381
382 def force_forward_reference() -> int:
383 return 4
384
385 def f() -> NoReturn:
386 x
387 exit()
388
389 x = force_forward_reference()
390 [builtins fixtures/exception.pyi]
391
392 [case testNoReturnNoWarnNoReturn]
393 # flags: --warn-no-return
394 from typing import NoReturn
395
396 def no_return() -> NoReturn: pass
397 def f() -> int:
398 if bool():
399 return 0
400 else:
401 no_return()
402 [builtins fixtures/dict.pyi]
403
404 [case testNoReturnInExpr]
405 # flags: --warn-no-return
406 from typing import NoReturn
407
408 def no_return() -> NoReturn: pass
409 def f() -> int:
410 return 0
411 reveal_type(f() or no_return()) # N: Revealed type is "builtins.int"
412 [builtins fixtures/dict.pyi]
413
414 [case testNoReturnVariable]
415 # flags: --warn-no-return
416 from typing import NoReturn
417
418 x = 0 # type: NoReturn # E: Incompatible types in assignment (expression has type "int", variable has type "Never")
419 [builtins fixtures/dict.pyi]
420
421 [case testNoReturnAsync]
422 # flags: --warn-no-return
423 from typing import NoReturn
424
425 async def f() -> NoReturn: ...
426
427 async def g() -> NoReturn:
428 await f()
429
430 async def h() -> NoReturn: # E: Implicit return in function which does not return
431 # Purposely not evaluating coroutine
432 _ = f()
433 [builtins fixtures/dict.pyi]
434 [typing fixtures/typing-async.pyi]
435
436 [case testNoWarnNoReturn]
437 # flags: --no-warn-no-return
438 import typing
439
440 def implicit_optional_return(arg) -> typing.Optional[str]:
441 if arg:
442 return "false"
443
444 def unsound_implicit_return(arg) -> str: # E: Incompatible return value type (implicitly returns "None", expected "str")
445 if arg:
446 return "false"
447
448 def implicit_return_gen(arg) -> typing.Generator[int, None, typing.Optional[str]]:
449 yield 1
450
451 def unsound_implicit_return_gen(arg) -> typing.Generator[int, None, str]: # E: Incompatible return value type (implicitly returns "None", expected "str")
452 yield 1
453 [builtins fixtures/dict.pyi]
454
455 [case testNoWarnNoReturnNoStrictOptional]
456 # flags: --no-warn-no-return --no-strict-optional
457 import typing
458
459 def implicit_optional_return(arg) -> typing.Optional[str]:
460 if arg:
461 return "false"
462
463 def unsound_implicit_return(arg) -> str:
464 if arg:
465 return "false"
466
467 def implicit_return_gen(arg) -> typing.Generator[int, None, typing.Optional[str]]:
468 yield 1
469
470 def unsound_implicit_return_gen(arg) -> typing.Generator[int, None, str]:
471 yield 1
472 [builtins fixtures/dict.pyi]
473
474 [case testNoReturnImportFromTyping]
475 from typing import NoReturn
476
477 def h() -> NoReturn:
478 if bool():
479 return 5 # E: Return statement in function which does not return
480 else:
481 return # E: Return statement in function which does not return
482
483 def no_return() -> NoReturn: pass
484 def f() -> NoReturn:
485 no_return()
486
487 x: NoReturn = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "Never")
488 [builtins fixtures/dict.pyi]
489
490 [case testShowErrorContextFunction]
491 # flags: --show-error-context
492 def f() -> None:
493 0 + ""
494 [out]
495 main: note: In function "f":
496 main:3: error: Unsupported operand types for + ("int" and "str")
497
498 [case testShowErrorContextClass]
499 # flags: --show-error-context
500 class A:
501 0 + ""
502 [out]
503 main: note: In class "A":
504 main:3: error: Unsupported operand types for + ("int" and "str")
505
506 [case testShowErrorContextMember]
507 # flags: --show-error-context
508 class A:
509 def f(self, x: int) -> None:
510 self.f("")
511 [out]
512 main: note: In member "f" of class "A":
513 main:4: error: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
514
515 [case testShowErrorContextModule]
516 # flags: --show-error-context
517 import m
518 [file m.py]
519 0 + ""
520 [out]
521 main:2: note: In module imported here:
522 tmp/m.py:1: error: Unsupported operand types for + ("int" and "str")
523
524 [case testShowErrorContextTopLevel]
525 # flags: --show-error-context
526 def f() -> None:
527 0 + ""
528 0 + ""
529 [out]
530 main: note: In function "f":
531 main:3: error: Unsupported operand types for + ("int" and "str")
532 main: note: At top level:
533 main:4: error: Unsupported operand types for + ("int" and "str")
534
535 [case testShowErrorContextFromHere]
536 # flags: --show-error-context
537 import a
538 [file a.py]
539 import b
540 [file b.py]
541 0 + ""
542 [out]
543 tmp/a.py:1: note: In module imported here,
544 main:2: note: ... from here:
545 tmp/b.py:1: error: Unsupported operand types for + ("int" and "str")
546
547 [case testFollowImportsNormal]
548 # flags: --follow-imports=normal
549 from mod import x
550 x + 0
551 x + "" # E: Unsupported operand types for + ("int" and "str")
552 import mod
553 mod.x + 0
554 mod.x + "" # E: Unsupported operand types for + ("int" and "str")
555 mod.y # E: "object" has no attribute "y"
556 mod + 0 # E: Unsupported left operand type for + ("object")
557 [file mod.py]
558 1 + "" # E: Unsupported operand types for + ("int" and "str")
559 x = 0
560 x += "" # E: Unsupported operand types for + ("int" and "str")
561
562 [case testFollowImportsSilent]
563 # flags: --follow-imports=silent
564 from mod import x
565 x + "" # E: Unsupported operand types for + ("int" and "str")
566 import mod
567 mod.x + "" # E: Unsupported operand types for + ("int" and "str")
568 mod.y # E: "object" has no attribute "y"
569 mod + 0 # E: Unsupported left operand type for + ("object")
570 [file mod.py]
571 1 + ""
572 x = 0
573 x += ""
574
575 [case testFollowImportsSilentTypeIgnore]
576 # flags: --warn-unused-ignores --follow-imports=silent
577 import mod
578 [file mod.py]
579 x = 3 # type: ignore
580
581 [case testFollowImportsSkip]
582 # flags: --follow-imports=skip
583 from mod import x
584 reveal_type(x) # N: Revealed type is "Any"
585 x + ""
586 import mod
587 reveal_type(mod.x) # N: Revealed type is "Any"
588 [file mod.py]
589 this deliberate syntax error will not be reported
590
591 [case testFollowImportsError]
592 # flags: --follow-imports=error
593 from mod import x # E: Import of "mod" ignored \
594 # N: (Using --follow-imports=error, module not passed on command line)
595 x + ""
596 reveal_type(x) # N: Revealed type is "Any"
597 import mod
598 reveal_type(mod.x) # N: Revealed type is "Any"
599 [file mod.py]
600 deliberate syntax error
601
602 [case testFollowImportsSelective]
603 # flags: --config-file tmp/mypy.ini
604 import normal
605 import silent
606 import skip
607 import error # E: Import of "error" ignored \
608 # N: (Using --follow-imports=error, module not passed on command line)
609 reveal_type(normal.x) # N: Revealed type is "builtins.int"
610 reveal_type(silent.x) # N: Revealed type is "builtins.int"
611 reveal_type(skip) # N: Revealed type is "Any"
612 reveal_type(error) # N: Revealed type is "Any"
613 [file mypy.ini]
614 \[mypy]
615 \[mypy-normal]
616 follow_imports = normal
617 \[mypy-silent]
618 follow_imports = silent
619 \[mypy-skip]
620 follow_imports = skip
621 \[mypy-error]
622 follow_imports = error
623 [file normal.py]
624 x = 0
625 x += '' # E: Unsupported operand types for + ("int" and "str")
626 [file silent.py]
627 x = 0
628 x += ''
629 [file skip.py]
630 bla bla
631 [file error.py]
632 bla bla
633
634 [case testFlagsFile]
635 # flags: @tmp/flagsfile
636 x: int
637 FLAG = False
638 if not FLAG:
639 x = "unreachable"
640 [file flagsfile]
641 ----always-true=FLAG
642
643 [case testConfigFile]
644 # flags: --config-file tmp/mypy.ini
645 x: int
646 FLAG = False
647 if not FLAG:
648 x = "unreachable"
649 [file mypy.ini]
650 \[mypy]
651 always_true = FLAG
652
653 [case testAltConfigFile]
654 # flags: --config-file tmp/config.ini
655 x: int
656 FLAG = False
657 if not FLAG:
658 x = "unreachable"
659 [file config.ini]
660 \[mypy]
661 always_true = FLAG
662
663 [case testMultipleGlobConfigSection]
664 # flags: --config-file tmp/mypy.ini
665 import x, y, z
666 [file mypy.ini]
667 \[mypy]
668 \[mypy-x.*,z.*]
669 disallow_untyped_defs = True
670 [file x.py]
671 def f(a): pass # E: Function is missing a type annotation
672 [file y.py]
673 def f(a): pass
674 [file z.py]
675 def f(a): pass # E: Function is missing a type annotation
676
677 [case testConfigMypyPath]
678 # flags: --config-file tmp/mypy.ini
679 import no_stubs # E: Cannot find implementation or library stub for module named "no_stubs" \
680 # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
681 from foo import foo
682 from bar import bar
683 from baz import baz
684 baz(bar(foo(42)))
685 baz(bar(foo('oof'))) # E: Argument 1 to "foo" has incompatible type "str"; expected "int"
686 [file mypy.ini]
687 \[mypy]
688 mypy_path =
689 $MYPY_CONFIG_FILE_DIR/foo_dir:$MYPY_CONFIG_FILE_DIR/bar_dir
690 , $MYPY_CONFIG_FILE_DIR/baz_dir
691 [file foo_dir/foo.pyi]
692 def foo(x: int) -> str: ...
693 [file bar_dir/bar.pyi]
694 def bar(x: str) -> list: ...
695 [file baz_dir/baz.pyi]
696 def baz(x: list) -> dict: ...
697
698 [case testDisallowAnyGenericsBuiltinCollections]
699 # flags: --config-file tmp/mypy.ini
700 import m
701 [file mypy.ini]
702 \[mypy]
703 \[mypy-m]
704 disallow_any_generics = True
705 [file m.py]
706 def j(s: set) -> None: pass # E: Missing type arguments for generic type "set"
707 [builtins fixtures/set.pyi]
708
709 [case testDisallowAnyGenericsTypingCollections]
710 # flags: --config-file tmp/mypy.ini
711 import m
712 [file mypy.ini]
713 \[mypy]
714 \[mypy-m]
715 disallow_any_generics = True
716 [file m.py]
717 from typing import Set
718 def j(s: Set) -> None: pass # E: Missing type arguments for generic type "Set"
719 [builtins fixtures/set.pyi]
720
721 [case testSectionInheritance]
722 # flags: --config-file tmp/mypy.ini
723 import a, a.foo, a.b.c, a.b.c.d.e
724 [file a/__init__.py]
725 0()
726 [file a/foo.py]
727 0()
728 [file a/b/__init__.py]
729 [file a/b/c/__init__.py]
730 0()
731 [file a/b/c/d/__init__.py]
732 [file a/b/c/d/e/__init__.py]
733 from typing import List
734 def g(x: List) -> None: pass # E: Missing type arguments for generic type "List"
735 g(None) # E: Argument 1 to "g" has incompatible type "None"; expected "list[Any]"
736 [file mypy.ini]
737 \[mypy]
738 allow_any_generics = True
739 strict_optional = False
740 \[mypy-a.*]
741 ignore_errors = True
742 \[mypy-a.b.*]
743 disallow_any_generics = True
744 ignore_errors = True
745 \[mypy-a.b.c.*]
746 ignore_errors = True
747 \[mypy-a.b.c.d.*]
748 ignore_errors = True
749 \[mypy-a.b.c.d.e.*]
750 ignore_errors = True
751 strict_optional = True
752 \[mypy-a.b.c.d.e]
753 ignore_errors = False
754
755 [case testFollowImportStubs1]
756 # flags: --config-file tmp/mypy.ini
757 import math # E: Import of "math" ignored \
758 # N: (Using --follow-imports=error, module not passed on command line)
759 math.frobnicate()
760 [file mypy.ini]
761 \[mypy]
762 \[mypy-math.*]
763 follow_imports = error
764 follow_imports_for_stubs = True
765
766 [case testFollowImportStubs2]
767 # flags: --config-file tmp/mypy.ini
768 import math
769 math.frobnicate()
770 [file mypy.ini]
771 \[mypy]
772 \[mypy-math.*]
773 follow_imports = skip
774 follow_imports_for_stubs = True
775
776 [case testConfigUnstructuredGlob]
777 # flags: --config-file tmp/mypy.ini
778 import emarg.foo, emarg.villip, emarg.hatch.villip.nus, emarg.hatch.villip.mankangulisk, foo.lol
779 [file mypy.ini]
780 \[mypy]
781 ignore_errors = true
782 \[mypy-*.lol]
783 ignore_errors = false
784 \[mypy-emarg.*]
785 ignore_errors = false
786 \[mypy-emarg.*.villip.*]
787 ignore_errors = true
788 \[mypy-emarg.hatch.villip.mankangulisk]
789 ignore_errors = false
790 [file emarg/__init__.py]
791 [file emarg/foo.py]
792 fail # E: Name "fail" is not defined
793 [file emarg/villip.py]
794 fail
795 [file emarg/hatch/__init__.py]
796 [file emarg/hatch/villip/__init__.py]
797 [file emarg/hatch/villip/nus.py]
798 fail
799 [file emarg/hatch/villip/mankangulisk.py]
800 fail # E: Name "fail" is not defined
801 [file foo/__init__.py]
802 [file foo/lol.py]
803 fail # E: Name "fail" is not defined
804
805 [case testIgnoreMissingImportsFalse]
806 from mod import x
807 [out]
808 main:1: error: Cannot find implementation or library stub for module named "mod"
809 main:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
810
811 [case testIgnoreMissingImportsTrue]
812 # flags: --ignore-missing-imports
813 from mod import x
814 [out]
815
816 [case testNoConfigFile]
817 # flags: --config-file=
818 # type: ignore
819
820 [file mypy.ini]
821 \[mypy]
822 warn_unused_ignores = True
823 [out]
824
825 [case testPerFileIncompleteDefsBasic]
826 # flags: --config-file tmp/mypy.ini
827 import standard, incomplete
828
829 [file standard.py]
830 def incomplete(x) -> int:
831 return 0
832 [file incomplete.py]
833 def incomplete(x) -> int: # E: Function is missing a type annotation for one or more parameters
834 return 0
835 [file mypy.ini]
836 \[mypy]
837 disallow_incomplete_defs = False
838 \[mypy-incomplete]
839 disallow_incomplete_defs = True
840
841
842 [case testPerFileIncompleteDefsBasicPyProjectTOML]
843 # flags: --config-file tmp/pyproject.toml
844 import standard, incomplete
845
846 [file standard.py]
847 def incomplete(x) -> int:
848 return 0
849 [file incomplete.py]
850 def incomplete(x) -> int: # E: Function is missing a type annotation for one or more parameters
851 return 0
852 [file pyproject.toml]
853 \[tool.mypy]
854 disallow_incomplete_defs = false
855 \[[tool.mypy.overrides]]
856 module = 'incomplete'
857 disallow_incomplete_defs = true
858
859
860 [case testPerFileStrictOptionalBasic]
861 # flags: --config-file tmp/mypy.ini
862 import standard, optional
863
864 [file standard.py]
865 x = 0
866 if int():
867 x = None
868 [file optional.py]
869 x = 0
870 if int():
871 x = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
872
873 [file mypy.ini]
874 \[mypy]
875 strict_optional = False
876 \[mypy-optional]
877 strict_optional = True
878
879
880 [case testPerFileStrictOptionalBasicPyProjectTOML]
881 # flags: --config-file tmp/pyproject.toml
882 import standard, optional
883
884 [file standard.py]
885 x = 0
886 if int():
887 x = None
888 [file optional.py]
889 x = 0
890 if int():
891 x = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
892
893 [file pyproject.toml]
894 \[tool.mypy]
895 strict_optional = false
896 \[[tool.mypy.overrides]]
897 module = 'optional'
898 strict_optional = true
899
900
901 [case testPerFileStrictOptionalBasicImportStandard]
902 # flags: --config-file tmp/mypy.ini
903 import standard, optional
904
905 [file standard.py]
906 from typing import Optional
907 def f(x: int) -> None: pass
908 an_int = 0 # type: int
909 optional_int = None # type: Optional[int]
910 f(an_int) # ints can be used as ints
911 f(optional_int) # optional ints can be used as ints in this file
912
913 [file optional.py]
914 import standard
915 def f(x: int) -> None: pass
916 standard.an_int = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
917 standard.optional_int = None # OK -- explicitly declared as optional
918 f(standard.an_int) # ints can be used as ints
919 f(standard.optional_int) # E: Argument 1 to "f" has incompatible type "None"; expected "int"
920
921 [file mypy.ini]
922 \[mypy]
923 strict_optional = False
924 \[mypy-optional]
925 strict_optional = True
926
927
928 [case testPerFileStrictOptionalBasicImportStandardPyProjectTOML]
929 # flags: --config-file tmp/pyproject.toml
930 import standard, optional
931
932 [file standard.py]
933 from typing import Optional
934 def f(x: int) -> None: pass
935 an_int = 0 # type: int
936 optional_int = None # type: Optional[int]
937 f(an_int) # ints can be used as ints
938 f(optional_int) # optional ints can be used as ints in this file
939
940 [file optional.py]
941 import standard
942 def f(x: int) -> None: pass
943 standard.an_int = None # E: Incompatible types in assignment (expression has type "None", variable has type "int")
944 standard.optional_int = None # OK -- explicitly declared as optional
945 f(standard.an_int) # ints can be used as ints
946 f(standard.optional_int) # E: Argument 1 to "f" has incompatible type "None"; expected "int"
947
948 [file pyproject.toml]
949 \[tool.mypy]
950 strict_optional = false
951 \[[tool.mypy.overrides]]
952 module = 'optional'
953 strict_optional = true
954
955
956 [case testPerFileStrictOptionalBasicImportOptional]
957 # flags: --config-file tmp/mypy.ini
958 import standard, optional
959
960 [file standard.py]
961 import optional
962 def f(x: int) -> None: pass
963 f(optional.x) # OK -- in non-strict Optional context
964 f(optional.y) # OK -- in non-strict Optional context
965
966 [file optional.py]
967 from typing import Optional
968 def f(x: int) -> None: pass
969 x = 0 # type: Optional[int]
970 y = None # type: None
971
972 [file mypy.ini]
973 \[mypy]
974 strict_optional = False
975 \[mypy-optional]
976 strict_optional = True
977
978
979 [case testPerFileStrictOptionalBasicImportOptionalPyProjectTOML]
980 # flags: --config-file tmp/pyproject.toml
981 import standard, optional
982
983 [file standard.py]
984 import optional
985 def f(x: int) -> None: pass
986 f(optional.x) # OK -- in non-strict Optional context
987 f(optional.y) # OK -- in non-strict Optional context
988
989 [file optional.py]
990 from typing import Optional
991 def f(x: int) -> None: pass
992 x = 0 # type: Optional[int]
993 y = None # type: None
994
995 [file pyproject.toml]
996 \[tool.mypy]
997 strict_optional = false
998 \[[tool.mypy.overrides]]
999 module = 'optional'
1000 strict_optional = true
1001
1002
1003 [case testPerFileStrictOptionalListItemImportOptional]
1004 # flags: --config-file tmp/mypy.ini
1005 import standard, optional
1006
1007 [file standard.py]
1008 import optional
1009 from typing import List
1010 def f(x: List[int]) -> None: pass
1011 f(optional.x) # OK -- in non-strict Optional context
1012 f(optional.y) # OK -- in non-strict Optional context
1013
1014 [file optional.py]
1015 from typing import Optional, List
1016 def f(x: List[int]) -> None: pass
1017 x = [] # type: List[Optional[int]]
1018 y = [] # type: List[int]
1019
1020 [file mypy.ini]
1021 \[mypy]
1022 strict_optional = False
1023 \[mypy-optional]
1024 strict_optional = True
1025 [builtins fixtures/list.pyi]
1026
1027
1028 [case testPerFileStrictOptionalListItemImportOptionalPyProjectTOML]
1029 # flags: --config-file tmp/pyproject.toml
1030 import standard, optional
1031
1032 [file standard.py]
1033 import optional
1034 from typing import List
1035 def f(x: List[int]) -> None: pass
1036 f(optional.x) # OK -- in non-strict Optional context
1037 f(optional.y) # OK -- in non-strict Optional context
1038
1039 [file optional.py]
1040 from typing import Optional, List
1041 def f(x: List[int]) -> None: pass
1042 x = [] # type: List[Optional[int]]
1043 y = [] # type: List[int]
1044
1045 [file pyproject.toml]
1046 \[tool.mypy]
1047 strict_optional = false
1048 \[[tool.mypy.overrides]]
1049 module = 'optional'
1050 strict_optional = true
1051
1052 [builtins fixtures/list.pyi]
1053
1054
1055 [case testPerFileStrictOptionalComplicatedList]
1056 from typing import Union, Optional, List
1057
1058 def f() -> None:
1059 x = [] # type: Union[List[Optional[str]], str]
1060 [builtins fixtures/list.pyi]
1061
1062 [case testPerFileStrictOptionalNoneArguments]
1063 # flags: --config-file tmp/mypy.ini
1064 import standard, optional
1065
1066 [file standard.py]
1067 def f(x: int = None) -> None: pass
1068
1069 [file optional.py]
1070 import standard
1071 def f(x: int = None) -> None: pass
1072 standard.f(None)
1073
1074 [file mypy.ini]
1075 \[mypy]
1076 strict_optional = False
1077 implicit_optional = true
1078 \[mypy-optional]
1079 strict_optional = True
1080
1081
1082 [case testPerFileStrictOptionalNoneArgumentsPyProjectTOML]
1083 # flags: --config-file tmp/pyproject.toml
1084 import standard, optional
1085
1086 [file standard.py]
1087 def f(x: int = None) -> None: pass
1088
1089 [file optional.py]
1090 import standard
1091 def f(x: int = None) -> None: pass
1092 standard.f(None)
1093
1094 [file pyproject.toml]
1095 \[tool.mypy]
1096 strict_optional = false
1097 implicit_optional = true
1098 \[[tool.mypy.overrides]]
1099 module = 'optional'
1100 strict_optional = true
1101
1102 [case testSilentMissingImportsOff]
1103 -- ignore_missing_imports is False by default.
1104 import missing # E: Cannot find implementation or library stub for module named "missing" \
1105 # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
1106 reveal_type(missing.x) # N: Revealed type is "Any"
1107
1108 [case testSilentMissingImportsOn]
1109 # flags: --ignore-missing-imports
1110 import missing
1111 reveal_type(missing.x) # N: Revealed type is "Any"
1112
1113 [case testDisallowImplicitTypesIgnoreMissingTypes]
1114 # flags: --ignore-missing-imports --disallow-any-unimported
1115 from missing import MyType
1116
1117 def f(x: MyType) -> None: # E: Argument 1 to "f" becomes "Any" due to an unfollowed import
1118 pass
1119
1120 [case testDisallowImplicitTypes]
1121 # flags: --disallow-any-unimported
1122 from missing import MyType
1123
1124 def f(x: MyType) -> None:
1125 pass
1126 [out]
1127 main:2: error: Cannot find implementation or library stub for module named "missing"
1128 main:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
1129 main:4: error: Argument 1 to "f" becomes "Any" due to an unfollowed import
1130
1131 [case testDisallowImplicitAnyVariableDefinition]
1132 # flags: --ignore-missing-imports --disallow-any-unimported
1133 from missing import Unchecked
1134
1135 t: Unchecked = 12 # E: Type of variable becomes "Any" due to an unfollowed import
1136
1137 [case testAllowImplicitAnyVariableDefinition]
1138 # flags: --ignore-missing-imports --allow-any-unimported
1139 from missing import Unchecked
1140
1141 t: Unchecked = 12
1142
1143 [case testDisallowImplicitAnyGeneric]
1144 # flags: --ignore-missing-imports --disallow-any-unimported
1145 from missing import Unchecked
1146 from typing import List
1147
1148 def foo(l: List[Unchecked]) -> List[Unchecked]:
1149 t = [] # type: List[Unchecked]
1150 return l
1151 [builtins fixtures/list.pyi]
1152 [out]
1153 main:5: error: Return type becomes "list[Any]" due to an unfollowed import
1154 main:5: error: Argument 1 to "foo" becomes "list[Any]" due to an unfollowed import
1155 main:6: error: Type of variable becomes "list[Any]" due to an unfollowed import
1156
1157 [case testDisallowImplicitAnyInherit]
1158 # flags: --ignore-missing-imports --disallow-any-unimported
1159 from missing import Unchecked
1160 from typing import List
1161
1162 class C(Unchecked): # E: Base type Unchecked becomes "Any" due to an unfollowed import
1163 pass
1164
1165 class A(List[Unchecked]): # E: Base type becomes "list[Any]" due to an unfollowed import
1166 pass
1167 [builtins fixtures/list.pyi]
1168
1169 [case testDisallowImplicitAnyAlias]
1170 # flags: --ignore-missing-imports --disallow-any-unimported
1171 from missing import Unchecked
1172 from typing import List
1173
1174 X = List[Unchecked] # E: Type alias target becomes "list[Any]" due to an unfollowed import
1175
1176 def f(x: X) -> None:
1177 pass
1178 [builtins fixtures/list.pyi]
1179
1180 [case testDisallowImplicitAnyCast]
1181 # flags: --ignore-missing-imports --disallow-any-unimported
1182 from missing import Unchecked
1183 from typing import List, cast
1184
1185
1186 foo = [1, 2, 3]
1187 cast(List[Unchecked], foo) # E: Target type of cast becomes "list[Any]" due to an unfollowed import
1188 cast(Unchecked, foo) # E: Target type of cast becomes "Any" due to an unfollowed import
1189 [builtins fixtures/list.pyi]
1190
1191 [case testDisallowImplicitAnyNamedTuple]
1192 # flags: --ignore-missing-imports --disallow-any-unimported
1193 from typing import List, NamedTuple
1194 from missing import Unchecked
1195
1196 Point = NamedTuple('Point', [('x', List[Unchecked]),
1197 ('y', Unchecked)])
1198 [builtins fixtures/list.pyi]
1199 [out]
1200 main:5: error: NamedTuple type becomes "tuple[list[Any], Any]" due to an unfollowed import
1201
1202 [case testDisallowImplicitAnyTypeVarConstraints]
1203 # flags: --ignore-missing-imports --disallow-any-unimported
1204 from typing import List, NamedTuple, TypeVar, Any
1205 from missing import Unchecked
1206
1207 T = TypeVar('T', Unchecked, List[Unchecked], str)
1208 [builtins fixtures/list.pyi]
1209 [out]
1210 main:5: error: Constraint 1 becomes "Any" due to an unfollowed import
1211 main:5: error: Constraint 2 becomes "list[Any]" due to an unfollowed import
1212
1213 [case testDisallowImplicitAnyNewType]
1214 # flags: --ignore-missing-imports --disallow-any-unimported
1215 from typing import NewType, List
1216 from missing import Unchecked
1217
1218 Baz = NewType('Baz', Unchecked) # E: Argument 2 to NewType(...) must be subclassable (got "Any")
1219 Bar = NewType('Bar', List[Unchecked]) # E: Argument 2 to NewType(...) becomes "list[Any]" due to an unfollowed import
1220
1221 [builtins fixtures/list.pyi]
1222
1223 [case testDisallowImplicitAnyCallableAndTuple]
1224 # flags: --ignore-missing-imports --disallow-any-unimported
1225 from typing import Callable, Tuple
1226 from missing import Unchecked
1227
1228 def foo(f: Callable[[], Unchecked]) -> Tuple[Unchecked]:
1229 return f()
1230 [builtins fixtures/list.pyi]
1231 [out]
1232 main:5: error: Return type becomes "tuple[Any]" due to an unfollowed import
1233 main:5: error: Argument 1 to "foo" becomes "Callable[[], Any]" due to an unfollowed import
1234
1235 [case testDisallowImplicitAnySubclassingExplicitAny]
1236 # flags: --ignore-missing-imports --disallow-any-unimported --disallow-subclassing-any
1237 from typing import Any
1238
1239 class C(Any): # E: Class cannot subclass "Any" (has type "Any")
1240 pass
1241
1242 [case testDisallowImplicitAnyVarDeclaration]
1243 # flags: --ignore-missing-imports --disallow-any-unimported
1244 from missing import Unchecked
1245
1246 foo: Unchecked = ""
1247 foo = ""
1248 x, y = 1, 2 # type: Unchecked, Unchecked
1249 [builtins fixtures/tuple.pyi]
1250 [out]
1251 main:4: error: Type of variable becomes "Any" due to an unfollowed import
1252 main:6: error: A type on this line becomes "Any" due to an unfollowed import
1253
1254 [case testDisallowUnimportedAnyTypedDictSimple]
1255 # flags: --ignore-missing-imports --disallow-any-unimported
1256 from typing import TypedDict
1257 from x import Unchecked
1258
1259 M = TypedDict('M', {'x': str, 'y': Unchecked}) # E: Type of a TypedDict key becomes "Any" due to an unfollowed import
1260
1261 def f(m: M) -> M: pass # no error
1262 [builtins fixtures/dict.pyi]
1263 [typing fixtures/typing-typeddict.pyi]
1264
1265 [case testDisallowUnimportedAnyTypedDictGeneric]
1266 # flags: --ignore-missing-imports --disallow-any-unimported
1267 from typing import List, TypedDict
1268 from x import Unchecked
1269
1270 M = TypedDict('M', {'x': str, 'y': List[Unchecked]}) # E: Type of a TypedDict key becomes "list[Any]" due to an unfollowed import
1271
1272 def f(m: M) -> M: pass # no error
1273 [builtins fixtures/dict.pyi]
1274 [typing fixtures/typing-typeddict.pyi]
1275
1276 [case testDisallowAnyDecoratedUnannotatedDecorator]
1277 # flags: --disallow-any-decorated
1278 from typing import Any
1279
1280 def d(f):
1281 return f
1282
1283 @d
1284 def f(x: Any) -> Any: # E: Function is untyped after decorator transformation
1285 pass
1286 @d
1287 def h(x): # E: Function is untyped after decorator transformation
1288 pass
1289 [builtins fixtures/list.pyi]
1290
1291 [case testDisallowAnyDecoratedUnannotatedDecoratorDeferred1]
1292 # flags: --disallow-any-decorated
1293 from typing import Callable
1294
1295 def d(f: Callable[[int], None]) -> Callable[[int], None]:
1296 return f
1297
1298 def wrapper() -> None:
1299 if c:
1300 @d
1301 def h(x):
1302 pass
1303
1304 c = [1]
1305 [builtins fixtures/list.pyi]
1306
1307 [case testDisallowAnyDecoratedUnannotatedDecoratorDeferred2]
1308 # flags: --disallow-any-decorated
1309 from typing import Callable
1310
1311 def d(f: Callable[[int], None]) -> Callable[[int], None]:
1312 return f
1313
1314 c = 1 # no deferral - check that the previous testcase is valid
1315
1316 def wrapper() -> None:
1317 if c:
1318 @d
1319 def h(x):
1320 pass
1321 [builtins fixtures/list.pyi]
1322
1323 [case testDisallowAnyDecoratedErrorIsReportedOnlyOnce]
1324 # flags: --disallow-any-decorated
1325
1326 def d(f):
1327 return f
1328
1329 def d2(f):
1330 return f
1331
1332 @d
1333 @d2
1334 @d
1335 def f(x: int) -> None: pass # E: Function is untyped after decorator transformation
1336 [case testDisallowAnyDecoratedReturnAny]
1337 # flags: --disallow-any-decorated
1338 from typing import Any
1339
1340 def d(f) -> Any:
1341 return f
1342
1343 @d
1344 def f() -> None: pass # E: Function is untyped after decorator transformation
1345 [builtins fixtures/list.pyi]
1346 [case testDisallowAnyDecoratedReturnCallable]
1347 # flags: --disallow-any-decorated
1348 from typing import Any, Callable
1349
1350 def d(f) -> Callable[..., None]:
1351 return f
1352
1353 @d
1354 def g(i: int, s: str) -> None: pass # E: Type of decorated function contains type "Any" ("Callable[..., None]")
1355
1356 [builtins fixtures/list.pyi]
1357 [case testDisallowAnyDecoratedNonexistentDecorator]
1358 # flags: --disallow-any-decorated --ignore-missing-imports
1359 from nonexistent import d
1360
1361 @d
1362 def f() -> None: pass # E: Function is untyped after decorator transformation
1363 [builtins fixtures/list.pyi]
1364
1365 [case testDisallowAnyDecoratedPartlyTypedCallable]
1366 # flags: --disallow-any-decorated --ignore-missing-imports
1367 from typing import Callable, Any, List
1368
1369 def d(f) -> Callable[[int, Any], Any]: pass
1370 def d2(f) -> Callable[[int], List[Any]]: pass
1371 def d3(f) -> Callable[[Any], List[str]]: pass
1372
1373 @d
1374 def f(i: int, s: str) -> None: # E: Type of decorated function contains type "Any" ("Callable[[int, Any], Any]")
1375 pass
1376 @d2
1377 def g(i: int) -> None: # E: Type of decorated function contains type "Any" ("Callable[[int], list[Any]]")
1378 pass
1379 @d3
1380 def h(i: int) -> None: # E: Type of decorated function contains type "Any" ("Callable[[Any], list[str]]")
1381 pass
1382 [builtins fixtures/list.pyi]
1383
1384 [case testDisallowAnyDecoratedReturnsCallableNoParams]
1385 # flags: --disallow-any-decorated
1386 from typing import Callable
1387
1388 def d(p) -> Callable[[], int]:
1389 return p
1390
1391 @d
1392 def f(i):
1393 return i
1394 [builtins fixtures/list.pyi]
1395
1396 [case testDisallowAnyDecoratedDecoratorReturnsNonCallable]
1397 # flags: --disallow-any-decorated
1398 def d(p) -> int:
1399 return p(0)
1400
1401 @d
1402 def f(i):
1403 return i
1404
1405 [case testDisallowAnyDecoratedUntypedUndecoratedFunction]
1406 # flags: --disallow-any-decorated
1407 from typing import Callable
1408
1409 def f(i): # no error
1410 return i
1411
1412 [case testDisallowAnyDecoratedTwoDecorators]
1413 # flags: --disallow-any-decorated
1414 from typing import Callable
1415
1416 def typed_dec(f) -> Callable[[], int]: pass
1417 def untyped_dec(f): pass
1418
1419 @typed_dec
1420 @untyped_dec
1421 def f(): # no error
1422 return i
1423
1424 @untyped_dec
1425 @typed_dec
1426 def g(): # E: Function is untyped after decorator transformation
1427 return i
1428
1429 [case testDisallowAnyExprSimple]
1430 # flags: --disallow-any-expr
1431 from typing import Any
1432 def f(s):
1433 yield s
1434
1435 def g(x) -> Any:
1436 yield x # E: Expression has type "Any"
1437
1438 x = f(0) # E: Expression has type "Any"
1439 for x in f(0): # E: Expression has type "Any"
1440 g(x) # E: Expression has type "Any"
1441
1442 l = [1, 2, 3]
1443 l[f(0)] # E: Expression has type "Any"
1444 f(l)
1445 f(f(0)) # E: Expression has type "Any"
1446 [builtins fixtures/list.pyi]
1447
1448 [case testDisallowAnyExprUnannotatedFunction]
1449 # flags: --disallow-any-expr
1450 def g(s):
1451 return s
1452
1453 g(0)
1454 w: int = g(1)
1455
1456 [case testDisallowAnyExprExplicitAnyParam]
1457 # flags: --disallow-any-expr
1458 from typing import Any, List
1459 def f(s: Any) -> None:
1460 pass
1461
1462 def g(s: List[Any]) -> None:
1463 pass
1464
1465 f(0)
1466
1467 # type of list below is inferred with expected type of "list[Any]", so that becomes it's type
1468 # instead of list[str]
1469 g(['']) # E: Expression type contains "Any" (has type "list[Any]")
1470 [builtins fixtures/list.pyi]
1471
1472 [case testDisallowAnyExprAllowsAnyInCast]
1473 # flags: --disallow-any-expr
1474 from typing import Any, cast
1475 class Foo:
1476 g: Any = 2
1477
1478 z = cast(int, Foo().g)
1479 m = cast(Any, Foo().g) # E: Expression has type "Any"
1480 k = Foo.g # E: Expression has type "Any"
1481 [builtins fixtures/list.pyi]
1482
1483 [case testDisallowAnyExprAllowsAnyInVariableAssignmentWithExplicitTypeAnnotation]
1484 # flags: --disallow-any-expr
1485 from typing import Any
1486 class Foo:
1487 g: Any = 2
1488
1489 z: int = Foo().g
1490 x = Foo().g # type: int
1491 m: Any = Foo().g # E: Expression has type "Any"
1492 n = Foo().g # type: Any # E: Expression has type "Any"
1493 [builtins fixtures/list.pyi]
1494
1495 [case testDisallowAnyExprGeneric]
1496 # flags: --disallow-any-expr
1497 from typing import List
1498
1499 l: List = []
1500 l.append(1) # E: Expression type contains "Any" (has type "list[Any]")
1501 k = l[0] # E: Expression type contains "Any" (has type "list[Any]") # E: Expression has type "Any"
1502 [builtins fixtures/list.pyi]
1503
1504 [case testDisallowAnyExprTypeVar]
1505 # flags: --disallow-any-expr
1506 from typing import TypeVar
1507
1508 T = TypeVar('T') # no error
1509
1510 def f(t: T) -> T:
1511 return t
1512 [builtins fixtures/list.pyi]
1513
1514 [case testDisallowAnyExprNamedTuple]
1515 # flags: --disallow-any-expr
1516 from typing import NamedTuple
1517
1518 Point = NamedTuple('Point', [('x', int), ('y', int)]) # no error
1519
1520 def origin() -> Point:
1521 return Point(x=0, y=0)
1522 [builtins fixtures/list.pyi]
1523
1524 [case testDisallowAnyExprNewType]
1525 # flags: --disallow-any-expr
1526 from typing import NewType
1527
1528 NT = NewType('NT', int) # no error
1529
1530 def nt() -> NT:
1531 return NT(1)
1532 [builtins fixtures/list.pyi]
1533
1534 [case testDisallowAnyExprEnum]
1535 # flags: --disallow-any-expr
1536 from enum import Enum
1537 E = Enum('E', '1, 2, 3') # no error
1538
1539 def k(s: E) -> None: pass
1540 [builtins fixtures/list.pyi]
1541
1542 [case testDisallowAnyExprTypedDict]
1543 # flags: --disallow-any-expr
1544 from typing import TypedDict
1545
1546 Movie = TypedDict('Movie', {'name': str, 'year': int})
1547
1548 def g(m: Movie) -> Movie:
1549 return m
1550 [builtins fixtures/dict.pyi]
1551 [typing fixtures/typing-typeddict.pyi]
1552
1553 [case testDisallowIncompleteDefs]
1554 # flags: --disallow-incomplete-defs
1555
1556 def f(i: int): # E: Function is missing a return type annotation
1557 pass
1558 def g(i) -> None: # E: Function is missing a type annotation for one or more parameters
1559 pass
1560 def h(i: int) -> int: # no error
1561 return i
1562 def i() -> None: # no error
1563 pass
1564
1565 [case testDisallowIncompleteDefsNoReturn]
1566 # flags: --disallow-incomplete-defs --disallow-untyped-defs
1567
1568 def f(i: int): # E: Function is missing a return type annotation
1569 pass
1570
1571 [case testDisallowIncompleteDefsSelf]
1572 # flags: --disallow-incomplete-defs
1573 class C:
1574 def foo(self) -> None: # no error
1575 pass
1576
1577 [case testDisallowIncompleteDefsPartiallyAnnotatedParams]
1578 # flags: --disallow-incomplete-defs
1579
1580 def f(i: int, s):
1581 pass
1582
1583 [out]
1584 main:3: error: Function is missing a return type annotation
1585 main:3: error: Function is missing a type annotation for one or more parameters
1586
1587 [case testDisallowIncompleteDefsAttrsNoAnnotations]
1588 # flags: --disallow-incomplete-defs
1589 import attrs
1590
1591 @attrs.define
1592 class Unannotated:
1593 foo = attrs.field()
1594
1595 [builtins fixtures/plugin_attrs.pyi]
1596
1597 [case testDisallowIncompleteDefsAttrsWithAnnotations]
1598 # flags: --disallow-incomplete-defs
1599 import attrs
1600
1601 @attrs.define
1602 class Annotated:
1603 bar: int = attrs.field()
1604
1605 [builtins fixtures/plugin_attrs.pyi]
1606
1607 [case testDisallowIncompleteDefsAttrsPartialAnnotations]
1608 # flags: --disallow-incomplete-defs
1609 import attrs
1610
1611 @attrs.define
1612 class PartiallyAnnotated: # E: Function is missing a type annotation for one or more parameters
1613 bar: int = attrs.field()
1614 baz = attrs.field()
1615
1616 [builtins fixtures/plugin_attrs.pyi]
1617
1618 [case testAlwaysTrueAlwaysFalseFlags]
1619 # flags: --always-true=YOLO --always-true=YOLO1 --always-false=BLAH1 --always-false BLAH --ignore-missing-imports
1620 from somewhere import YOLO, BLAH
1621 if not YOLO:
1622 1+()
1623 if BLAH:
1624 1+()
1625 [builtins fixtures/bool.pyi]
1626
1627 [case testAlwaysTrueAlwaysFalseConfigFile]
1628 # flags: --config-file tmp/mypy.ini
1629 from somewhere import YOLO, BLAH
1630 if not YOLO:
1631 1+()
1632 if BLAH:
1633 1+()
1634 [file mypy.ini]
1635 \[mypy]
1636 ignore_missing_imports = True
1637 always_true = YOLO1, YOLO
1638 always_false = BLAH, BLAH1
1639 [builtins fixtures/bool.pyi]
1640
1641
1642 [case testAlwaysTrueAlwaysFalseConfigFilePyProjectTOML]
1643 # flags: --config-file tmp/pyproject.toml
1644 from somewhere import YOLO, BLAH
1645 if not YOLO:
1646 1+()
1647 if BLAH:
1648 1+()
1649
1650 [file pyproject.toml]
1651 \[tool.mypy]
1652 ignore_missing_imports = true
1653 always_true = ['YOLO1', 'YOLO']
1654 always_false = ['BLAH', 'BLAH1']
1655
1656 [builtins fixtures/bool.pyi]
1657
1658
1659 [case testDisableErrorCodeConfigFile]
1660 # flags: --config-file tmp/mypy.ini --disallow-untyped-defs
1661 import foo
1662 def bar():
1663 pass
1664 [file mypy.ini]
1665 \[mypy]
1666 disable_error_code = import, no-untyped-def
1667
1668
1669 [case testDisableErrorCodeConfigFilePyProjectTOML]
1670 # flags: --config-file tmp/pyproject.toml --disallow-untyped-defs
1671 import foo
1672 def bar():
1673 pass
1674
1675 [file pyproject.toml]
1676 \[tool.mypy]
1677 disable_error_code = ['import', 'no-untyped-def']
1678
1679
1680 [case testCheckDisallowAnyGenericsNamedTuple]
1681 # flags: --disallow-any-generics
1682 from typing import NamedTuple
1683
1684 N = NamedTuple('N', [('x', N)]) # type: ignore
1685 n: N
1686 [builtins fixtures/tuple.pyi]
1687 [out]
1688
1689 [case testCheckDisallowAnyGenericsTypedDict]
1690 # flags: --disallow-any-generics
1691 from typing import Dict, Any, Optional, TypedDict
1692
1693 VarsDict = Dict[str, Any]
1694 HostsDict = Dict[str, Optional[VarsDict]]
1695
1696 GroupDataDict = TypedDict(
1697 "GroupDataDict", {"children": "GroupsDict", # type: ignore
1698 "vars": VarsDict,
1699 "hosts": HostsDict}, total=False
1700 )
1701
1702 GroupsDict = Dict[str, GroupDataDict] # type: ignore
1703 [builtins fixtures/dict.pyi]
1704 [typing fixtures/typing-typeddict.pyi]
1705
1706
1707 [case testCheckDisallowAnyGenericsStubOnly]
1708 # flags: --disallow-any-generics
1709 from asyncio import Future
1710 from queue import Queue
1711 x: Future[str]
1712 y: Queue[int]
1713
1714 p: Future # E: Missing type arguments for generic type "Future"
1715 q: Queue # E: Missing type arguments for generic type "Queue"
1716 [file asyncio/__init__.pyi]
1717 from asyncio.futures import Future as Future
1718 [file asyncio/futures.pyi]
1719 from typing import TypeVar, Generic
1720 _T = TypeVar('_T')
1721 class Future(Generic[_T]): ...
1722 [file queue.pyi]
1723 from typing import TypeVar, Generic
1724 _T = TypeVar('_T')
1725 class Queue(Generic[_T]): ...
1726 [builtins fixtures/async_await.pyi]
1727 [typing fixtures/typing-full.pyi]
1728
1729 [case testDisallowAnyGenericsBuiltinTuple]
1730 # flags: --disallow-any-generics
1731 s = tuple([1, 2, 3])
1732 def f(t: tuple) -> None: pass # E: Missing type arguments for generic type "tuple"
1733 [builtins fixtures/tuple.pyi]
1734
1735 [case testDisallowAnyGenericsBuiltinList]
1736 # flags: --disallow-any-generics
1737 l = list([1, 2, 3])
1738 def f(t: list) -> None: pass # E: Missing type arguments for generic type "list"
1739 [builtins fixtures/list.pyi]
1740
1741 [case testDisallowAnyGenericsBuiltinSet]
1742 # flags: --disallow-any-generics
1743 l = set({1, 2, 3})
1744 def f(s: set) -> None: pass # E: Missing type arguments for generic type "set"
1745 [builtins fixtures/set.pyi]
1746
1747 [case testDisallowAnyGenericsBuiltinDict]
1748 # flags: --disallow-any-generics
1749 l = dict([('a', 1)])
1750 def f(d: dict) -> None: pass # E: Missing type arguments for generic type "dict"
1751 [builtins fixtures/dict.pyi]
1752
1753 [case testCheckDefaultAllowAnyGeneric]
1754 from typing import TypeVar, Callable
1755
1756 T = TypeVar('T')
1757 C = Callable[[], T]
1758
1759 def f(c: C):
1760 pass
1761 [out]
1762
1763 [case testCheckAllowAnyGenericAnyGeneric]
1764 # flags: --strict --allow-any-generics
1765 from typing import TypeVar, Callable
1766
1767 T = TypeVar('T')
1768 C = Callable[[], T]
1769
1770 def f(c: C) -> None:
1771 pass
1772 [out]
1773
1774 [case testCheckDisallowAnyGenericsAnyGeneric]
1775 # flags: --disallow-any-generics
1776 from typing import TypeVar, Callable
1777
1778 T = TypeVar('T')
1779 C = Callable[[], T]
1780
1781 def f(c: C): # E: Missing type arguments for generic type "C"
1782 pass
1783
1784 [case testStrictAnyGeneric]
1785 # flags: --strict
1786 from typing import TypeVar, Generic
1787
1788 T = TypeVar('T')
1789
1790 class A(Generic[T]):
1791 pass
1792
1793 def f(c: A) -> None: # E: Missing type arguments for generic type "A"
1794 pass
1795
1796 [case testStrictInConfigAnyGeneric]
1797 # flags: --config-file tmp/mypy.ini
1798 from typing import TypeVar, Generic
1799
1800 T = TypeVar('T')
1801
1802 class A(Generic[T]):
1803 pass
1804
1805 def f(c: A) -> None: # E: Missing type arguments for generic type "A"
1806 pass
1807 [file mypy.ini]
1808 \[mypy]
1809 strict = True
1810
1811
1812 [case testStrictInConfigAnyGenericPyProjectTOML]
1813 # flags: --config-file tmp/pyproject.toml
1814 from typing import TypeVar, Generic
1815
1816 T = TypeVar('T')
1817
1818 class A(Generic[T]):
1819 pass
1820
1821 def f(c: A) -> None: # E: Missing type arguments for generic type "A"
1822 pass
1823
1824 [file pyproject.toml]
1825 \[tool.mypy]
1826 strict = true
1827
1828
1829 [case testStrictFalseInConfigAnyGeneric]
1830 # flags: --config-file tmp/mypy.ini
1831 from typing import TypeVar, Generic
1832
1833 T = TypeVar('T')
1834
1835 class A(Generic[T]):
1836 pass
1837
1838 def f(c: A) -> None:
1839 pass
1840 [file mypy.ini]
1841 \[mypy]
1842 strict = False
1843 [out]
1844
1845
1846 [case testStrictFalseInConfigAnyGenericPyProjectTOML]
1847 # flags: --config-file tmp/pyproject.toml
1848 from typing import TypeVar, Generic
1849
1850 T = TypeVar('T')
1851
1852 class A(Generic[T]):
1853 pass
1854
1855 def f(c: A) -> None:
1856 pass
1857
1858 [file pyproject.toml]
1859 \[tool.mypy]
1860 strict = false
1861
1862 [out]
1863
1864
1865 [case testStrictAndStrictEquality]
1866 # flags: --strict
1867 x = 0
1868 y = ''
1869 if x == y: # E: Non-overlapping equality check (left operand type: "int", right operand type: "str")
1870 int()
1871 [builtins fixtures/ops.pyi]
1872
1873 [case testStrictEqualityPerFile]
1874 # flags: --config-file tmp/mypy.ini
1875 import b
1876 42 == 'no' # E: Non-overlapping equality check (left operand type: "Literal[42]", right operand type: "Literal['no']")
1877 [file b.py]
1878 42 == 'no'
1879 [file mypy.ini]
1880 \[mypy]
1881 strict_equality = True
1882 \[mypy-b]
1883 strict_equality = False
1884 [builtins fixtures/bool.pyi]
1885
1886
1887 [case testStrictEqualityPerFilePyProjectTOML]
1888 # flags: --config-file tmp/pyproject.toml
1889 import b
1890 42 == 'no' # E: Non-overlapping equality check (left operand type: "Literal[42]", right operand type: "Literal['no']")
1891
1892 [file b.py]
1893 42 == 'no'
1894
1895 [file pyproject.toml]
1896 \[tool.mypy]
1897 strict_equality = true
1898 \[[tool.mypy.overrides]]
1899 module = 'b'
1900 strict_equality = false
1901
1902 [builtins fixtures/bool.pyi]
1903
1904
1905 [case testNoImplicitReexport]
1906 # flags: --no-implicit-reexport --show-error-codes
1907 from other_module_2 import a # E: Module "other_module_2" does not explicitly export attribute "a" [attr-defined]
1908 reveal_type(a) # N: Revealed type is "builtins.int"
1909
1910 import other_module_2
1911 reveal_type(other_module_2.a) # E: Module "other_module_2" does not explicitly export attribute "a" [attr-defined] \
1912 # N: Revealed type is "builtins.int"
1913
1914 from other_module_2 import b # E: Module "other_module_2" does not explicitly export attribute "b" [attr-defined]
1915 reveal_type(b) # N: Revealed type is "def (a: builtins.int) -> builtins.str"
1916
1917 import other_module_2
1918 reveal_type(other_module_2.b) # E: Module "other_module_2" does not explicitly export attribute "b" [attr-defined] \
1919 # N: Revealed type is "def (a: builtins.int) -> builtins.str"
1920
1921 [file other_module_1.py]
1922 a = 5
1923 def b(a: int) -> str: ...
1924 [file other_module_2.py]
1925 from other_module_1 import a, b
1926 [builtins fixtures/module.pyi]
1927
1928 [case testNoImplicitReexportRespectsAll]
1929 # flags: --no-implicit-reexport
1930 from other_module_2 import a
1931 from other_module_2 import b
1932 [file other_module_1.py]
1933 a = 5
1934 b = 6
1935 [file other_module_2.py]
1936 from other_module_1 import a, b
1937 __all__ = ('b',)
1938 [builtins fixtures/tuple.pyi]
1939 [out]
1940 main:2: error: Module "other_module_2" does not explicitly export attribute "a"
1941
1942 [case testNoImplicitReexportStarConsideredExplicit]
1943 # flags: --no-implicit-reexport
1944 from other_module_2 import a
1945 from other_module_2 import b
1946 [file other_module_1.py]
1947 a = 5
1948 b = 6
1949 [file other_module_2.py]
1950 from other_module_1 import *
1951 __all__ = ('b',)
1952 [builtins fixtures/tuple.pyi]
1953
1954 [case testNoImplicitReexportGetAttr]
1955 # flags: --no-implicit-reexport
1956 from other_module_2 import a # E: Module "other_module_2" does not explicitly export attribute "a"
1957 reveal_type(a) # N: Revealed type is "builtins.int"
1958 from other_module_2 import b # E: Module "other_module_2" does not explicitly export attribute "b"
1959 reveal_type(b) # N: Revealed type is "builtins.str"
1960 [file other_module_1.py]
1961 b: str = "asdf"
1962 def __getattr__(name: str) -> int: ...
1963 [file other_module_2.py]
1964 from other_module_1 import a, b
1965 def __getattr__(name: str) -> bytes: ...
1966 [builtins fixtures/tuple.pyi]
1967
1968 [case textNoImplicitReexportSuggestions]
1969 # flags: --no-implicit-reexport
1970 from other_module_2 import attr_1
1971
1972 [file other_module_1.py]
1973 attr_1 = 5
1974 attr_2 = 6
1975 [file other_module_2.py]
1976 from other_module_1 import attr_1, attr_2
1977 [out]
1978 main:2: error: Module "other_module_2" does not explicitly export attribute "attr_1"
1979
1980 [case testNoImplicitReexportMypyIni]
1981 # flags: --config-file tmp/mypy.ini
1982 from other_module_2 import a
1983
1984 [file other_module_1.py]
1985 a = 5
1986
1987 [file other_module_2.py]
1988 from other_module_1 import a
1989
1990 [file mypy.ini]
1991 \[mypy]
1992 implicit_reexport = True
1993 \[mypy-other_module_2]
1994 implicit_reexport = False
1995 [out]
1996 main:2: error: Module "other_module_2" does not explicitly export attribute "a"
1997
1998
1999 [case testNoImplicitReexportPyProjectTOML]
2000 # flags: --config-file tmp/pyproject.toml
2001 from other_module_2 import a
2002
2003 [file other_module_1.py]
2004 a = 5
2005
2006 [file other_module_2.py]
2007 from other_module_1 import a
2008
2009 [file pyproject.toml]
2010 \[tool.mypy]
2011 implicit_reexport = true
2012 \[[tool.mypy.overrides]]
2013 module = 'other_module_2'
2014 implicit_reexport = false
2015
2016 [out]
2017 main:2: error: Module "other_module_2" does not explicitly export attribute "a"
2018
2019
2020 [case testImplicitAnyOKForNoArgs]
2021 # flags: --disallow-any-generics --show-column-numbers
2022 from typing import List
2023
2024 A = List # OK
2025 B = List[A] # E:10: Missing type arguments for generic type "A"
2026 x: A # E:4: Missing type arguments for generic type "A"
2027 [builtins fixtures/list.pyi]
2028
2029 [case testDisallowAnyExplicitDefSignature]
2030 # flags: --disallow-any-explicit --show-error-codes
2031
2032 from typing import Any, List
2033
2034 def f(x: Any) -> None: # E: Explicit "Any" is not allowed [explicit-any]
2035 pass
2036
2037 def g() -> Any: # E: Explicit "Any" is not allowed [explicit-any]
2038 pass
2039
2040 def h() -> List[Any]: # E: Explicit "Any" is not allowed [explicit-any]
2041 pass
2042 [builtins fixtures/list.pyi]
2043
2044 [case testDisallowAnyExplicitVarDeclaration]
2045 # flags: --disallow-any-explicit --show-error-codes
2046 from typing import Any
2047 v: Any = '' # E: Explicit "Any" is not allowed [explicit-any]
2048 w = '' # type: Any # E: Explicit "Any" is not allowed [explicit-any]
2049 class X:
2050 y = '' # type: Any # E: Explicit "Any" is not allowed [explicit-any]
2051
2052 [case testDisallowAnyExplicitGenericVarDeclaration]
2053 # flags: --disallow-any-explicit --show-error-codes
2054 from typing import Any, List
2055 v: List[Any] = [] # E: Explicit "Any" is not allowed [explicit-any]
2056 [builtins fixtures/list.pyi]
2057
2058 [case testDisallowAnyExplicitInheritance]
2059 # flags: --disallow-any-explicit --show-error-codes
2060 from typing import Any, List
2061
2062 class C(Any): # E: Explicit "Any" is not allowed [explicit-any]
2063 pass
2064
2065 class D(List[Any]): # E: Explicit "Any" is not allowed [explicit-any]
2066 pass
2067 [builtins fixtures/list.pyi]
2068
2069 [case testDisallowAnyExplicitAlias]
2070 # flags: --disallow-any-explicit --show-error-codes
2071 from typing import Any, List
2072
2073 X = Any # E: Explicit "Any" is not allowed [explicit-any]
2074 Y = List[Any] # E: Explicit "Any" is not allowed [explicit-any]
2075
2076 def foo(x: X) -> Y: # no error
2077 x.nonexistent() # no error
2078 return x
2079 [builtins fixtures/list.pyi]
2080
2081 [case testDisallowAnyExplicitGenericAlias]
2082 # flags: --disallow-any-explicit --show-error-codes
2083 from typing import Any, TypeVar, Tuple
2084
2085 T = TypeVar('T')
2086
2087 TupleAny = Tuple[Any, T] # E: Explicit "Any" is not allowed [explicit-any]
2088
2089 def foo(x: TupleAny[str]) -> None: # no error
2090 pass
2091
2092 def goo(x: TupleAny[Any]) -> None: # E: Explicit "Any" is not allowed [explicit-any]
2093 pass
2094 [builtins fixtures/tuple.pyi]
2095
2096 [case testDisallowAnyExplicitCast]
2097 # flags: --disallow-any-explicit --show-error-codes
2098 from typing import Any, List, cast
2099
2100 x = 1
2101 y = cast(Any, x) # E: Explicit "Any" is not allowed [explicit-any]
2102 z = cast(List[Any], x) # E: Explicit "Any" is not allowed [explicit-any]
2103 [builtins fixtures/list.pyi]
2104
2105 [case testDisallowAnyExplicitNamedTuple]
2106 # flags: --disallow-any-explicit --show-error-codes
2107 from typing import Any, List, NamedTuple
2108
2109 Point = NamedTuple('Point', [('x', List[Any]), ('y', Any)]) # E: Explicit "Any" is not allowed [explicit-any]
2110 [builtins fixtures/list.pyi]
2111
2112 [case testDisallowAnyExplicitTypeVarConstraint]
2113 # flags: --disallow-any-explicit --show-error-codes
2114 from typing import Any, List, TypeVar
2115
2116 T = TypeVar('T', Any, List[Any]) # E: Explicit "Any" is not allowed [explicit-any]
2117 [builtins fixtures/list.pyi]
2118
2119 [case testDisallowAnyExplicitNewType]
2120 # flags: --disallow-any-explicit --show-error-codes
2121 from typing import Any, List, NewType
2122
2123 # this error does not come from `--disallow-any-explicit` flag
2124 Baz = NewType('Baz', Any) # E: Argument 2 to NewType(...) must be subclassable (got "Any") [valid-newtype]
2125 Bar = NewType('Bar', List[Any]) # E: Explicit "Any" is not allowed [explicit-any]
2126 [builtins fixtures/list.pyi]
2127
2128 [case testDisallowAnyExplicitTypedDictSimple]
2129 # flags: --disallow-any-explicit --show-error-codes
2130 from typing import Any, TypedDict
2131
2132 M = TypedDict('M', {'x': str, 'y': Any}) # E: Explicit "Any" is not allowed [explicit-any]
2133 M(x='x', y=2) # no error
2134 def f(m: M) -> None: pass # no error
2135 [builtins fixtures/dict.pyi]
2136 [typing fixtures/typing-typeddict.pyi]
2137
2138 [case testDisallowAnyExplicitTypedDictGeneric]
2139 # flags: --disallow-any-explicit --show-error-codes
2140 from typing import Any, List, TypedDict
2141
2142 M = TypedDict('M', {'x': str, 'y': List[Any]}) # E: Explicit "Any" is not allowed [explicit-any]
2143 N = TypedDict('N', {'x': str, 'y': List}) # no error
2144 [builtins fixtures/dict.pyi]
2145 [typing fixtures/typing-typeddict.pyi]
2146
2147 [case testDisallowAnyGenericsTupleNoTypeParams]
2148 # flags: --disallow-any-generics
2149 from typing import Tuple
2150
2151 def f(s: Tuple) -> None: pass # E: Missing type arguments for generic type "Tuple"
2152 def g(s) -> Tuple: # E: Missing type arguments for generic type "Tuple"
2153 return 'a', 'b'
2154 def h(s) -> Tuple[str, str]: # no error
2155 return 'a', 'b'
2156 x: Tuple = () # E: Missing type arguments for generic type "Tuple"
2157 [builtins fixtures/tuple.pyi]
2158
2159 [case testDisallowAnyGenericsTupleWithNoTypeParamsGeneric]
2160 # flags: --disallow-any-generics
2161 from typing import Tuple, List
2162
2163 def f(s: Tuple) -> None: pass # E: Missing type arguments for generic type "Tuple"
2164 def g(s: List[Tuple]) -> None: pass # E: Missing type arguments for generic type "Tuple"
2165 def h(s: List[Tuple[str, str]]) -> None: pass # no error
2166 [builtins fixtures/list.pyi]
2167
2168 [case testDisallowAnyGenericsTypeType]
2169 # flags: --disallow-any-generics
2170 from typing import Type, Any
2171
2172 def f(s: Type[Any]) -> None: pass # no error
2173 def g(s) -> Type: # E: Missing type arguments for generic type "Type"
2174 return s
2175 def h(s) -> Type[str]: # no error
2176 return s
2177 x: Type = g(0) # E: Missing type arguments for generic type "Type"
2178
2179 [case testDisallowAnyGenericsAliasGenericType]
2180 # flags: --disallow-any-generics
2181 from typing import List
2182
2183 L = List # no error
2184
2185 def f(l: L) -> None: pass # E: Missing type arguments for generic type "L"
2186 def g(l: L[str]) -> None: pass # no error
2187 [builtins fixtures/list.pyi]
2188
2189 [case testDisallowAnyGenericsGenericAlias]
2190 # flags: --disallow-any-generics
2191 from typing import TypeVar, Tuple
2192
2193 T = TypeVar('T')
2194 A = Tuple[T, str, T]
2195
2196 def f(s: A) -> None: pass # E: Missing type arguments for generic type "A"
2197 def g(s) -> A: # E: Missing type arguments for generic type "A"
2198 return 'a', 'b', 1
2199 def h(s) -> A[str]: # no error
2200 return 'a', 'b', 'c'
2201 x: A = ('a', 'b', 1) # E: Missing type arguments for generic type "A"
2202 [builtins fixtures/tuple.pyi]
2203
2204 [case testDisallowAnyGenericsPlainList]
2205 # flags: --disallow-any-generics
2206 from typing import List
2207
2208 def f(l: List) -> None: pass # E: Missing type arguments for generic type "List"
2209 def g(l: List[str]) -> None: pass
2210 def h(l: List[List]) -> None: pass # E: Missing type arguments for generic type "List"
2211 def i(l: List[List[List[List]]]) -> None: pass # E: Missing type arguments for generic type "List"
2212 def j() -> List: pass # E: Missing type arguments for generic type "List"
2213
2214 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
2215 y: List = [] # E: Missing type arguments for generic type "List"
2216 [builtins fixtures/list.pyi]
2217
2218 [case testDisallowAnyGenericsPlainDict]
2219 # flags: --disallow-any-generics
2220 from typing import List, Dict
2221
2222 def f(d: Dict) -> None: pass # E: Missing type arguments for generic type "Dict"
2223 def g(d: Dict[str, Dict]) -> None: pass # E: Missing type arguments for generic type "Dict"
2224 def h(d: List[Dict]) -> None: pass # E: Missing type arguments for generic type "Dict"
2225
2226 d: Dict = {} # E: Missing type arguments for generic type "Dict"
2227 [builtins fixtures/dict.pyi]
2228
2229 [case testDisallowAnyGenericsPlainSet]
2230 # flags: --disallow-any-generics
2231 from typing import Set
2232
2233 def f(s: Set) -> None: pass # E: Missing type arguments for generic type "Set"
2234 def g(s: Set[Set]) -> None: pass # E: Missing type arguments for generic type "Set"
2235
2236 s: Set = set() # E: Missing type arguments for generic type "Set"
2237 [builtins fixtures/set.pyi]
2238
2239 [case testDisallowAnyGenericsCustomGenericClass]
2240 # flags: --disallow-any-generics
2241 from typing import Generic, TypeVar, Any
2242
2243 T = TypeVar('T')
2244 class G(Generic[T]): pass
2245
2246 def f() -> G: # E: Missing type arguments for generic type "G"
2247 return G()
2248
2249 x: G[Any] = G() # no error
2250 y: G = x # E: Missing type arguments for generic type "G"
2251
2252 [case testDisallowAnyGenericsForAliasesInRuntimeContext]
2253 # flags: --disallow-any-generics
2254 from typing import Any, TypeVar, Generic, Tuple
2255
2256 T = TypeVar("T")
2257 class G(Generic[T]):
2258 @classmethod
2259 def foo(cls) -> T: ...
2260
2261 A = G[Tuple[T, T]]
2262 A() # E: Missing type arguments for generic type "A"
2263 A.foo() # E: Missing type arguments for generic type "A"
2264
2265 B = G
2266 B()
2267 B.foo()
2268
2269 def foo(x: Any) -> None: ...
2270 foo(A)
2271 foo(A.foo)
2272 [builtins fixtures/classmethod.pyi]
2273
2274 [case testDisallowSubclassingAny]
2275 # flags: --config-file tmp/mypy.ini
2276 import m
2277 import y
2278
2279 [file m.py]
2280 from typing import Any
2281
2282 x = None # type: Any
2283
2284 class ShouldBeFine(x): ...
2285
2286 [file y.py]
2287 from typing import Any
2288
2289 x = None # type: Any
2290
2291 class ShouldNotBeFine(x): ... # E: Class cannot subclass "x" (has type "Any")
2292
2293 [file mypy.ini]
2294 \[mypy]
2295 disallow_subclassing_any = True
2296 \[mypy-m]
2297 disallow_subclassing_any = False
2298
2299
2300 [case testDisallowSubclassingAnyPyProjectTOML]
2301 # flags: --config-file tmp/pyproject.toml
2302 import m
2303 import y
2304
2305 [file m.py]
2306 from typing import Any
2307
2308 x = None # type: Any
2309
2310 class ShouldBeFine(x): ...
2311
2312 [file y.py]
2313 from typing import Any
2314
2315 x = None # type: Any
2316
2317 class ShouldNotBeFine(x): ... # E: Class cannot subclass "x" (has type "Any")
2318
2319 [file pyproject.toml]
2320 \[tool.mypy]
2321 disallow_subclassing_any = true
2322 \[[tool.mypy.overrides]]
2323 module = 'm'
2324 disallow_subclassing_any = false
2325
2326
2327 [case testNoImplicitOptionalPerModule]
2328 # flags: --config-file tmp/mypy.ini
2329 import m
2330
2331 [file m.py]
2332 def f(a: str = None) -> int:
2333 return 0
2334
2335 [file mypy.ini]
2336 \[mypy]
2337 no_implicit_optional = True
2338 \[mypy-m]
2339 no_implicit_optional = False
2340
2341
2342 [case testNoImplicitOptionalPerModulePyProjectTOML]
2343 # flags: --config-file tmp/pyproject.toml
2344 import m
2345
2346 [file m.py]
2347 def f(a: str = None) -> int:
2348 return 0
2349
2350 [file pyproject.toml]
2351 \[tool.mypy]
2352 no_implicit_optional = true
2353 \[[tool.mypy.overrides]]
2354 module = 'm'
2355 no_implicit_optional = false
2356
2357 [case testDisableErrorCode]
2358 # flags: --disable-error-code attr-defined
2359 x = 'should be fine'
2360 x.trim()
2361
2362 [case testDisableDifferentErrorCode]
2363 # flags: --disable-error-code name-defined --show-error-codes
2364 x = 'should not be fine'
2365 x.trim() # E: "str" has no attribute "trim" [attr-defined]
2366
2367 [case testDisableMultipleErrorCode]
2368 # flags: --disable-error-code attr-defined --disable-error-code return-value --show-error-codes
2369 x = 'should be fine'
2370 x.trim()
2371
2372 def bad_return_type() -> str:
2373 return None
2374
2375 bad_return_type('no args taken!') # E: Too many arguments for "bad_return_type" [call-arg]
2376
2377 [case testEnableErrorCode]
2378 # flags: --disable-error-code attr-defined --enable-error-code attr-defined --show-error-codes
2379 x = 'should be fine'
2380 x.trim() # E: "str" has no attribute "trim" [attr-defined]
2381
2382 [case testEnableDifferentErrorCode]
2383 # flags: --disable-error-code attr-defined --enable-error-code name-defined --show-error-codes
2384 x = 'should not be fine'
2385 x.trim()
2386 y.trim() # E: Name "y" is not defined [name-defined]
2387
2388 [case testEnableMultipleErrorCode]
2389 # flags: \
2390 --disable-error-code attr-defined \
2391 --disable-error-code return-value \
2392 --disable-error-code call-arg \
2393 --enable-error-code attr-defined \
2394 --enable-error-code return-value --show-error-codes
2395 x = 'should be fine'
2396 x.trim() # E: "str" has no attribute "trim" [attr-defined]
2397
2398 def bad_return_type() -> str:
2399 return None # E: Incompatible return value type (got "None", expected "str") [return-value]
2400
2401 bad_return_type('no args taken!')
2402
2403 [case testDisallowUntypedCallsArgType]
2404 # flags: --disallow-untyped-calls
2405 def f(x):
2406 pass
2407
2408 y = 1
2409 f(reveal_type(y)) # E: Call to untyped function "f" in typed context \
2410 # N: Revealed type is "builtins.int"
2411
2412 [case testDisallowUntypedCallsAllowListFlags]
2413 # flags: --disallow-untyped-calls --untyped-calls-exclude=foo --untyped-calls-exclude=bar.A
2414 from foo import test_foo
2415 from bar import A, B
2416 from baz import test_baz
2417 from foobar import bad
2418
2419 test_foo(42) # OK
2420 test_baz(42) # E: Call to untyped function "test_baz" in typed context
2421 bad(42) # E: Call to untyped function "bad" in typed context
2422
2423 a: A
2424 b: B
2425 a.meth() # OK
2426 b.meth() # E: Call to untyped function "meth" in typed context
2427 [file foo.py]
2428 def test_foo(x): pass
2429 [file foobar.py]
2430 def bad(x): pass
2431 [file bar.py]
2432 class A:
2433 def meth(self): pass
2434 class B:
2435 def meth(self): pass
2436 [file baz.py]
2437 def test_baz(x): pass
2438
2439 [case testDisallowUntypedCallsAllowListConfig]
2440 # flags: --config-file tmp/mypy.ini
2441 from foo import test_foo
2442 from bar import A, B
2443 from baz import test_baz
2444
2445 test_foo(42) # OK
2446 test_baz(42) # E: Call to untyped function "test_baz" in typed context
2447
2448 a: A
2449 b: B
2450 a.meth() # OK
2451 b.meth() # E: Call to untyped function "meth" in typed context
2452 [file foo.py]
2453 def test_foo(x): pass
2454 [file bar.py]
2455 class A:
2456 def meth(self): pass
2457 class B:
2458 def meth(self): pass
2459 [file baz.py]
2460 def test_baz(x): pass
2461
2462 [file mypy.ini]
2463 \[mypy]
2464 disallow_untyped_calls = True
2465 untyped_calls_exclude = foo, bar.A
2466
2467 [case testPerModuleErrorCodes]
2468 # flags: --config-file tmp/mypy.ini
2469 import tests.foo
2470 import bar
2471 [file bar.py]
2472 x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
2473 [file tests/__init__.py]
2474 [file tests/foo.py]
2475 x = [] # OK
2476 [file mypy.ini]
2477 \[mypy]
2478 strict = True
2479
2480 \[mypy-tests.*]
2481 allow_untyped_defs = True
2482 allow_untyped_calls = True
2483 disable_error_code = var-annotated
2484
2485 [case testPerFileIgnoreErrors]
2486 # flags: --config-file tmp/mypy.ini
2487 import foo, bar
2488 [file foo.py]
2489 x: str = 5
2490 [file bar.py]
2491 x: str = 5 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
2492 [file mypy.ini]
2493 \[mypy]
2494 \[mypy-foo]
2495 ignore_errors = True
2496
2497 [case testPerFileUntypedDefs]
2498 # flags: --config-file tmp/mypy.ini
2499 import x, y, z
2500 [file x.py]
2501 def f(a): ... # E: Function is missing a type annotation
2502 def g(a: int) -> int: return f(a)
2503 [file y.py]
2504 def f(a): pass
2505 def g(a: int) -> int: return f(a)
2506 [file z.py]
2507 def f(a): pass # E: Function is missing a type annotation
2508 def g(a: int) -> int: return f(a) # E: Call to untyped function "f" in typed context
2509 [file mypy.ini]
2510 \[mypy]
2511 disallow_untyped_defs = True
2512 \[mypy-y]
2513 disallow_untyped_defs = False
2514 \[mypy-z]
2515 disallow_untyped_calls = True
2516
2517 [case testPerModuleErrorCodesOverride]
2518 # flags: --config-file tmp/mypy.ini
2519 import tests.foo
2520 import bar
2521 [file bar.py]
2522 def foo() -> int: ...
2523 if foo: ... # E: Function "foo" could always be true in boolean context
2524 42 + "no" # type: ignore # E: "type: ignore" comment without error code (consider "type: ignore[operator]" instead)
2525 [file tests/__init__.py]
2526 [file tests/foo.py]
2527 def foo() -> int: ...
2528 if foo: ... # E: Function "foo" could always be true in boolean context
2529 42 + "no" # type: ignore
2530 [file mypy.ini]
2531 \[mypy]
2532 enable_error_code = ignore-without-code, truthy-bool, used-before-def
2533
2534 \[mypy-tests.*]
2535 disable_error_code = ignore-without-code
2536
2537 [case testShowErrorCodes]
2538 # flags: --show-error-codes
2539 x: int = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
2540
2541 [case testHideErrorCodes]
2542 # flags: --hide-error-codes
2543 x: int = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2544
2545 [case testStrictBytes]
2546 # flags: --strict-bytes
2547 def f(x: bytes) -> None: ...
2548 f(bytearray(b"asdf")) # E: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"
2549 f(memoryview(b"asdf")) # E: Argument 1 to "f" has incompatible type "memoryview"; expected "bytes"
2550 [builtins fixtures/primitives.pyi]
2551
2552 [case testNoStrictBytes]
2553 # flags: --no-strict-bytes
2554 def f(x: bytes) -> None: ...
2555 f(bytearray(b"asdf"))
2556 f(memoryview(b"asdf"))
2557 [builtins fixtures/primitives.pyi]
2558
2559 [case testNoCrashFollowImportsForStubs]
2560 # flags: --config-file tmp/mypy.ini
2561 {**{"x": "y"}}
2562
2563 [file mypy.ini]
2564 \[mypy]
2565 follow_imports = skip
2566 follow_imports_for_stubs = true
2567 [builtins fixtures/dict.pyi]
2568
2569 [case testReturnAnyLambda]
2570 # flags: --warn-return-any
2571 from typing import Any, Callable
2572
2573 def cb(f: Callable[[int], int]) -> None: ...
2574 a: Any
2575 cb(lambda x: a) # OK
2576
2577 fn = lambda x: a
2578 cb(fn)
2579
2580 [case testShowErrorCodeLinks]
2581 # flags: --show-error-codes --show-error-code-links
2582
2583 x: int = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
2584 list(1) # E: No overload variant of "list" matches argument type "int" [call-overload] \
2585 # N: Possible overload variants: \
2586 # N: def [T] list() -> list[T] \
2587 # N: def [T] list(x: Iterable[T]) -> list[T] \
2588 # N: See https://mypy.rtfd.io/en/stable/_refs.html#code-call-overload for more info
2589 list(2) # E: No overload variant of "list" matches argument type "int" [call-overload] \
2590 # N: Possible overload variants: \
2591 # N: def [T] list() -> list[T] \
2592 # N: def [T] list(x: Iterable[T]) -> list[T]
2593 [builtins fixtures/list.pyi]
2594
2595 [case testNestedGenericInAliasDisallow]
2596 # flags: --disallow-any-generics
2597 from typing import TypeVar, Generic, List, Union
2598
2599 class C(Generic[T]): ...
2600
2601 A = Union[C, List] # E: Missing type arguments for generic type "C" \
2602 # E: Missing type arguments for generic type "List"
2603
2604 [builtins fixtures/list.pyi]
2605
2606 [case testNestedGenericInAliasAllow]
2607 # flags: --allow-any-generics
2608 from typing import TypeVar, Generic, List, Union
2609
2610 class C(Generic[T]): ...
2611
2612 A = Union[C, List] # OK
2613 [builtins fixtures/list.pyi]
2614
2615 [case testNotesOnlyResultInExitSuccess]
2616 -- check_untyped_defs is False by default.
2617 def f():
2618 x: int = "no" # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs
2619
2620 [case testRedefineLocalWithDifferentTypeAlias]
2621 # flags: --allow-redefinition-old
2622 def f() -> None:
2623 x = 0
2624 reveal_type(x) # N: Revealed type is "builtins.int"
2625 x = ''
2626 reveal_type(x) # N: Revealed type is "builtins.str"
2627
2628 [case testRedefineLocalWithDifferentTypeInline]
2629 # mypy: allow-redefinition-old
2630 def f() -> None:
2631 x = 0
2632 reveal_type(x) # N: Revealed type is "builtins.int"
2633 x = ''
2634 reveal_type(x) # N: Revealed type is "builtins.str"
2635
2636 [case testRedefineLocalWithDifferentTypeInverse]
2637 # flags: --disallow-redefinition-old
2638 def f() -> None:
2639 x = 0
2640 reveal_type(x) # N: Revealed type is "builtins.int"
2641 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2642
2643 [case testRedefineLocalWithDifferentTypeConfigAlias]
2644 # flags: --config-file tmp/mypy.ini
2645 def f() -> None:
2646 x = 0
2647 reveal_type(x) # N: Revealed type is "builtins.int"
2648 x = ''
2649 reveal_type(x) # N: Revealed type is "builtins.str"
2650 [file mypy.ini]
2651 \[mypy]
2652 allow_redefinition_old = true
2653
2654 [case testRedefineLocalWithDifferentTypeConfigOld]
2655 # flags: --config-file tmp/mypy.ini
2656 def f() -> None:
2657 x = 0
2658 reveal_type(x) # N: Revealed type is "builtins.int"
2659 x = ''
2660 reveal_type(x) # N: Revealed type is "builtins.str"
2661 [file mypy.ini]
2662 \[mypy]
2663 allow_redefinition_old = true
2664
2665 [case testRedefineLocalWithDifferentTypeConfigInverse]
2666 # flags: --config-file tmp/mypy.ini
2667 def f() -> None:
2668 x = 0
2669 reveal_type(x) # N: Revealed type is "builtins.int"
2670 x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
2671 [file mypy.ini]
2672 \[mypy]
2673 disallow_redefinition_old = true
2674
2675 [case testRevealSimpleTypes_no_verbose_reveal]
2676 from typing import Generic, TypeVar, Callable
2677 from typing_extensions import TypeVarTuple, Unpack, TypedDict
2678
2679 T = TypeVar("T", bound=int)
2680 S = TypeVar("S", default=list[T])
2681
2682 class A(Generic[T, S]): ...
2683 reveal_type(A) # N: Revealed type is "def [T <: int, S = list[T]] () -> __main__.A[T, S]"
2684
2685 Ts = TypeVarTuple("Ts")
2686 def foo(x: int, *xs: Unpack[Ts]) -> tuple[int, Unpack[Ts]]: ...
2687 reveal_type(foo) # N: Revealed type is "def [Ts] (x: int, *xs: *Ts) -> tuple[int, *Ts]"
2688
2689 class User(TypedDict):
2690 age: int
2691 name: str
2692
2693 def bar(x: int, **kwargs: Unpack[User]) -> None: ...
2694 reveal_type(bar) # N: Revealed type is "def (x: int, **kwargs: **TypedDict(__main__.User, {'age': int, 'name': str}))"
2695
2696 fn: Callable[[Unpack[Ts], Unpack[User]], tuple[Unpack[Ts]]]
2697 reveal_type(fn) # N: Revealed type is "def [Ts] (*args: *Ts, **kwargs: **TypedDict(__main__.User, {'age': int, 'name': str})) -> tuple[*Ts]"
2698
2699 fx: Callable[[int, Unpack[Ts], int], tuple[Unpack[Ts]]]
2700 reveal_type(fx) # N: Revealed type is "def [Ts] (int, *args: *tuple[*Ts, int]) -> tuple[*Ts]"
2701 [builtins fixtures/tuple.pyi]
2702
2703 [case testOnlyOneRedefinitionModeAllowed]
2704 # flags: --allow-redefinition --allow-redefinition-old
2705 x = 1
2706 [out]
2707 main:1: error: --allow-redefinition-old and --allow-redefinition should not be used together
2708
2709 [case testRedundantExpressionMultiline]
2710 # mypy: enable-error-code="redundant-expr"
2711 x: int
2712 y: int
2713 z: int
2714 if (
2715 x is None # E: Left operand of "or" is always false
2716 or y is None # E: Left operand of "or" is always false
2717 or z is None
2718 ):
2719 pass
2720
2721 [case testRecursiveTypeVarDefaultMutualDisallow]
2722 # flags: --disallow-any-generic
2723 from typing import TypeVar, Generic
2724
2725 class C(Generic["T"]):
2726 pass
2727
2728 class D(Generic["S"]):
2729 pass
2730
2731 T = TypeVar("T", default=D) # E: Missing type arguments for generic type "D" \
2732 # N: Cyclic type variable defaults are not supported
2733 S = TypeVar("S", default=C) # E: Missing type arguments for generic type "C" \
2734 # N: Cyclic type variable defaults are not supported
2735
2736 c: C
2737 d: D
2738 reveal_type(c) # N: Revealed type is "__main__.C[__main__.D[Any]]"
2739 reveal_type(d) # N: Revealed type is "__main__.D[__main__.C[Any]]"
2740
2741 [case testRecursiveTypeVarDefaultOnlyAliasDisallow]
2742 # flags: --disallow-any-generic
2743 from typing import TypeVar
2744
2745 T = TypeVar("T", default="A") # E: Missing type arguments for generic type "A" \
2746 # N: Cyclic type variable defaults are not supported
2747 A = list[T]
2748 a: A
2749 reveal_type(a) # N: Revealed type is "builtins.list[builtins.list[Any]]"
2750 [builtins fixtures/tuple.pyi]