-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathcheck-errorcodes.test
1241 lines (982 loc) · 43 KB
/
check-errorcodes.test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Tests for error codes and ignoring errors using error codes
--
-- These implicitly use --show-error-codes.
[case testErrorCodeNoAttribute]
import m
m.x # E: Module has no attribute "x" [attr-defined]
'x'.foobar # E: "str" has no attribute "foobar" [attr-defined]
from m import xx # E: Module "m" has no attribute "xx" [attr-defined]
from m import think # E: Module "m" has no attribute "think"; maybe "thing"? [attr-defined]
for x in 1: # E: "int" has no attribute "__iter__" (not iterable) [attr-defined]
pass
[file m.py]
thing = 0
[builtins fixtures/module.pyi]
[case testErrorCodeUndefinedName]
x # E: Name "x" is not defined [name-defined]
def f() -> None:
y # E: Name "y" is not defined [name-defined]
[file m.py]
[builtins fixtures/module.pyi]
[case testErrorCodeUnclassifiedError]
class A:
def __init__(self) -> int: \
# E: The return type of "__init__" must be None [misc]
pass
[case testErrorCodeNoteHasNoCode]
reveal_type(1) # N: Revealed type is "Literal[1]?"
[case testErrorCodeSyntaxError]
1 ''
[out]
main:1: error: invalid syntax [syntax]
[out version==3.10.0]
main:1: error: invalid syntax. Perhaps you forgot a comma? [syntax]
[case testErrorCodeSyntaxError2]
def f(): # E: Type signature has too many arguments [syntax]
# type: (int) -> None
1
x = 0 # type: x y # E: Syntax error in type comment "x y" [syntax]
[case testErrorCodeSyntaxError3]
# This is a bit inconsistent -- syntax error would be more logical?
x: 'a b' # E: Invalid type comment or annotation [valid-type]
for v in x: # type: int, int # E: Syntax error in type annotation [syntax] \
# N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)
pass
[case testErrorCodeSyntaxErrorIgnoreNote]
# This is a bit inconsistent -- syntax error would be more logical?
x: 'a b' # type: ignore[valid-type]
for v in x: # type: int, int # type: ignore[syntax]
pass
[case testErrorCodeIgnore1]
'x'.foobar # type: ignore[attr-defined]
'x'.foobar # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \
# N: Error code "attr-defined" not covered by "type: ignore" comment
'x'.foobar # type: ignore
[case testErrorCodeIgnore2]
a = 'x'.foobar # type: int # type: ignore[attr-defined]
b = 'x'.foobar # type: int # type: ignore[xyz] # E: "str" has no attribute "foobar" [attr-defined] \
# N: Error code "attr-defined" not covered by "type: ignore" comment
c = 'x'.foobar # type: int # type: ignore
[case testErrorCodeIgnoreMultiple1]
a = 'x'.foobar(b) # type: ignore[name-defined, attr-defined]
a = 'x'.foobar(b) # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \
# N: Error code "attr-defined" not covered by "type: ignore" comment
a = 'x'.foobar(b) # type: ignore[xyz, w, attr-defined] # E: Name "b" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
[case testErrorCodeIgnoreMultiple2]
a = 'x'.foobar(c) # type: int # type: ignore[name-defined, attr-defined]
b = 'x'.foobar(c) # type: int # type: ignore[name-defined, xyz] # E: "str" has no attribute "foobar" [attr-defined] \
# N: Error code "attr-defined" not covered by "type: ignore" comment
[case testErrorCodeWarnUnusedIgnores1]
# flags: --warn-unused-ignores
x # type: ignore[name-defined, attr-defined] # E: Unused "type: ignore[attr-defined]" comment [unused-ignore]
[case testErrorCodeWarnUnusedIgnores2]
# flags: --warn-unused-ignores
"x".foobar(y) # type: ignore[name-defined, attr-defined]
[case testErrorCodeWarnUnusedIgnores3]
# flags: --warn-unused-ignores
"x".foobar(y) # type: ignore[name-defined, attr-defined, xyz] # E: Unused "type: ignore[xyz]" comment [unused-ignore]
[case testErrorCodeWarnUnusedIgnores4]
# flags: --warn-unused-ignores
"x".foobar(y) # type: ignore[name-defined, attr-defined, valid-type] # E: Unused "type: ignore[valid-type]" comment [unused-ignore]
[case testErrorCodeWarnUnusedIgnores5]
# flags: --warn-unused-ignores
"x".foobar(y) # type: ignore[name-defined, attr-defined, valid-type, xyz] # E: Unused "type: ignore[valid-type, xyz]" comment [unused-ignore]
[case testErrorCodeWarnUnusedIgnores6_NoDetailWhenSingleErrorCode]
# flags: --warn-unused-ignores
"x" # type: ignore[name-defined] # E: Unused "type: ignore" comment [unused-ignore]
[case testErrorCodeMissingWhenRequired]
# flags: --enable-error-code ignore-without-code
"x" # type: ignore # E: "type: ignore" comment without error code [ignore-without-code]
y # type: ignore # E: "type: ignore" comment without error code (consider "type: ignore[name-defined]" instead) [ignore-without-code]
z # type: ignore[name-defined]
"a" # type: ignore[ignore-without-code]
[case testErrorCodeMissingDoesntTrampleUnusedIgnoresWarning]
# flags: --enable-error-code ignore-without-code --warn-unused-ignores
"x" # type: ignore # E: Unused "type: ignore" comment [unused-ignore]
"y" # type: ignore[ignore-without-code] # E: Unused "type: ignore" comment [unused-ignore]
z # type: ignore[ignore-without-code] # E: Unused "type: ignore" comment [unused-ignore] \
# E: Name "z" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
[case testErrorCodeMissingWholeFileIgnores]
# flags: --enable-error-code ignore-without-code
# type: ignore # whole file ignore
x
y # type: ignore # ignore the lack of error code since we ignore the whole file
[case testErrorCodeMissingMultiple]
# flags: --enable-error-code ignore-without-code
from __future__ import annotations
class A:
attr: int
def func(self, var: int) -> A | None: ...
a: A | None
# 'union-attr' should only be listed once (instead of twice) and list should be sorted
a.func("invalid string").attr # type: ignore # E: "type: ignore" comment without error code (consider "type: ignore[arg-type, union-attr]" instead) [ignore-without-code]
[builtins fixtures/tuple.pyi]
[case testErrorCodeIgnoreWithExtraSpace]
x # type: ignore [name-defined]
x2 # type: ignore [ name-defined ]
x3 # type: ignore [ xyz , name-defined ]
x4 # type: ignore[xyz,name-defined]
y # type: ignore [xyz] # E: Name "y" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
y # type: ignore[ xyz ] # E: Name "y" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
y # type: ignore[ xyz , foo ] # E: Name "y" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
a = z # type: int # type: ignore [name-defined]
b = z2 # type: int # type: ignore [ name-defined ]
c = z2 # type: int # type: ignore [ name-defined , xyz ]
d = zz # type: int # type: ignore [xyz] # E: Name "zz" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
e = zz # type: int # type: ignore [ xyz ] # E: Name "zz" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
f = zz # type: int # type: ignore [ xyz,foo ] # E: Name "zz" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
[case testErrorCodeIgnoreAfterArgComment]
def f(x # type: xyz # type: ignore[name-defined] # Comment
):
# type () -> None
pass
def g(x # type: xyz # type: ignore # Comment
):
# type () -> None
pass
def h(x # type: xyz # type: ignore[foo] # E: Name "xyz" is not defined [name-defined] \
# N: Error code "name-defined" not covered by "type: ignore" comment
):
# type () -> None
pass
[case testErrorCodeIgnoreWithNote]
import nostub # type: ignore[import]
from defusedxml import xyz # type: ignore[import]
[case testErrorCodeBadIgnore]
import nostub # type: ignore xyz # E: Invalid "type: ignore" comment [syntax] \
# E: Cannot find implementation or library stub for module named "nostub" [import-not-found] \
# N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
import nostub # type: ignore[ # E: Invalid "type: ignore" comment [syntax]
import nostub # type: ignore[foo # E: Invalid "type: ignore" comment [syntax]
import nostub # type: ignore[foo, # E: Invalid "type: ignore" comment [syntax]
import nostub # type: ignore[foo]] # E: Invalid "type: ignore" comment [syntax]
import nostub # type: ignore[foo][bar] # E: Invalid "type: ignore" comment [syntax]
import nostub # type: ignore[foo] [bar] # E: Invalid "type: ignore" comment [syntax]
x = 0 # type: ignore[ # E: Invalid "type: ignore" comment [syntax]
def f(x, # type: int # type: ignore[ # E: Invalid "type: ignore" comment [syntax]
):
# type: (...) -> None
pass
[case testErrorCodeBadIgnoreNoExtraComment]
# Omit the E: ... comments, as they affect parsing
import nostub # type: ignore xyz
import nostub # type: ignore[xyz
import nostub # type: ignore[xyz][xyz]
x = 0 # type: ignore[
def f(x, # type: int # type: ignore[
):
# type: (...) -> None
pass
[out]
main:2: error: Invalid "type: ignore" comment [syntax]
main:2: error: Cannot find implementation or library stub for module named "nostub" [import-not-found]
main:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
main:3: error: Invalid "type: ignore" comment [syntax]
main:4: error: Invalid "type: ignore" comment [syntax]
main:5: error: Invalid "type: ignore" comment [syntax]
main:6: error: Invalid "type: ignore" comment [syntax]
[case testErrorCodeArgKindAndCount]
def f(x: int) -> None: pass # N: "f" defined here
f() # E: Missing positional argument "x" in call to "f" [call-arg]
f(1, 2) # E: Too many arguments for "f" [call-arg]
f(y=1) # E: Unexpected keyword argument "y" for "f" [call-arg]
def g(*, x: int) -> None: pass
g() # E: Missing named argument "x" for "g" [call-arg]
def h(x: int, y: int, z: int) -> None: pass
h(y=1, z=1) # E: Missing positional argument "x" in call to "h" [call-arg]
h(y=1) # E: Missing positional arguments "x", "z" in call to "h" [call-arg]
[case testErrorCodeArgType]
def f(x: int) -> None: pass
f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int" [arg-type]
class A:
def g(self, *, x: int) -> None: pass
A().g(x='') # E: Argument "x" to "g" of "A" has incompatible type "str"; expected "int" [arg-type]
[case testErrorCodeInvalidType]
def f(): pass
x: f # E: Function "__main__.f" is not valid as a type [valid-type] \
# N: Perhaps you need "Callable[...]" or a callback protocol?
import sys
y: sys # E: Module "sys" is not valid as a type [valid-type] \
# N: Perhaps you meant to use a protocol matching the module structure?
z: y # E: Variable "__main__.y" is not valid as a type [valid-type] \
# N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
[builtins fixtures/tuple.pyi]
[case testErrorCodeNeedTypeAnnotation]
from typing import TypeVar
T = TypeVar('T')
def f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar [type-var]
x = f() # E: Need type annotation for "x" [var-annotated]
y = [] # E: Need type annotation for "y" (hint: "y: List[<type>] = ...") [var-annotated]
[builtins fixtures/list.pyi]
[case testErrorCodeBadOverride]
from typing import overload
class A:
def f(self) -> int:
return 0
class B(A):
def f(self) -> str: # E: Return type "str" of "f" incompatible with return type "int" in supertype "A" [override]
return ''
class C(A):
def f(self, x: int) -> int: # E: Signature of "f" incompatible with supertype "A" [override] \
# N: Superclass: \
# N: def f(self) -> int \
# N: Subclass: \
# N: def f(self, x: int) -> int
return 0
class D:
def f(self, x: int) -> int:
return 0
class E(D):
def f(self, x: str) -> int: # E: Argument 1 of "f" is incompatible with supertype "D"; supertype defines the argument type as "int" [override] \
# N: This violates the Liskov substitution principle \
# N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
return 0
class O:
@overload
def f(self, x: int) -> None: pass
@overload
def f(self, x: str) -> None: pass
def f(self, x):
pass
class OO(O):
@overload # E: Signature of "f" incompatible with supertype "O" [override] \
# N: Overload variants must be defined in the same order as they are in "O"
def f(self, x: str) -> None: pass
@overload
def f(self, x: int) -> None: pass
def f(self, x):
pass
[case testErrorCodeReturnValue]
def f() -> int:
return '' # E: Incompatible return value type (got "str", expected "int") [return-value]
[case testErrorCodeMissingReturnValueInReturnStatement]
def f() -> int:
return # E: Return value expected [return-value]
[case testErrorCodeAssignment]
x: str = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "str") [assignment]
def f(x: str = 0) -> None: # E: Incompatible default for argument "x" (default has type "int", argument has type "str") [assignment]
pass
class A:
x = 0
class B(A):
x = '' # E: Incompatible types in assignment (expression has type "str", base class "A" defined the type as "int") [assignment]
a: A
a.x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int") [assignment]
[case testErrorCodeMissingTypeArg]
# flags: --python-version 3.8 --disallow-any-generics
from typing import List, TypeVar
x: List # E: Missing type parameters for generic type "List" [type-arg]
y: list # E: Implicit generic "Any". Use "typing.List" and specify generic parameters [type-arg]
T = TypeVar('T')
L = List[List[T]]
z: L # E: Missing type parameters for generic type "L" [type-arg]
[builtins fixtures/list.pyi]
[case testErrorCodeUnionAttribute]
from typing import Union
class A:
x: int
class B:
y: str
a: Union[A, B]
a.x # E: Item "B" of "Union[A, B]" has no attribute "x" [union-attr]
[case testErrorCodeFunctionHasNoAnnotation]
# flags: --disallow-untyped-defs
def f(x): # E: Function is missing a type annotation [no-untyped-def]
pass
def g(x: int): # E: Function is missing a return type annotation [no-untyped-def]
pass
def h(x) -> None: # E: Function is missing a type annotation for one or more arguments [no-untyped-def]
pass
def gen(): # E: Function is missing a return type annotation [no-untyped-def]
yield 1
def gen2(x: int): # E: Function is missing a return type annotation [no-untyped-def]
yield 1
async def asyncf(): # E: Function is missing a return type annotation [no-untyped-def]
return 0
async def asyncf2(x: int): # E: Function is missing a return type annotation [no-untyped-def]
return 0
[typing fixtures/typing-async.pyi]
[builtins fixtures/tuple.pyi]
[case testErrorCodeCallUntypedFunction]
# flags: --disallow-untyped-calls
def f() -> None:
g() # E: Call to untyped function "g" in typed context [no-untyped-call]
def g():
pass
[case testErrorCodeIndexing]
from typing import Dict
x: Dict[int, int]
x[''] # E: Invalid index type "str" for "Dict[int, int]"; expected type "int" [index]
1[''] # E: Value of type "int" is not indexable [index]
1[''] = 1 # E: Unsupported target for indexed assignment ("int") [index]
[builtins fixtures/dict.pyi]
[case testErrorCodeInvalidTypeArg]
from typing import TypeVar, Generic
T = TypeVar('T', int, str)
TT = TypeVar('TT', int, None)
S = TypeVar('S', bound=str)
def f(x: T) -> T:
return x
f(object()) # E: Value of type variable "T" of "f" cannot be "object" [type-var]
def g(x: S) -> S:
return x
g(1) # E: Value of type variable "S" of "g" cannot be "int" [type-var]
class C(Generic[T]): pass
class D(Generic[S]): pass
class E(Generic[S, T]): pass
x: C[object] # E: Value of type variable "T" of "C" cannot be "object" [type-var]
y: D[int] # E: Type argument "int" of "D" must be a subtype of "str" [type-var]
z: D[int, int] # E: "D" expects 1 type argument, but 2 given [type-arg]
def h(a: TT, s: S) -> None:
b: C[TT] # E: Invalid type argument value for "C" [type-var]
c: C[S] # E: Type variable "S" not valid as type argument value for "C" [type-var]
[case testErrorCodeOperators]
class A: pass
A() + 1 # E: Unsupported left operand type for + ("A") [operator]
1 in A() # E: Unsupported right operand type for in ("A") [operator]
A() < 1 # E: Unsupported left operand type for < ("A") [operator]
-A() # E: Unsupported operand type for unary - ("A") [operator]
+A() # E: Unsupported operand type for unary + ("A") [operator]
~A() # E: Unsupported operand type for ~ ("A") [operator]
class B:
def __add__(self, other: int) -> 'B':
return self
def __radd__(self, other: int) -> 'B':
return self
def __contains__(self, other: int) -> int:
return 0
B() + '' # E: Unsupported operand types for + ("B" and "str") [operator]
'' + B() # E: Unsupported operand types for + ("str" and "B") [operator]
'' in B() # E: Unsupported operand types for in ("str" and "B") [operator]
1() # E: "int" not callable [operator]
[builtins fixtures/tuple.pyi]
[case testErrorCodeListOrDictItem]
from typing import List, Dict
x: List[int] = [''] # E: List item 0 has incompatible type "str"; expected "int" [list-item]
y: Dict[int, int] = {1: ''} # E: Dict entry 0 has incompatible type "int": "str"; expected "int": "int" [dict-item]
[builtins fixtures/dict.pyi]
[case testErrorCodeTypedDict]
from typing_extensions import TypedDict
class D(TypedDict):
x: int
class E(TypedDict):
x: int
y: int
a: D = {'x': ''} # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [typeddict-item]
b: D = {'y': ''} # E: Missing key "x" for TypedDict "D" [typeddict-item] \
# E: Extra key "y" for TypedDict "D" [typeddict-unknown-key]
c = D(x=0) if int() else E(x=0, y=0)
c = {} # E: Missing key "x" for TypedDict "D" [typeddict-item]
d: D = {'x': '', 'y': 1} # E: Extra key "y" for TypedDict "D" [typeddict-unknown-key] \
# E: Incompatible types (expression has type "str", TypedDict item "x" has type "int") [typeddict-item]
a['y'] = 1 # E: TypedDict "D" has no key "y" [typeddict-unknown-key]
a['x'] = 'x' # E: Value of "x" has incompatible type "str"; expected "int" [typeddict-item]
a['y'] # E: TypedDict "D" has no key "y" [typeddict-item]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[case testErrorCodeTypedDictNoteIgnore]
from typing_extensions import TypedDict
class A(TypedDict):
one_commonpart: int
two_commonparts: int
a: A = {'one_commonpart': 1, 'two_commonparts': 2}
a['other_commonpart'] = 3 # type: ignore[typeddict-unknown-key]
not_exist = a['not_exist'] # type: ignore[typeddict-item]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[case testErrorCodeTypedDictSubCodeIgnore]
from typing_extensions import TypedDict
class D(TypedDict):
x: int
d: D = {'x': 1, 'y': 2} # type: ignore[typeddict-item]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[case testErrorCodeCannotDetermineType]
y = x # E: Cannot determine type of "x" [has-type] # E: Name "x" is used before definition [used-before-def]
reveal_type(y) # N: Revealed type is "Any"
x = None
[case testErrorCodeRedundantCast]
# flags: --warn-redundant-casts
from typing import cast
x = cast(int, int()) # E: Redundant cast to "int" [redundant-cast]
[case testErrorCodeInvalidCommentSignature]
def f(x): # E: Type signature has too few arguments [syntax]
# type: () -> None
pass
def g(x): # E: Type signature has too many arguments [syntax]
# type: (int, int) -> None
pass
[case testErrorCodeNonOverlappingEquality]
# flags: --strict-equality
if int() == str(): # E: Non-overlapping equality check (left operand type: "int", right operand type: "str") [comparison-overlap]
pass
if int() != str(): # E: Non-overlapping equality check (left operand type: "int", right operand type: "str") [comparison-overlap]
pass
if int() is str(): # E: Non-overlapping identity check (left operand type: "int", right operand type: "str") [comparison-overlap]
pass
[builtins fixtures/primitives.pyi]
[case testErrorCodeMissingModule]
from defusedxml import xyz # E: Library stubs not installed for "defusedxml" [import-untyped] \
# N: Hint: "python3 -m pip install types-defusedxml" \
# N: (or run "mypy --install-types" to install all missing stub packages)
from nonexistent import foobar # E: Cannot find implementation or library stub for module named "nonexistent" [import-not-found]
import nonexistent2 # E: Cannot find implementation or library stub for module named "nonexistent2" [import-not-found]
from nonexistent3 import * # E: Cannot find implementation or library stub for module named "nonexistent3" [import-not-found]
from pkg import bad # E: Module "pkg" has no attribute "bad" [attr-defined]
from pkg.bad2 import bad3 # E: Cannot find implementation or library stub for module named "pkg.bad2" [import-not-found] \
# N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
[file pkg/__init__.py]
[case testErrorCodeAlreadyDefined]
x: int
x: str # E: Name "x" already defined on line 1 [no-redef]
def f():
pass
def f(): # E: Name "f" already defined on line 4 [no-redef]
pass
[case testErrorCodeMissingReturn]
def f() -> int: # E: Missing return statement [return]
x = 0
[case testErrorCodeReturnValueNotExpected]
def f() -> None:
return 1 # E: No return value expected [return-value]
[case testErrorCodeFunctionDoesNotReturnValue]
from typing import Callable
def f() -> None: pass
x = f() # E: "f" does not return a value (it only ever returns None) [func-returns-value]
class A:
def g(self) -> None: pass
y = A().g() # E: "g" of "A" does not return a value (it only ever returns None) [func-returns-value]
c: Callable[[], None]
z = c() # E: Function does not return a value (it only ever returns None) [func-returns-value]
[case testErrorCodeInstantiateAbstract]
from abc import abstractmethod
class A:
@abstractmethod
def f(self): pass
class B(A):
pass
B() # E: Cannot instantiate abstract class "B" with abstract attribute "f" [abstract]
[case testErrorCodeNewTypeNotSubclassable]
from typing import Union, NewType
X = NewType('X', Union[int, str]) # E: Argument 2 to NewType(...) must be subclassable (got "Union[int, str]") [valid-newtype]
[case testErrorCodeOverloadVariant]
from typing import overload
@overload
def f(x: int) -> int: ...
@overload
def f(x: str) -> str: ...
def f(x):
return x
f(object()) # E: No overload variant of "f" matches argument type "object" [call-overload] \
# N: Possible overload variants: \
# N: def f(x: int) -> int \
# N: def f(x: str) -> str
f() # E: All overload variants of "f" require at least one argument [call-overload] \
# N: Possible overload variants: \
# N: def f(x: int) -> int \
# N: def f(x: str) -> str
f(1, 1) # E: No overload variant of "f" matches argument types "int", "int" [call-overload] \
# N: Possible overload variants: \
# N: def f(x: int) -> int \
# N: def f(x: str) -> str
[case testErrorCodeOverloadVariantIgnore]
from typing import overload
@overload
def f(x: int) -> int: ...
@overload
def f(x: str) -> str: ...
def f(x):
return x
f(object()) # type: ignore[call-overload]
[case testErrorCodeAnyFromUnfollowedImport]
# flags: --disallow-any-unimported
from m import C # type: ignore
def f(x: C) -> None: # E: Argument 1 to "f" becomes "Any" due to an unfollowed import [no-any-unimported]
pass
def g() -> C: ... # E: Return type becomes "Any" due to an unfollowed import [no-any-unimported]
[case testErrorCodeReturnAny]
# flags: --warn-return-any
def f(): pass
def g() -> int:
return f() # E: Returning Any from function declared to return "int" [no-any-return]
[case testErrorCodeFormatCall]
'{:d}'.format('no') # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "int") [str-format]
'{!x}'.format('Hm...') # E: Invalid conversion type "x", must be one of "r", "s" or "a" [str-format]
'}{'.format() # E: Invalid conversion specifier in format string: unexpected } [str-format]
'%d' % 'no' # E: Incompatible types in string interpolation (expression has type "str", placeholder has type "Union[int, float, SupportsInt]") [str-format]
'%d + %d' % (1, 2, 3) # E: Not all arguments converted during string formatting [str-format]
'{}'.format(b'abc') # E: If x = b'abc' then f"{x}" or "{}".format(x) produces "b'abc'", not "abc". If this is desired behavior, use f"{x!r}" or "{!r}".format(x). Otherwise, decode the bytes [str-bytes-safe]
'%s' % b'abc' # E: If x = b'abc' then "%s" % x produces "b'abc'", not "abc". If this is desired behavior use "%r" % x. Otherwise, decode the bytes [str-bytes-safe]
[builtins fixtures/primitives.pyi]
[typing fixtures/typing-medium.pyi]
[case testErrorCodeIgnoreNamedDefinedNote]
x: List[int] # type: ignore[name-defined]
[case testErrorCodeProtocolProblemsIgnore]
from typing_extensions import Protocol
class P(Protocol):
def f(self, x: str) -> None: ...
class A:
def f(self, x: int) -> None: ...
def g(p: P) -> None: pass
p: A
g(p) # type: ignore[arg-type]
[builtins fixtures/tuple.pyi]
[case testErrorCodeNoneReturnNoteIgnore]
# flags: --disallow-untyped-defs
def f(): # type: ignore[no-untyped-def]
pass
[case testErrorCodeVarianceNoteIgnore]
from typing import List
def f(x: List[object]) -> None: pass
a = [1]
f(a) # type: ignore[arg-type]
[builtins fixtures/list.pyi]
[case testErrorCodeAssignToMethod]
class A:
def f(self) -> None: pass
def g(self: A) -> None: pass
A.f = g # E: Cannot assign to a method [method-assign]
[case testErrorCodeDefinedHereNoteIgnore]
import m
m.f(kw=1) # type: ignore[call-arg]
[file m.py]
def f() -> None: pass
[case testErrorCodeUnionNoteIgnore]
from typing import Union
class Foo:
def __add__(self, x: Foo) -> Foo: pass
def __radd__(self, x: Foo) -> Foo: pass
class Bar:
def __add__(self, x: Bar) -> Bar: pass
def __radd__(self, x: Bar) -> Bar: pass
a: Union[Foo, Bar]
a + a # type: ignore[operator]
a + Foo() # type: ignore[operator]
Foo() + a # type: ignore[operator]
[case testErrorCodeTypeIgnoreMisspelled1]
x = y # type: ignored[foo]
xx = y # type: ignored [foo]
[out]
main:1: error: Name "ignored" is not defined [name-defined]
main:1: error: Name "y" is not defined [name-defined]
main:2: error: Name "ignored" is not defined [name-defined]
main:2: error: Name "y" is not defined [name-defined]
[case testErrorCodeTypeIgnoreMisspelled2]
x = y # type: int # type: ignored[foo]
x = y # type: int # type: ignored [foo]
[out]
main:1: error: Syntax error in type comment "int" [syntax]
main:2: error: Syntax error in type comment "int" [syntax]
[case testErrorCode__exit__Return]
class InvalidReturn:
def __exit__(self, x, y, z) -> bool: # E: "bool" is invalid as return type for "__exit__" that always returns False [exit-return] \
# N: Use "typing.Literal[False]" as the return type or change it to "None" \
# N: If return type of "__exit__" implies that it may return True, the context manager may swallow exceptions
return False
[builtins fixtures/bool.pyi]
[case testErrorCodeOverloadedOperatorMethod]
from typing import Optional, overload
class A:
@overload
def __add__(self, x: int) -> A: ...
@overload
def __add__(self, x: str) -> str: ...
def __add__(self, x): pass
class B:
pass
x: Optional[B]
A() + x # type: ignore[operator]
class C:
@overload
def __rsub__(self, x: int) -> A: ...
@overload
def __rsub__(self, x: str) -> str: ...
def __rsub__(self, x): pass
x - C() # type: ignore[operator]
[case testErrorCodeMultiLineBinaryOperatorOperand]
from typing import Optional
class C: pass
def f() -> Optional[C]:
return None
f( # type: ignore[operator]
) + C()
[case testErrorCodeSpecialArgTypeErrors]
from typing import TypedDict
class C(TypedDict):
x: int
c: C
c.setdefault('x', '1') # type: ignore[typeddict-item]
class A:
pass
class B(A):
def f(self) -> None:
super(1, self).foo() # type: ignore[arg-type]
def f(**x: int) -> None:
pass
f(**1) # type: ignore[arg-type]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[case testRedundantExpressions]
# flags: --enable-error-code redundant-expr
def foo() -> bool: ...
lst = [1, 2, 3, 4]
b = False or foo() # E: Left operand of "or" is always false [redundant-expr]
c = True and foo() # E: Left operand of "and" is always true [redundant-expr]
g = 3 if True else 4 # E: If condition is always true [redundant-expr]
h = 3 if False else 4 # E: If condition is always false [redundant-expr]
i = [x for x in lst if True] # E: If condition in comprehension is always true [redundant-expr]
j = [x for x in lst if False] # E: If condition in comprehension is always false [redundant-expr]
k = [x for x in lst if isinstance(x, int) or foo()] # E: If condition in comprehension is always true [redundant-expr]
[builtins fixtures/isinstancelist.pyi]
[case testRedundantExprTruthiness]
# flags: --enable-error-code redundant-expr
from typing import List
def maybe() -> bool: ...
class Foo:
def __init__(self, x: List[int]) -> None:
self.x = x or []
def method(self) -> int:
if not self.x or maybe():
return 1
return 2
[builtins fixtures/list.pyi]
[case testNamedTupleNameMismatch]
from typing import NamedTuple
Foo = NamedTuple("Bar", []) # E: First argument to namedtuple() should be "Foo", not "Bar" [name-match]
[builtins fixtures/tuple.pyi]
[case testTypedDictNameMismatch]
from typing_extensions import TypedDict
Foo = TypedDict("Bar", {}) # E: First argument "Bar" to TypedDict() does not match variable name "Foo" [name-match]
[builtins fixtures/dict.pyi]
[case testTruthyBool]
# flags: --enable-error-code truthy-bool --no-local-partial-types
from typing import List, Union, Any
class Foo:
pass
class Bar:
pass
foo = Foo()
if foo: # E: "__main__.foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
pass
not foo # E: "__main__.foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
zero = 0
if zero:
pass
not zero
false = False
if false:
pass
not false
null = None
if null:
pass
not null
s = ''
if s:
pass
not s
good_union: Union[str, int] = 5
if good_union:
pass
if not good_union:
pass
not good_union
bad_union: Union[Foo, Bar] = Foo()
if bad_union: # E: "__main__.bad_union" has type "Union[Foo, Bar]" of which no members implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
pass
if not bad_union: # E: "__main__.bad_union" has type "Union[Foo, Bar]" of which no members implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
pass
not bad_union # E: "__main__.bad_union" has type "Union[Foo, Bar]" of which no members implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
# 'object' is special and is treated as potentially falsy
obj: object = Foo()
if obj:
pass
if not obj:
pass
not obj
lst: List[int] = []
if lst:
pass
not lst
a: Any
if a:
pass
not a
any_or_object: Union[object, Any]
if any_or_object:
pass
not any_or_object
if (my_foo := Foo()): # E: "__main__.my_foo" has type "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
pass
if my_a := (a or Foo()): # E: "__main__.Foo" returns "Foo" which does not implement __bool__ or __len__ so it could always be true in boolean context [truthy-bool]
pass
[builtins fixtures/list.pyi]
[case testTruthyFunctions]
def f():
pass
if f: # E: Function "f" could always be true in boolean context [truthy-function]
pass
if not f: # E: Function "f" could always be true in boolean context [truthy-function]
pass
conditional_result = 'foo' if f else 'bar' # E: Function "f" could always be true in boolean context [truthy-function]
not f # E: Function "f" could always be true in boolean context [truthy-function]
[case testTruthyIterable]
# flags: --enable-error-code truthy-iterable
from typing import Iterable
def func(var: Iterable[str]) -> None:
if var: # E: "var" has type "Iterable[str]" which can always be true in boolean context. Consider using "Collection[str]" instead. [truthy-iterable]
...
not var # E: "var" has type "Iterable[str]" which can always be true in boolean context. Consider using "Collection[str]" instead. [truthy-iterable]
[case testNoOverloadImplementation]
from typing import overload
@overload # E: An overloaded function outside a stub file must have an implementation [no-overload-impl]
def f(arg: int) -> int:
...
@overload
def f(arg: str) -> str:
...
[case testSliceInDict39]
# flags: --python-version 3.9 --show-column-numbers
from typing import Dict
b: Dict[int, x:y]
c: Dict[x:y]
[builtins fixtures/dict.pyi]
[out]
main:3:14: error: Invalid type comment or annotation [valid-type]
main:3:14: note: did you mean to use ',' instead of ':' ?
main:4:4: error: "dict" expects 2 type arguments, but 1 given [type-arg]
main:4:9: error: Invalid type comment or annotation [valid-type]
main:4:9: note: did you mean to use ',' instead of ':' ?
[case testSliceInDict38]
# flags: --python-version 3.8 --show-column-numbers
from typing import Dict
b: Dict[int, x:y]
c: Dict[x:y]
[builtins fixtures/dict.pyi]
[out]
main:3:14: error: Invalid type comment or annotation [valid-type]
main:3:14: note: did you mean to use ',' instead of ':' ?
main:4:4: error: "dict" expects 2 type arguments, but 1 given [type-arg]
main:4:9: error: Invalid type comment or annotation [valid-type]
main:4:9: note: did you mean to use ',' instead of ':' ?
[case testSliceInCustomTensorType]
# syntactically mimics torchtyping.TensorType
class TensorType: ...
t: TensorType["batch":..., float] # type: ignore
reveal_type(t) # N: Revealed type is "__main__.TensorType"
[builtins fixtures/tuple.pyi]
[case testNoteAboutChangedTypedDictErrorCode]
from typing_extensions import TypedDict
class D(TypedDict):
x: int
def f(d: D, s: str) -> None: