-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
Copy pathpythoneval.test
2192 lines (1875 loc) · 59.4 KB
/
pythoneval.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
-- Test cases for type checking mypy programs using full stubs and running
-- using CPython.
--
-- These are mostly regression tests -- no attempt is made to make these
-- complete.
[case testHello]
import typing
print('hello, world')
[out]
hello, world
[case testMiscStdlibFeatures]
# Various legacy tests merged together to speed up test runtimes.
def f(x: object) -> None: pass
# testReversed
from typing import Reversible
class R(Reversible):
def __iter__(self): return iter('oof')
def __reversed__(self): return iter('foo')
f(list(reversed(range(5))))
f(list(reversed([1,2,3])))
f(list(reversed('abc')))
f(list(reversed(R())))
# testIntAndFloatConversion
from typing import SupportsInt, SupportsFloat
class A(SupportsInt):
def __int__(self): return 5
class B(SupportsFloat):
def __float__(self): return 1.2
f(int(1))
f(int(6.2))
f(int('3'))
f(int(b'4'))
f(int(A()))
f(float(-9))
f(float(B()))
# testAbs
from typing import SupportsAbs
class Ab(SupportsAbs[float]):
def __abs__(self) -> float: return 5.5
f(abs(-1))
f(abs(-1.2))
f(abs(Ab()))
# testRound
from typing import SupportsRound
class Ro(SupportsRound):
def __round__(self, ndigits=0): return 'x%d' % ndigits
f(round(1.6))
f(round(Ro()))
f(round(Ro(), 2))
# testCallMethodViaTypeObject
list.__add__([1, 2], [3, 4])
# testInheritedClassAttribute
import typing
class AA:
x = 1
def f(self: typing.Optional["AA"]) -> None: pass
class BB(AA):
pass
BB.f(None)
f(BB.x)
# testSpecialAttributes
class Doc:
"""A docstring!"""
f(Doc().__doc__)
f(Doc().__class__)
# testFunctionAttributes
f(ord.__class__)
f(type(ord.__doc__ or '' + ''))
f(ord.__name__)
f(ord.__module__)
# testModuleAttributes
import math
f(type(__spec__))
f(math.__name__)
f(math.__spec__.name)
f(type(math.__dict__))
f(type(math.__doc__ or ''))
f(type(math.__spec__).__name__)
f(math.__class__)
[case testAbs2]
n: int
f: float
n = abs(1)
abs(1) + 'x' # Error
f = abs(1.1)
abs(1.1) + 'x' # Error
[out]
_program.py:4: error: Unsupported operand types for + ("int" and "str")
_program.py:6: error: Unsupported operand types for + ("float" and "str")
[case testTypeAttributes]
import typing
print(str.__class__)
print(type(str.__doc__))
print(str.__name__)
print(str.__module__)
print(str.__dict__ is not None)
[out]
<class 'type'>
<class 'str'>
str
builtins
True
[case testBoolCompatibilityWithInt]
import typing
x = 0
x = True
print(bool('x'))
print(bool(''))
[out]
True
False
[case testCannotExtendBoolUnlessIgnored]
class A(bool): pass
class B(bool): pass # type: ignore
[out]
_program.py:1: error: Cannot inherit from final class "bool"
[case testCallBuiltinTypeObjectsWithoutArguments]
import typing
print(int())
print(repr(str()))
print(repr(bytes()))
print(float())
print(bool())
[out]
0
''
b''
0.0
False
[case testIntegerDivision]
import typing
x = 1 / 2
x = 1.5
[out]
[case testIntMethods]
import typing
print(int.from_bytes(b'ab', 'big'))
n = 0
print(n.from_bytes(b'ac', 'big'))
print(n.from_bytes([2, 3], 'big'))
print(n.to_bytes(2, 'big'))
[out]
24930
24931
515
b'\x00\x00'
[case testFloatMethods]
import typing
print(1.5.as_integer_ratio())
print(1.5.hex())
print(2.0.is_integer())
print(float.fromhex('0x1.8'))
[out]
(3, 2)
0x1.8000000000000p+0
True
1.5
[case testDictFromkeys]
import typing
d = dict.fromkeys('foo')
d['x'] = 2
d2 = dict.fromkeys([1, 2], b'')
d2[2] = b'foo'
[out]
[case testIsinstanceWithTuple]
from typing import cast, Any
x = cast(Any, (1, 'x'))
if isinstance(x, tuple):
print(x[0], x[1])
[out]
1 x
[case testAnyStr]
from typing import AnyStr
def f(x: AnyStr) -> AnyStr:
if isinstance(x, str):
return 'foo'
else:
return b'zar'
print(f(''))
print(f(b''))
[out]
foo
b'zar'
[case testNameNotImportedFromTyping]
import typing
cast(int, 2)
[out]
_program.py:2: error: Name "cast" is not defined
_program.py:2: note: Did you forget to import it from "typing"? (Suggestion: "from typing import cast")
[case testBinaryIOType]
from typing import BinaryIO
def f(f: BinaryIO) -> None:
f.write(b'foo')
f.write(bytearray(b'foo'))
[out]
[case testIOTypes]
from typing import IO
import sys
def txt(f: IO[str]) -> None:
f.write('foo')
f.write(b'foo')
def bin(f: IO[bytes]) -> None:
f.write(b'foo')
f.write(bytearray(b'foo'))
txt(sys.stdout)
bin(sys.stdout)
[out]
_program.py:5: error: Argument 1 to "write" of "IO" has incompatible type "bytes"; expected "str"
_program.py:10: error: Argument 1 to "bin" has incompatible type "Union[TextIO, Any]"; expected "IO[bytes]"
[case testBuiltinOpen]
f = open('x')
f.write('x')
f.write(b'x')
f.foobar()
[out]
_program.py:3: error: Argument 1 to "write" of "_TextIOBase" has incompatible type "bytes"; expected "str"
_program.py:4: error: "TextIOWrapper[_WrappedBuffer]" has no attribute "foobar"
[case testOpenReturnTypeInference]
reveal_type(open('x'))
reveal_type(open('x', 'r'))
reveal_type(open('x', 'rb'))
mode = 'rb'
reveal_type(open('x', mode))
[out]
_program.py:1: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]"
_program.py:2: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]"
_program.py:3: note: Revealed type is "_io.BufferedReader"
_program.py:5: note: Revealed type is "typing.IO[Any]"
[case testOpenReturnTypeInferenceSpecialCases]
reveal_type(open(mode='rb', file='x'))
reveal_type(open(file='x', mode='rb'))
mode = 'rb'
reveal_type(open(mode=mode, file='r'))
[out]
_testOpenReturnTypeInferenceSpecialCases.py:1: note: Revealed type is "_io.BufferedReader"
_testOpenReturnTypeInferenceSpecialCases.py:2: note: Revealed type is "_io.BufferedReader"
_testOpenReturnTypeInferenceSpecialCases.py:4: note: Revealed type is "typing.IO[Any]"
[case testPathOpenReturnTypeInference]
from pathlib import Path
p = Path("x")
reveal_type(p.open())
reveal_type(p.open('r'))
reveal_type(p.open('rb'))
mode = 'rb'
reveal_type(p.open(mode))
[out]
_program.py:3: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]"
_program.py:4: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]"
_program.py:5: note: Revealed type is "_io.BufferedReader"
_program.py:7: note: Revealed type is "typing.IO[Any]"
[case testPathOpenReturnTypeInferenceSpecialCases]
from pathlib import Path
p = Path("x")
reveal_type(p.open(mode='r', errors='replace'))
reveal_type(p.open(errors='replace', mode='r'))
mode = 'r'
reveal_type(p.open(mode=mode, errors='replace'))
[out]
_program.py:3: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]"
_program.py:4: note: Revealed type is "_io.TextIOWrapper[_io._WrappedBuffer]"
_program.py:6: note: Revealed type is "typing.IO[Any]"
[case testGenericPatterns]
from typing import Pattern
import re
p: Pattern[str]
p = re.compile('foo*')
b: Pattern[bytes]
b = re.compile(b'foo*')
m = p.match('fooo')
assert m
print(m.group(0))
[out]
fooo
[case testGenericMatch]
from typing import Match, Optional
import re
def f(m: Optional[Match[bytes]]) -> None:
assert m
print(m.group(0))
f(re.match(b'x*', b'xxy'))
[out]
b'xx'
[case testIntFloatDucktyping]
x: float
x = 2.2
x = 2
def f(x: float) -> None: pass
f(1.1)
f(1)
[out]
[case testsFloatOperations]
import typing
print(1.5 + 1.5)
print(1.5 + 1)
[out]
3.0
2.5
[case testMathFunctionWithIntArgument]
import typing
import math
math.sin(2)
math.sin(2.2)
[case testAbsReturnType]
f: float
n: int
n = abs(2)
f = abs(2.2)
abs(2.2) + 'x'
[out]
_program.py:5: error: Unsupported operand types for + ("float" and "str")
[case testROperatorMethods]
b: bytes
s: str
if int():
s = b'foo' * 5 # Error
if int():
b = 5 * b'foo'
if int():
b = b'foo' * 5
if int():
s = 5 * 'foo'
if int():
s = 'foo' * 5
[out]
_program.py:4: error: Incompatible types in assignment (expression has type "bytes", variable has type "str")
[case testROperatorMethods2]
import typing
print(2 / 0.5)
print(' ', 2 * [3, 4])
[out]
4.0
[3, 4, 3, 4]
[case testNotImplemented]
import typing
class A:
def __add__(self, x: int) -> int:
if isinstance(x, int):
return x + 1
return NotImplemented
class B:
def __radd__(self, x: A) -> str:
return 'x'
print(A() + 1)
print(A() + B())
[out]
2
x
[case testMappingMethods]
# Regression test
from typing import Mapping
x = {'x': 'y'} # type: Mapping[str, str]
print('x' in x)
print('y' in x)
[out]
True
False
[case testOverlappingOperatorMethods]
class X: pass
class A:
def __add__(self, x: object) -> int:
if isinstance(x, X):
return 1
return NotImplemented
class B:
def __radd__(self, x: A) -> str: return 'x'
class C(X, B): pass
b: B
b = C()
print(A() + b)
[out]
_program.py:8: error: Signatures of "__radd__" of "B" and "__add__" of "A" are unsafely overlapping
[case testBytesAndBytearrayComparisons]
import typing
print(b'ab' < bytearray(b'b'))
print(bytearray(b'ab') < b'a')
[out]
True
False
[case testBytesAndBytearrayComparisons2]
import typing
'' < b''
b'' < ''
'' < bytearray()
bytearray() < ''
[out]
_program.py:2: error: Unsupported operand types for < ("str" and "bytes")
_program.py:3: error: Unsupported operand types for < ("bytes" and "str")
_program.py:4: error: Unsupported operand types for < ("str" and "bytearray")
_program.py:5: error: Unsupported operand types for < ("bytearray" and "str")
[case testInplaceOperatorMethod]
import typing
a = [1]
print('', a.__iadd__([2]))
print('', a)
[out]
[1, 2]
[1, 2]
[case testListInplaceAdd]
import typing
a = [1]
a += iter([2, 3])
print(tuple(a))
[out]
(1, 2, 3)
[case testInferHeterogeneousListOfIterables]
from typing import Sequence
s = ['x', 'y'] # type: Sequence[str]
a = [['x', 'x'], 'fo', s, iter('foo'), {'aa'}]
for i, x in enumerate(a):
print(i, next(iter(x)))
[out]
0 x
1 f
2 x
3 f
4 aa
[case testTextIOProperties]
import typing
import sys
print(type(sys.stdin.encoding))
print(type(sys.stdin.errors))
sys.stdin.line_buffering
sys.stdin.buffer
sys.stdin.newlines
[out]
<class 'str'>
<class 'str'>
[case testIOProperties]
import typing
import sys
print(sys.stdin.name)
print(sys.stdin.buffer.mode)
[out]
<stdin>
rb
[case testFromFuturePrintFunction]
from __future__ import print_function
print('a', 'b')
[out]
a b
[case testListMethods]
import typing
import sys
l = [0, 1, 2, 3, 4]
if sys.version >= '3.3':
l.clear()
else:
l = []
l.append(0)
print('>', l)
if sys.version >= '3.3':
m = l.copy()
else:
m = l[:]
m.extend([1, 2, 3, 4])
print('>', m)
print(l.index(0))
print(l.index(0, 0))
print(l.index(0, 0, 1))
try:
print(l.index(1))
print('expected ValueError')
except ValueError:
pass
l.insert(0, 1)
print('>', l)
print(l.pop(0))
print(l.pop())
m.remove(0)
try:
m.remove(0)
print('expected ValueError')
except ValueError:
pass
m.reverse()
m.sort()
m.sort(key=lambda x: -x)
m.sort(reverse=False)
m.sort(key=lambda x: -x, reverse=True)
print('>', m)
[out]
> [0]
> [0, 1, 2, 3, 4]
0
0
0
> [1, 0]
1
0
> [1, 2, 3, 4]
[case testListOperators]
import typing
l = [0, 1]
print('+', l + [2])
print('*', l * 2)
print('*', 2 * l)
print('in', 1 in l)
print('==', l == [1, 2])
print('!=', l != [1, 2])
print('>', l > [1, 2, 3])
print('>=', l >= [1, 2, 3])
print('<', l < [1, 2, 3])
print('<=', l <= [1, 2, 3])
print('>[0]', l[0])
l += [2]
print('+=', l)
l *= 2
print('*=', l)
print('iter', list(iter(l)))
print('len', len(l))
print('repr', repr(l))
l[:3] = []
print('setslice', l)
print('reversed', list(reversed(l)))
[out]
+ [0, 1, 2]
* [0, 1, 0, 1]
* [0, 1, 0, 1]
in True
== False
!= True
> False
>= False
< True
<= True
>[0] 0
+= [0, 1, 2]
*= [0, 1, 2, 0, 1, 2]
iter [0, 1, 2, 0, 1, 2]
len 6
repr [0, 1, 2, 0, 1, 2]
setslice [0, 1, 2]
reversed [2, 1, 0]
[case testTupleAsSubtypeOfSequence]
from typing import TypeVar, Sequence
T = TypeVar('T')
def f(a: Sequence[T]) -> None: print(a)
f(tuple())
[out]
()
[case testMapWithLambdaSpecialCase]
from typing import List, Iterator
a = [[1], [3]]
b = map(lambda y: y[0], a)
print('>', list(b))
[out]
> [1, 3]
[case testInternalBuiltinDefinition]
import typing
def f(x: _T) -> None: pass
s: FrozenSet
[out]
_program.py:2: error: Name "_T" is not defined
_program.py:3: error: Name "FrozenSet" is not defined
[case testVarArgsFunctionSubtyping]
import typing
def f(*args: str) -> str: return args[0]
map(f, ['x'])
map(f, [1])
[out]
_program.py:4: error: Argument 1 to "map" has incompatible type "Callable[[VarArg(str)], str]"; expected "Callable[[int], str]"
[case testMapStr]
import typing
x = range(3)
a = list(map(str, x))
a + 1
[out]
_testMapStr.py:4: error: No overload variant of "__add__" of "list" matches argument type "int"
_testMapStr.py:4: note: Possible overload variants:
_testMapStr.py:4: note: def __add__(self, List[str], /) -> List[str]
_testMapStr.py:4: note: def [_S] __add__(self, List[_S], /) -> List[Union[_S, str]]
[case testRelativeImport]
import typing
from m import x
print(x)
[file m/__init__.py]
from .n import x
[file m/n.py]
x = 1
[out]
1
[case testRelativeImport2]
import typing
from m.n import x
print(x)
[file m/__init__.py]
[file m/n.py]
from .nn import x
[file m/nn.py]
x = 2
[out]
2
[case testPyiTakesPrecedenceOverPy]
import m
m.f(1)
[file m.py]
def f(x):
print(x)
[file m.pyi]
import typing
def f(x: str) -> None: pass
[out]
_program.py:2: error: Argument 1 to "f" has incompatible type "int"; expected "str"
[case testComplexArithmetic]
import typing
print(5 + 8j)
print(3j * 2.0)
print(4J / 2.0)
[out]
(5+8j)
6j
2j
[case testComplexArithmetic2]
x = 5 + 8j
if int():
x = '' # E
y = 3j * 2.0
if int():
y = '' # E
[out]
_program.py:3: error: Incompatible types in assignment (expression has type "str", variable has type "complex")
_program.py:6: error: Incompatible types in assignment (expression has type "str", variable has type "complex")
[case testSuperNew]
from typing import Dict, Any
class MyType(type):
def __new__(cls, name: str, bases: tuple, namespace: Dict[str, Any]) -> Any:
return super().__new__(cls, name + 'x', bases, namespace)
class A(metaclass=MyType): pass
print(type(A()).__name__)
[out]
Ax
[case testSubclassBothGenericAndNonGenericABC]
from typing import Generic, TypeVar
from abc import ABCMeta
T = TypeVar('T')
class A(metaclass=ABCMeta): pass
class B(Generic[T]): pass
class C(A, B): pass
class D(B, A): pass
class E(A, B[T], Generic[T]): pass
class F(B[T], A, Generic[T]): pass
def f(e: E[int], f: F[int]) -> None: pass
[out]
[case testTypeVariableTypeComparability]
from typing import TypeVar
T = TypeVar('T')
def eq(x: T, y: T, z: T) -> T:
if x == y:
return y
else:
return z
print(eq(1, 2, 3))
print(eq('x', 'x', 'z'))
[out]
3
x
[case testIntDecimalCompatibility]
import typing
from decimal import Decimal
print(Decimal(1) + 2)
print(Decimal(1) - 2)
print(1 + Decimal('2.34'))
print(1 - Decimal('2.34'))
print(2 * Decimal('2.34'))
[out]
3
-1
3.34
-1.34
4.68
[case testInstantiateBuiltinTypes]
from typing import Dict, Set, List
d = dict() # type: Dict[int, str]
s = set() # type: Set[int]
l = list() # type: List[int]
str()
bytes()
bytearray()
int()
float()
complex()
slice(1)
bool()
[case testVariableLengthTupleError]
from typing import Tuple
def p(t: Tuple[str, ...]) -> None:
n = 5
print(t[n])
for s in t:
s()
''.startswith(('x', 'y'))
''.startswith(('x', b'y'))
[out]
_program.py:6: error: "str" not callable
_program.py:8: error: Argument 1 to "startswith" of "str" has incompatible type "Tuple[str, bytes]"; expected "Union[str, Tuple[str, ...]]"
[case testMultiplyTupleByInteger]
n = 4
t = ('',) * n
t + 1
[out]
_program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int"
_program.py:3: note: Possible overload variants:
_program.py:3: note: def __add__(self, Tuple[str, ...], /) -> Tuple[str, ...]
_program.py:3: note: def [_T] __add__(self, Tuple[_T, ...], /) -> Tuple[Union[str, _T], ...]
[case testMultiplyTupleByIntegerReverse]
n = 4
t = n * ('',)
t + 1
[out]
_program.py:3: error: No overload variant of "__add__" of "tuple" matches argument type "int"
_program.py:3: note: Possible overload variants:
_program.py:3: note: def __add__(self, Tuple[str, ...], /) -> Tuple[str, ...]
_program.py:3: note: def [_T] __add__(self, Tuple[_T, ...], /) -> Tuple[Union[str, _T], ...]
[case testDictWithKeywordArgs]
from typing import Dict, Any, List
d1 = dict(a=1, b=2) # type: Dict[str, int]
d2 = dict(a=1, b='') # type: Dict[str, int] # E
d3 = dict(a=1, b=1)
d3.xyz # E
d4 = dict(a=1, b='') # type: Dict[str, Any]
result = dict(x=[], y=[]) # type: Dict[str, List[str]]
[out]
_program.py:3: error: Dict entry 1 has incompatible type "str": "str"; expected "str": "int"
_program.py:5: error: "Dict[str, int]" has no attribute "xyz"
[case testDefaultDict]
# flags: --new-type-inference
import typing as t
from collections import defaultdict
T = t.TypeVar('T')
d1 = defaultdict(list) # type: t.DefaultDict[int, str]
d2 = defaultdict() # type: t.DefaultDict[int, str]
d2[0] = '0'
d2['0'] = 0
def tst(dct: t.DefaultDict[int, T]) -> T:
return dct[0]
collections = ['coins', 'stamps', 'comics'] # type: t.List[str]
d3 = defaultdict(str) # type: t.DefaultDict[int, str]
collections[2]
tst(defaultdict(list, {0: []}))
tst(defaultdict(list, {'0': []}))
class MyDDict(t.DefaultDict[int,T], t.Generic[T]):
pass
MyDDict(dict)['0']
MyDDict(dict)[0]
[out]
_program.py:7: error: Argument 1 to "defaultdict" has incompatible type "Type[List[_T]]"; expected "Optional[Callable[[], str]]"
_program.py:10: error: Invalid index type "str" for "defaultdict[int, str]"; expected type "int"
_program.py:10: error: Incompatible types in assignment (expression has type "int", target has type "str")
_program.py:20: error: Argument 1 to "tst" has incompatible type "defaultdict[str, List[Never]]"; expected "defaultdict[int, List[Never]]"
_program.py:24: error: Invalid index type "str" for "MyDDict[Dict[Never, Never]]"; expected type "int"
[case testCollectionsAliases]
import typing as t
import collections as c
o1 = c.Counter() # type: t.Counter[int]
reveal_type(o1)
o1['string']
o2 = c.ChainMap() # type: t.ChainMap[int, str]
reveal_type(o2)
o3 = c.deque() # type: t.Deque[int]
reveal_type(o3)
o4 = t.Counter[int]()
reveal_type(o4)
o5 = t.ChainMap[int, str]()
reveal_type(o5)
o6 = t.Deque[int]()
reveal_type(o6)
[out]
_testCollectionsAliases.py:5: note: Revealed type is "collections.Counter[builtins.int]"
_testCollectionsAliases.py:6: error: Invalid index type "str" for "Counter[int]"; expected type "int"
_testCollectionsAliases.py:9: note: Revealed type is "collections.ChainMap[builtins.int, builtins.str]"
_testCollectionsAliases.py:12: note: Revealed type is "collections.deque[builtins.int]"
_testCollectionsAliases.py:15: note: Revealed type is "collections.Counter[builtins.int]"
_testCollectionsAliases.py:18: note: Revealed type is "collections.ChainMap[builtins.int, builtins.str]"
_testCollectionsAliases.py:21: note: Revealed type is "collections.deque[builtins.int]"
[case testChainMapUnimported]
ChainMap[int, str]()
[out]
_testChainMapUnimported.py:1: error: Name "ChainMap" is not defined
[case testDequeWrongCase]
import collections
import typing
collections.Deque()
typing.deque()
[out]
_testDequeWrongCase.py:4: error: Module has no attribute "Deque"; maybe "deque"?
_testDequeWrongCase.py:5: error: Module has no attribute "deque"; maybe "Deque"?
[case testDictUpdateInference]
from typing import Dict, Optional
d = {} # type: Dict[str, Optional[int]]
d.update({str(i): None for i in range(4)})
[case testSuperAndSetattr]
class A:
def __init__(self) -> None:
super().__setattr__('a', 1)
super().__setattr__(1, 'a')
[out]
_program.py:4: error: Argument 1 to "__setattr__" of "object" has incompatible type "int"; expected "str"
[case testMetaclassAndSuper]
from typing import Any
class A(type):
def __new__(cls, name, bases, namespace) -> Any:
return super().__new__(cls, '', (object,), {'x': 7})
class B(metaclass=A):
pass
print(getattr(B(), 'x'))
[out]
7
[case testSortedNoError]
from typing import Iterable, Callable, TypeVar, List, Dict, Optional
T = TypeVar('T')
def sorted(x: Iterable[T], *, key: Optional[Callable[[T], object]] = None) -> None: ...
a = [] # type: List[Dict[str, str]]
sorted(a, key=lambda y: y[''])
[case testAbstractProperty]
from abc import abstractproperty, ABCMeta # type: ignore[deprecated]
class A(metaclass=ABCMeta):
@abstractproperty
def x(self) -> int: pass
class B(A):
@property
def x(self) -> int:
return 3
b = B()
print(b.x + 1)
[out]
4
[case testInferenceWithLambda]
from typing import TypeVar, Iterable, Iterator, List
import itertools
_T = TypeVar('_T')
def f(iterable): # type: (Iterable[_T]) -> Iterator[List[_T]]
grouped = itertools.groupby(enumerate(iterable), lambda pair: pair[0] // 2)
return ([elem for _, elem in group] for _, group in grouped)
[case testReModuleBytes]
# Regression tests for various overloads in the re module -- bytes version
import re
bre = b'a+'
bpat = re.compile(bre)
bpat = re.compile(bpat)
s1 = re.search(bre, b'')
assert s1
s1.groups()
re.search(bre, u'') # Error
s2 = re.search(bpat, b'')
assert s2
s2.groups()
re.search(bpat, u'') # Error
# match(), split(), findall(), finditer() are much the same, so skip those.
# sub(), subn() have more overloads and we are checking these:
re.sub(bre, b'', b'') + b''
re.sub(bpat, b'', b'') + b''
re.sub(bre, lambda m: b'', b'') + b''
re.sub(bpat, lambda m: b'', b'') + b''
re.subn(bre, b'', b'')[0] + b''
re.subn(bpat, b'', b'')[0] + b''
re.subn(bre, lambda m: b'', b'')[0] + b''
re.subn(bpat, lambda m: b'', b'')[0] + b''
[out]
_testReModuleBytes.py:9: error: No overload variant of "search" matches argument types "bytes", "str"
_testReModuleBytes.py:9: note: Possible overload variants:
_testReModuleBytes.py:9: note: def search(pattern: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]]
_testReModuleBytes.py:9: note: def search(pattern: Union[bytes, Pattern[bytes]], string: Buffer, flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]]
_testReModuleBytes.py:13: error: Argument 1 to "search" has incompatible type "Pattern[bytes]"; expected "Union[str, Pattern[str]]"
[case testReModuleString]
# Regression tests for various overloads in the re module -- string version
import re
sre = 'a+'
spat = re.compile(sre)
spat = re.compile(spat)
s1 = re.search(sre, '')
assert s1
s1.groups()
re.search(sre, b'') # Error
s2 = re.search(spat, '')
assert s2
s2.groups()
re.search(spat, b'') # Error
# match(), split(), findall(), finditer() are much the same, so skip those.
# sus(), susn() have more overloads and we are checking these:
re.sub(sre, '', '') + ''
re.sub(spat, '', '') + ''
re.sub(sre, lambda m: '', '') + ''
re.sub(spat, lambda m: '', '') + ''
re.subn(sre, '', '')[0] + ''
re.subn(spat, '', '')[0] + ''
re.subn(sre, lambda m: '', '')[0] + ''
re.subn(spat, lambda m: '', '')[0] + ''
[out]
_testReModuleString.py:9: error: No overload variant of "search" matches argument types "str", "bytes"
_testReModuleString.py:9: note: Possible overload variants:
_testReModuleString.py:9: note: def search(pattern: Union[str, Pattern[str]], string: str, flags: Union[int, RegexFlag] = ...) -> Optional[Match[str]]
_testReModuleString.py:9: note: def search(pattern: Union[bytes, Pattern[bytes]], string: Buffer, flags: Union[int, RegexFlag] = ...) -> Optional[Match[bytes]]
_testReModuleString.py:13: error: Argument 1 to "search" has incompatible type "Pattern[str]"; expected "Union[bytes, Pattern[bytes]]"