-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
check-typeddict.test
1664 lines (1379 loc) · 56.7 KB
/
check-typeddict.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
-- Create Instance
[case testCanCreateTypedDictInstanceWithKeywordArguments]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(x=42, y=1337)
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})'
# Use values() to check fallback value type.
reveal_type(p.values()) # N: Revealed type is 'typing.Iterable[builtins.object*]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testCanCreateTypedDictInstanceWithDictCall]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(dict(x=42, y=1337))
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})'
# Use values() to check fallback value type.
reveal_type(p.values()) # N: Revealed type is 'typing.Iterable[builtins.object*]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testCanCreateTypedDictInstanceWithDictLiteral]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point({'x': 42, 'y': 1337})
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})'
# Use values() to check fallback value type.
reveal_type(p.values()) # N: Revealed type is 'typing.Iterable[builtins.object*]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testCanCreateTypedDictInstanceWithNoArguments]
from typing import TypeVar, Union
from mypy_extensions import TypedDict
EmptyDict = TypedDict('EmptyDict', {})
p = EmptyDict()
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.EmptyDict', {})'
reveal_type(p.values()) # N: Revealed type is 'typing.Iterable[builtins.object*]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
-- Create Instance (Errors)
[case testCannotCreateTypedDictInstanceWithUnknownArgumentPattern]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(42, 1337) # E: Expected keyword arguments, {...}, or dict(...) in TypedDict constructor
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictInstanceNonLiteralItemName]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
x = 'x'
p = Point({x: 42, 'y': 1337}) # E: Expected TypedDict key to be string literal
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictInstanceWithExtraItems]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(x=42, y=1337, z=666) # E: Extra key 'z' for TypedDict "Point"
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictInstanceWithMissingItems]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(x=42) # E: Key 'y' missing for TypedDict "Point"
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictInstanceWithIncompatibleItemType]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(x='meaning_of_life', y=1337) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
[builtins fixtures/dict.pyi]
-- Define TypedDict (Class syntax)
[case testCanCreateTypedDictWithClass]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point(TypedDict):
x: int
y: int
p = Point(x=42, y=1337)
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCanCreateTypedDictWithSubclass]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point1D(TypedDict):
x: int
class Point2D(Point1D):
y: int
r: Point1D
p: Point2D
reveal_type(r) # N: Revealed type is 'TypedDict('__main__.Point1D', {'x': builtins.int})'
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCanCreateTypedDictWithSubclass2]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point1D(TypedDict):
x: int
class Point2D(TypedDict, Point1D): # We also allow to include TypedDict in bases, it is simply ignored at runtime
y: int
p: Point2D
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCanCreateTypedDictClassEmpty]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class EmptyDict(TypedDict):
pass
p = EmptyDict()
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.EmptyDict', {})'
[builtins fixtures/dict.pyi]
[case testCanCreateTypedDictWithClassOldVersion]
# flags: --python-version 3.5
# Test that we can use class-syntax to merge TypedDicts even in
# versions without type annotations
from mypy_extensions import TypedDict
MovieBase1 = TypedDict(
'MovieBase1', {'name': str, 'year': int})
MovieBase2 = TypedDict(
'MovieBase2', {'based_on': str}, total=False)
class Movie(MovieBase1, MovieBase2):
pass
def foo(x):
# type: (Movie) -> None
pass
foo({}) # E: Keys ('name', 'year') missing for TypedDict "Movie"
foo({'name': 'lol', 'year': 2009, 'based_on': 0}) # E: Incompatible types (expression has type "int", TypedDict item "based_on" has type "str")
[builtins fixtures/dict.pyi]
-- Define TypedDict (Class syntax errors)
[case testCannotCreateTypedDictWithClassOtherBases]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class A: pass
class Point1D(TypedDict, A): # E: All bases of a new TypedDict must be TypedDict types
x: int
class Point2D(Point1D, A): # E: All bases of a new TypedDict must be TypedDict types
y: int
p: Point2D
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point2D', {'x': builtins.int, 'y': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictWithClassWithOtherStuff]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point(TypedDict):
x: int
y: int = 1 # E: Right hand side values are not supported in TypedDict
def f(): pass # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
z = int # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
p = Point(x=42, y=1337, z='whatever')
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int, 'z': Any})'
[builtins fixtures/dict.pyi]
[case testCanCreateTypedDictTypeWithUnderscoreItemName]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int, '_fallback': object})
[builtins fixtures/dict.pyi]
[case testCanCreateTypedDictWithClassUnderscores]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point(TypedDict):
x: int
_y: int
p: Point
reveal_type(p) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, '_y': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictWithClassOverwriting]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Bad(TypedDict):
x: int
x: str # E: Duplicate TypedDict field "x"
b: Bad
reveal_type(b) # N: Revealed type is 'TypedDict('__main__.Bad', {'x': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictWithClassOverwriting2]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point1(TypedDict):
x: int
class Point2(TypedDict):
x: float
class Bad(Point1, Point2): # E: Cannot overwrite TypedDict field "x" while merging
pass
b: Bad
reveal_type(b) # N: Revealed type is 'TypedDict('__main__.Bad', {'x': builtins.int})'
[builtins fixtures/dict.pyi]
[case testCannotCreateTypedDictWithClassOverwriting2]
# flags: --python-version 3.6
from mypy_extensions import TypedDict
class Point1(TypedDict):
x: int
class Point2(Point1):
x: float # E: Cannot overwrite TypedDict field "x" while extending
p2: Point2
reveal_type(p2) # N: Revealed type is 'TypedDict('__main__.Point2', {'x': builtins.int})'
[builtins fixtures/dict.pyi]
-- Subtyping
[case testCanConvertTypedDictToItself]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
def identity(p: Point) -> Point:
return p
[builtins fixtures/dict.pyi]
[case testCanConvertTypedDictToEquivalentTypedDict]
from mypy_extensions import TypedDict
PointA = TypedDict('PointA', {'x': int, 'y': int})
PointB = TypedDict('PointB', {'x': int, 'y': int})
def identity(p: PointA) -> PointB:
return p
[builtins fixtures/dict.pyi]
[case testCannotConvertTypedDictToSimilarTypedDictWithNarrowerItemTypes]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
ObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object})
def convert(op: ObjectPoint) -> Point:
return op # E: Incompatible return value type (got "ObjectPoint", expected "Point")
[builtins fixtures/dict.pyi]
[case testCannotConvertTypedDictToSimilarTypedDictWithWiderItemTypes]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
ObjectPoint = TypedDict('ObjectPoint', {'x': object, 'y': object})
def convert(p: Point) -> ObjectPoint:
return p # E: Incompatible return value type (got "Point", expected "ObjectPoint")
[builtins fixtures/dict.pyi]
[case testCannotConvertTypedDictToSimilarTypedDictWithIncompatibleItemTypes]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
Chameleon = TypedDict('Chameleon', {'x': str, 'y': str})
def convert(p: Point) -> Chameleon:
return p # E: Incompatible return value type (got "Point", expected "Chameleon")
[builtins fixtures/dict.pyi]
[case testCanConvertTypedDictToNarrowerTypedDict]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
Point1D = TypedDict('Point1D', {'x': int})
def narrow(p: Point) -> Point1D:
return p
[builtins fixtures/dict.pyi]
[case testCannotConvertTypedDictToWiderTypedDict]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
Point3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int})
def widen(p: Point) -> Point3D:
return p # E: Incompatible return value type (got "Point", expected "Point3D")
[builtins fixtures/dict.pyi]
[case testCanConvertTypedDictToCompatibleMapping]
from mypy_extensions import TypedDict
from typing import Mapping
Point = TypedDict('Point', {'x': int, 'y': int})
def as_mapping(p: Point) -> Mapping[str, object]:
return p
[builtins fixtures/dict.pyi]
[case testCannotConvertTypedDictToIncompatibleMapping]
from mypy_extensions import TypedDict
from typing import Mapping
Point = TypedDict('Point', {'x': int, 'y': int})
def as_mapping(p: Point) -> Mapping[str, int]:
return p # E: Incompatible return value type (got "Point", expected "Mapping[str, int]")
[builtins fixtures/dict.pyi]
[case testTypedDictAcceptsIntForFloatDuckTypes]
from mypy_extensions import TypedDict
from typing import Any, Mapping
Point = TypedDict('Point', {'x': float, 'y': float})
def create_point() -> Point:
return Point(x=1, y=2)
reveal_type(Point(x=1, y=2)) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.float, 'y': builtins.float})'
[builtins fixtures/dict.pyi]
[case testTypedDictDoesNotAcceptsFloatForInt]
from mypy_extensions import TypedDict
from typing import Any, Mapping
Point = TypedDict('Point', {'x': int, 'y': int})
def create_point() -> Point:
return Point(x=1.2, y=2.5)
[out]
main:5: error: Incompatible types (expression has type "float", TypedDict item "x" has type "int")
main:5: error: Incompatible types (expression has type "float", TypedDict item "y" has type "int")
[builtins fixtures/dict.pyi]
[case testTypedDictAcceptsAnyType]
from mypy_extensions import TypedDict
from typing import Any, Mapping
Point = TypedDict('Point', {'x': float, 'y': float})
def create_point(something: Any) -> Point:
return Point({
'x': something.x,
'y': something.y
})
[builtins fixtures/dict.pyi]
[case testTypedDictValueTypeContext]
from mypy_extensions import TypedDict
from typing import List
D = TypedDict('D', {'x': List[int]})
reveal_type(D(x=[])) # N: Revealed type is 'TypedDict('__main__.D', {'x': builtins.list[builtins.int]})'
[builtins fixtures/dict.pyi]
[case testCannotConvertTypedDictToDictOrMutableMapping]
from mypy_extensions import TypedDict
from typing import Dict, MutableMapping
Point = TypedDict('Point', {'x': int, 'y': int})
def as_dict(p: Point) -> Dict[str, int]:
return p # E: Incompatible return value type (got "Point", expected "Dict[str, int]")
def as_mutable_mapping(p: Point) -> MutableMapping[str, object]:
return p # E: Incompatible return value type (got "Point", expected "MutableMapping[str, object]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testCanConvertTypedDictToAny]
from mypy_extensions import TypedDict
from typing import Any
Point = TypedDict('Point', {'x': int, 'y': int})
def unprotect(p: Point) -> Any:
return p
[builtins fixtures/dict.pyi]
[case testAnonymousTypedDictInErrorMessages]
from mypy_extensions import TypedDict
A = TypedDict('A', {'x': int, 'y': str})
B = TypedDict('B', {'x': int, 'z': str, 'a': int})
C = TypedDict('C', {'x': int, 'z': str, 'a': str})
a: A
b: B
c: C
def f(a: A) -> None: pass
l = [a, b] # Join generates an anonymous TypedDict
f(l) # E: Argument 1 to "f" has incompatible type "List[TypedDict({'x': int})]"; expected "A"
ll = [b, c]
f(ll) # E: Argument 1 to "f" has incompatible type "List[TypedDict({'x': int, 'z': str})]"; expected "A"
[builtins fixtures/dict.pyi]
[case testTypedDictWithSimpleProtocol]
from typing_extensions import Protocol
from mypy_extensions import TypedDict
class StrObjectMap(Protocol):
def __getitem__(self, key: str) -> object: ...
class StrIntMap(Protocol):
def __getitem__(self, key: str) -> int: ...
A = TypedDict('A', {'x': int, 'y': int})
B = TypedDict('B', {'x': int, 'y': str})
def fun(arg: StrObjectMap) -> None: ...
def fun2(arg: StrIntMap) -> None: ...
a: A
b: B
fun(a)
fun(b)
fun2(a) # Error
[builtins fixtures/dict.pyi]
[out]
main:18: error: Argument 1 to "fun2" has incompatible type "A"; expected "StrIntMap"
main:18: note: Following member(s) of "A" have conflicts:
main:18: note: Expected:
main:18: note: def __getitem__(self, str) -> int
main:18: note: Got:
main:18: note: def __getitem__(self, str) -> object
[case testTypedDictWithSimpleProtocolInference]
from typing_extensions import Protocol
from mypy_extensions import TypedDict
from typing import TypeVar
T_co = TypeVar('T_co', covariant=True)
T = TypeVar('T')
class StrMap(Protocol[T_co]):
def __getitem__(self, key: str) -> T_co: ...
A = TypedDict('A', {'x': int, 'y': int})
B = TypedDict('B', {'x': int, 'y': str})
def fun(arg: StrMap[T]) -> T:
return arg['whatever']
a: A
b: B
reveal_type(fun(a)) # N: Revealed type is 'builtins.object*'
reveal_type(fun(b)) # N: Revealed type is 'builtins.object*'
[builtins fixtures/dict.pyi]
[out]
-- Join
[case testJoinOfTypedDictHasOnlyCommonKeysAndNewFallback]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
Point3D = TypedDict('Point3D', {'x': int, 'y': int, 'z': int})
p1 = TaggedPoint(type='2d', x=0, y=0)
p2 = Point3D(x=1, y=1, z=1)
joined_points = [p1, p2][0]
reveal_type(p1.values()) # N: Revealed type is 'typing.Iterable[builtins.object*]'
reveal_type(p2.values()) # N: Revealed type is 'typing.Iterable[builtins.object*]'
reveal_type(joined_points) # N: Revealed type is 'TypedDict({'x': builtins.int, 'y': builtins.int})'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testJoinOfTypedDictRemovesNonequivalentKeys]
from mypy_extensions import TypedDict
CellWithInt = TypedDict('CellWithInt', {'value': object, 'meta': int})
CellWithObject = TypedDict('CellWithObject', {'value': object, 'meta': object})
c1 = CellWithInt(value=1, meta=42)
c2 = CellWithObject(value=2, meta='turtle doves')
joined_cells = [c1, c2]
reveal_type(c1) # N: Revealed type is 'TypedDict('__main__.CellWithInt', {'value': builtins.object, 'meta': builtins.int})'
reveal_type(c2) # N: Revealed type is 'TypedDict('__main__.CellWithObject', {'value': builtins.object, 'meta': builtins.object})'
reveal_type(joined_cells) # N: Revealed type is 'builtins.list[TypedDict({'value': builtins.object})]'
[builtins fixtures/dict.pyi]
[case testJoinOfDisjointTypedDictsIsEmptyTypedDict]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
Cell = TypedDict('Cell', {'value': object})
d1 = Point(x=0, y=0)
d2 = Cell(value='pear tree')
joined_dicts = [d1, d2]
reveal_type(d1) # N: Revealed type is 'TypedDict('__main__.Point', {'x': builtins.int, 'y': builtins.int})'
reveal_type(d2) # N: Revealed type is 'TypedDict('__main__.Cell', {'value': builtins.object})'
reveal_type(joined_dicts) # N: Revealed type is 'builtins.list[TypedDict({})]'
[builtins fixtures/dict.pyi]
[case testJoinOfTypedDictWithCompatibleMappingIsMapping]
from mypy_extensions import TypedDict
from typing import Mapping
Cell = TypedDict('Cell', {'value': int})
left = Cell(value=42)
right = {'score': 999} # type: Mapping[str, int]
joined1 = [left, right]
joined2 = [right, left]
reveal_type(joined1) # N: Revealed type is 'builtins.list[typing.Mapping*[builtins.str, builtins.object]]'
reveal_type(joined2) # N: Revealed type is 'builtins.list[typing.Mapping*[builtins.str, builtins.object]]'
[builtins fixtures/dict.pyi]
[case testJoinOfTypedDictWithCompatibleMappingSupertypeIsSupertype]
from mypy_extensions import TypedDict
from typing import Sized
Cell = TypedDict('Cell', {'value': int})
left = Cell(value=42)
right = {'score': 999} # type: Sized
joined1 = [left, right]
joined2 = [right, left]
reveal_type(joined1) # N: Revealed type is 'builtins.list[typing.Sized*]'
reveal_type(joined2) # N: Revealed type is 'builtins.list[typing.Sized*]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testJoinOfTypedDictWithIncompatibleTypeIsObject]
from mypy_extensions import TypedDict
from typing import Mapping
Cell = TypedDict('Cell', {'value': int})
left = Cell(value=42)
right = 42
joined1 = [left, right]
joined2 = [right, left]
reveal_type(joined1) # N: Revealed type is 'builtins.list[builtins.object*]'
reveal_type(joined2) # N: Revealed type is 'builtins.list[builtins.object*]'
[builtins fixtures/dict.pyi]
-- Meet
[case testMeetOfTypedDictsWithCompatibleCommonKeysHasAllKeysAndNewFallback]
from mypy_extensions import TypedDict
from typing import TypeVar, Callable
XY = TypedDict('XY', {'x': int, 'y': int})
YZ = TypedDict('YZ', {'y': int, 'z': int})
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: XY, y: YZ) -> None: pass
reveal_type(f(g)) # N: Revealed type is 'TypedDict({'x': builtins.int, 'y': builtins.int, 'z': builtins.int})'
[builtins fixtures/dict.pyi]
[case testMeetOfTypedDictsWithIncompatibleCommonKeysIsUninhabited]
# flags: --strict-optional
from mypy_extensions import TypedDict
from typing import TypeVar, Callable
XYa = TypedDict('XYa', {'x': int, 'y': int})
YbZ = TypedDict('YbZ', {'y': object, 'z': int})
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: XYa, y: YbZ) -> None: pass
reveal_type(f(g)) # N: Revealed type is '<nothing>'
[builtins fixtures/dict.pyi]
[case testMeetOfTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback]
from mypy_extensions import TypedDict
from typing import TypeVar, Callable
X = TypedDict('X', {'x': int})
Z = TypedDict('Z', {'z': int})
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: X, y: Z) -> None: pass
reveal_type(f(g)) # N: Revealed type is 'TypedDict({'x': builtins.int, 'z': builtins.int})'
[builtins fixtures/dict.pyi]
# TODO: It would be more accurate for the meet to be TypedDict instead.
[case testMeetOfTypedDictWithCompatibleMappingIsUninhabitedForNow]
# flags: --strict-optional
from mypy_extensions import TypedDict
from typing import TypeVar, Callable, Mapping
X = TypedDict('X', {'x': int})
M = Mapping[str, int]
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: X, y: M) -> None: pass
reveal_type(f(g)) # N: Revealed type is '<nothing>'
[builtins fixtures/dict.pyi]
[case testMeetOfTypedDictWithIncompatibleMappingIsUninhabited]
# flags: --strict-optional
from mypy_extensions import TypedDict
from typing import TypeVar, Callable, Mapping
X = TypedDict('X', {'x': int})
M = Mapping[str, str]
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: X, y: M) -> None: pass
reveal_type(f(g)) # N: Revealed type is '<nothing>'
[builtins fixtures/dict.pyi]
# TODO: It would be more accurate for the meet to be TypedDict instead.
[case testMeetOfTypedDictWithCompatibleMappingSuperclassIsUninhabitedForNow]
# flags: --strict-optional
from mypy_extensions import TypedDict
from typing import TypeVar, Callable, Iterable
X = TypedDict('X', {'x': int})
I = Iterable[str]
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: X, y: I) -> None: pass
reveal_type(f(g)) # N: Revealed type is '<nothing>'
[builtins fixtures/dict.pyi]
[case testMeetOfTypedDictsWithNonTotal]
from mypy_extensions import TypedDict
from typing import TypeVar, Callable
XY = TypedDict('XY', {'x': int, 'y': int}, total=False)
YZ = TypedDict('YZ', {'y': int, 'z': int}, total=False)
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: XY, y: YZ) -> None: pass
reveal_type(f(g)) # N: Revealed type is 'TypedDict({'x'?: builtins.int, 'y'?: builtins.int, 'z'?: builtins.int})'
[builtins fixtures/dict.pyi]
[case testMeetOfTypedDictsWithNonTotalAndTotal]
from mypy_extensions import TypedDict
from typing import TypeVar, Callable
XY = TypedDict('XY', {'x': int}, total=False)
YZ = TypedDict('YZ', {'y': int, 'z': int})
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: XY, y: YZ) -> None: pass
reveal_type(f(g)) # N: Revealed type is 'TypedDict({'x'?: builtins.int, 'y': builtins.int, 'z': builtins.int})'
[builtins fixtures/dict.pyi]
[case testMeetOfTypedDictsWithIncompatibleNonTotalAndTotal]
# flags: --strict-optional
from mypy_extensions import TypedDict
from typing import TypeVar, Callable
XY = TypedDict('XY', {'x': int, 'y': int}, total=False)
YZ = TypedDict('YZ', {'y': int, 'z': int})
T = TypeVar('T')
def f(x: Callable[[T, T], None]) -> T: pass
def g(x: XY, y: YZ) -> None: pass
reveal_type(f(g)) # N: Revealed type is '<nothing>'
[builtins fixtures/dict.pyi]
-- Constraint Solver
[case testTypedDictConstraintsAgainstIterable]
from typing import TypeVar, Iterable
from mypy_extensions import TypedDict
T = TypeVar('T')
def f(x: Iterable[T]) -> T: pass
A = TypedDict('A', {'x': int})
a: A
reveal_type(f(a)) # N: Revealed type is 'builtins.str*'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
-- TODO: Figure out some way to trigger the ConstraintBuilderVisitor.visit_typeddict_type() path.
-- Special Method: __getitem__
[case testCanGetItemOfTypedDictWithValidStringLiteralKey]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
reveal_type(p['type']) # N: Revealed type is 'builtins.str'
reveal_type(p['x']) # N: Revealed type is 'builtins.int'
reveal_type(p['y']) # N: Revealed type is 'builtins.int'
[builtins fixtures/dict.pyi]
[case testCanGetItemOfTypedDictWithValidBytesOrUnicodeLiteralKey]
# flags: --python-version 2.7
from mypy_extensions import TypedDict
Cell = TypedDict('Cell', {'value': int})
c = Cell(value=42)
reveal_type(c['value']) # N: Revealed type is 'builtins.int'
reveal_type(c[u'value']) # N: Revealed type is 'builtins.int'
[builtins_py2 fixtures/dict.pyi]
[case testCannotGetItemOfTypedDictWithInvalidStringLiteralKey]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p: TaggedPoint
p['z'] # E: TypedDict "TaggedPoint" has no key 'z'
[builtins fixtures/dict.pyi]
[case testCannotGetItemOfAnonymousTypedDictWithInvalidStringLiteralKey]
from typing import TypeVar
from mypy_extensions import TypedDict
A = TypedDict('A', {'x': str, 'y': int, 'z': str})
B = TypedDict('B', {'x': str, 'z': int})
C = TypedDict('C', {'x': str, 'y': int, 'z': int})
T = TypeVar('T')
def join(x: T, y: T) -> T: return x
ab = join(A(x='', y=1, z=''), B(x='', z=1))
ac = join(A(x='', y=1, z=''), C(x='', y=0, z=1))
ab['y'] # E: 'y' is not a valid TypedDict key; expected one of ('x')
ac['a'] # E: 'a' is not a valid TypedDict key; expected one of ('x', 'y')
[builtins fixtures/dict.pyi]
[case testCannotGetItemOfTypedDictWithNonLiteralKey]
from mypy_extensions import TypedDict
from typing import Union
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
def get_coordinate(p: TaggedPoint, key: str) -> Union[str, int]:
return p[key] # E: TypedDict key must be a string literal; expected one of ('type', 'x', 'y')
[builtins fixtures/dict.pyi]
-- Special Method: __setitem__
[case testCanSetItemOfTypedDictWithValidStringLiteralKeyAndCompatibleValueType]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
p['type'] = 'two_d'
p['x'] = 1
[builtins fixtures/dict.pyi]
[case testCannotSetItemOfTypedDictWithIncompatibleValueType]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
p['x'] = 'y' # E: Argument 2 has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]
[case testCannotSetItemOfTypedDictWithInvalidStringLiteralKey]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
p['z'] = 1 # E: TypedDict "TaggedPoint" has no key 'z'
[builtins fixtures/dict.pyi]
[case testCannotSetItemOfTypedDictWithNonLiteralKey]
from mypy_extensions import TypedDict
from typing import Union
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
def set_coordinate(p: TaggedPoint, key: str, value: int) -> None:
p[key] = value # E: TypedDict key must be a string literal; expected one of ('type', 'x', 'y')
[builtins fixtures/dict.pyi]
-- isinstance
[case testTypedDictWithIsInstanceAndIsSubclass]
from mypy_extensions import TypedDict
D = TypedDict('D', {'x': int})
d: object
if isinstance(d, D): # E: Cannot use isinstance() with a TypedDict type
reveal_type(d) # N: Revealed type is '__main__.D'
issubclass(object, D) # E: Cannot use issubclass() with a TypedDict type
[builtins fixtures/isinstancelist.pyi]
-- Scoping
[case testTypedDictInClassNamespace]
# https://github.com/python/mypy/pull/2553#issuecomment-266474341
from mypy_extensions import TypedDict
class C:
def f(self):
A = TypedDict('A', {'x': int})
def g(self):
A = TypedDict('A', {'y': int})
C.A # E: "Type[C]" has no attribute "A"
[builtins fixtures/dict.pyi]
[case testTypedDictInFunction]
from mypy_extensions import TypedDict
def f() -> None:
A = TypedDict('A', {'x': int})
A # E: Name 'A' is not defined
[builtins fixtures/dict.pyi]
-- Union simplification / proper subtype checks
[case testTypedDictUnionSimplification]
from typing import TypeVar, Union, Any, cast
from mypy_extensions import TypedDict
T = TypeVar('T')
S = TypeVar('S')
def u(x: T, y: S) -> Union[S, T]: pass
C = TypedDict('C', {'a': int})
D = TypedDict('D', {'a': int, 'b': int})
E = TypedDict('E', {'a': str})
F = TypedDict('F', {'x': int})
G = TypedDict('G', {'a': Any})
c = C(a=1)
d = D(a=1, b=1)
e = E(a='')
f = F(x=1)
g = G(a=cast(Any, 1)) # Work around #2610
reveal_type(u(d, d)) # N: Revealed type is 'TypedDict('__main__.D', {'a': builtins.int, 'b': builtins.int})'
reveal_type(u(c, d)) # N: Revealed type is 'TypedDict('__main__.C', {'a': builtins.int})'
reveal_type(u(d, c)) # N: Revealed type is 'TypedDict('__main__.C', {'a': builtins.int})'
reveal_type(u(c, e)) # N: Revealed type is 'Union[TypedDict('__main__.E', {'a': builtins.str}), TypedDict('__main__.C', {'a': builtins.int})]'
reveal_type(u(e, c)) # N: Revealed type is 'Union[TypedDict('__main__.C', {'a': builtins.int}), TypedDict('__main__.E', {'a': builtins.str})]'
reveal_type(u(c, f)) # N: Revealed type is 'Union[TypedDict('__main__.F', {'x': builtins.int}), TypedDict('__main__.C', {'a': builtins.int})]'
reveal_type(u(f, c)) # N: Revealed type is 'Union[TypedDict('__main__.C', {'a': builtins.int}), TypedDict('__main__.F', {'x': builtins.int})]'
reveal_type(u(c, g)) # N: Revealed type is 'Union[TypedDict('__main__.G', {'a': Any}), TypedDict('__main__.C', {'a': builtins.int})]'
reveal_type(u(g, c)) # N: Revealed type is 'Union[TypedDict('__main__.C', {'a': builtins.int}), TypedDict('__main__.G', {'a': Any})]'
[builtins fixtures/dict.pyi]
[case testTypedDictUnionSimplification2]
from typing import TypeVar, Union, Mapping, Any
from mypy_extensions import TypedDict
T = TypeVar('T')
S = TypeVar('S')
def u(x: T, y: S) -> Union[S, T]: pass
C = TypedDict('C', {'a': int, 'b': int})
c = C(a=1, b=1)
m_s_o: Mapping[str, object]
m_s_s: Mapping[str, str]
m_i_i: Mapping[int, int]
m_s_a: Mapping[str, Any]
reveal_type(u(c, m_s_o)) # N: Revealed type is 'typing.Mapping*[builtins.str, builtins.object]'
reveal_type(u(m_s_o, c)) # N: Revealed type is 'typing.Mapping*[builtins.str, builtins.object]'
reveal_type(u(c, m_s_s)) # N: Revealed type is 'Union[typing.Mapping*[builtins.str, builtins.str], TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})]'
reveal_type(u(c, m_i_i)) # N: Revealed type is 'Union[typing.Mapping*[builtins.int, builtins.int], TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})]'
reveal_type(u(c, m_s_a)) # N: Revealed type is 'Union[typing.Mapping*[builtins.str, Any], TypedDict('__main__.C', {'a': builtins.int, 'b': builtins.int})]'
[builtins fixtures/dict.pyi]
-- Use dict literals
[case testTypedDictDictLiterals]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
def f(p: Point) -> None:
if int():
p = {'x': 2, 'y': 3}
p = {'x': 2} # E: Key 'y' missing for TypedDict "Point"
p = dict(x=2, y=3)
f({'x': 1, 'y': 3})
f({'x': 1, 'y': 'z'}) # E: Incompatible types (expression has type "str", TypedDict item "y" has type "int")
f(dict(x=1, y=3))
f(dict(x=1, y=3, z=4)) # E: Extra key 'z' for TypedDict "Point"
f(dict(x=1, y=3, z=4, a=5)) # E: Extra keys ('z', 'a') for TypedDict "Point"
[builtins fixtures/dict.pyi]
[case testTypedDictExplicitTypes]
from mypy_extensions import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p1a: Point = {'x': 'hi'} # E: Key 'y' missing for TypedDict "Point"
p1b: Point = {} # E: Keys ('x', 'y') missing for TypedDict "Point"
p2: Point
p2 = dict(x='bye') # E: Key 'y' missing for TypedDict "Point"
p3 = Point(x=1, y=2)
if int():
p3 = {'x': 'hi'} # E: Key 'y' missing for TypedDict "Point"
p4: Point = {'x': 1, 'y': 2}
[builtins fixtures/dict.pyi]
[case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithExtraItems]
from mypy_extensions import TypedDict
from typing import TypeVar
A = TypedDict('A', {'x': int, 'y': int})
B = TypedDict('B', {'x': int, 'y': str})
T = TypeVar('T')
def join(x: T, y: T) -> T: return x
ab = join(A(x=1, y=1), B(x=1, y=''))
if int():
ab = {'x': 1, 'z': 1} # E: Expected TypedDict key 'x' but found keys ('x', 'z')
[builtins fixtures/dict.pyi]
[case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithMissingItems]
from mypy_extensions import TypedDict
from typing import TypeVar
A = TypedDict('A', {'x': int, 'y': int, 'z': int})
B = TypedDict('B', {'x': int, 'y': int, 'z': str})
T = TypeVar('T')
def join(x: T, y: T) -> T: return x
ab = join(A(x=1, y=1, z=1), B(x=1, y=1, z=''))
if int():
ab = {} # E: Expected TypedDict keys ('x', 'y') but found no keys
[builtins fixtures/dict.pyi]
-- Other TypedDict methods
[case testTypedDictGetMethod]
# flags: --strict-optional
from mypy_extensions import TypedDict
class A: pass
D = TypedDict('D', {'x': int, 'y': str})
d: D
reveal_type(d.get('x')) # N: Revealed type is 'Union[builtins.int, None]'
reveal_type(d.get('y')) # N: Revealed type is 'Union[builtins.str, None]'
reveal_type(d.get('x', A())) # N: Revealed type is 'Union[builtins.int, __main__.A]'
reveal_type(d.get('x', 1)) # N: Revealed type is 'builtins.int'
reveal_type(d.get('y', None)) # N: Revealed type is 'Union[builtins.str, None]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testTypedDictGetMethodTypeContext]
# flags: --strict-optional
from typing import List
from mypy_extensions import TypedDict
class A: pass
D = TypedDict('D', {'x': List[int], 'y': int})
d: D
reveal_type(d.get('x', [])) # N: Revealed type is 'builtins.list[builtins.int]'
d.get('x', ['x']) # E: List item 0 has incompatible type "str"; expected "int"
a = ['']
reveal_type(d.get('x', a)) # N: Revealed type is 'Union[builtins.list[builtins.int], builtins.list[builtins.str*]]'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testTypedDictGetMethodInvalidArgs]
from mypy_extensions import TypedDict
D = TypedDict('D', {'x': int, 'y': str})
d: D
d.get() # E: All overload variants of "get" of "Mapping" require at least one argument \
# N: Possible overload variants: \
# N: def get(self, k: str) -> object \
# N: def [V] get(self, k: str, default: object) -> object
d.get('x', 1, 2) # E: No overload variant of "get" of "Mapping" matches argument types "str", "int", "int" \
# N: Possible overload variants: \
# N: def get(self, k: str) -> object \
# N: def [V] get(self, k: str, default: Union[int, V]) -> object
x = d.get('z') # E: TypedDict "D" has no key 'z'
reveal_type(x) # N: Revealed type is 'Any'
s = ''
y = d.get(s)
reveal_type(y) # N: Revealed type is 'builtins.object*'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testTypedDictMissingMethod]
from mypy_extensions import TypedDict
D = TypedDict('D', {'x': int, 'y': str})
d: D
d.bad(1) # E: "D" has no attribute "bad"
[builtins fixtures/dict.pyi]
[case testTypedDictChainedGetMethodWithDictFallback]
from mypy_extensions import TypedDict
D = TypedDict('D', {'x': int, 'y': str})
E = TypedDict('E', {'d': D})
p = E(d=D(x=0, y=''))
reveal_type(p.get('d', {'x': 1, 'y': ''})) # N: Revealed type is 'TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testTypedDictGetDefaultParameterStillTypeChecked]
from mypy_extensions import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
p.get('x', 1 + 'y') # E: Unsupported operand types for + ("int" and "str")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
[case testTypedDictChainedGetWithEmptyDictDefault]
# flags: --strict-optional
from mypy_extensions import TypedDict
C = TypedDict('C', {'a': int})
D = TypedDict('D', {'x': C, 'y': str})
d: D
reveal_type(d.get('x', {})) \
# N: Revealed type is 'TypedDict('__main__.C', {'a'?: builtins.int})'
reveal_type(d.get('x', None)) \
# N: Revealed type is 'Union[TypedDict('__main__.C', {'a': builtins.int}), None]'
reveal_type(d.get('x', {}).get('a')) # N: Revealed type is 'Union[builtins.int, None]'
reveal_type(d.get('x', {})['a']) # N: Revealed type is 'builtins.int'
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]
-- Totality (the "total" keyword argument)
[case testTypedDictWithTotalTrue]
from mypy_extensions import TypedDict
D = TypedDict('D', {'x': int, 'y': str}, total=True)
d: D
reveal_type(d) \
# N: Revealed type is 'TypedDict('__main__.D', {'x': builtins.int, 'y': builtins.str})'
[builtins fixtures/dict.pyi]
[case testTypedDictWithInvalidTotalArgument]
from mypy_extensions import TypedDict
A = TypedDict('A', {'x': int}, total=0) # E: TypedDict() "total" argument must be True or False
B = TypedDict('B', {'x': int}, total=bool) # E: TypedDict() "total" argument must be True or False
C = TypedDict('C', {'x': int}, x=False) # E: Unexpected keyword argument "x" for "TypedDict"
D = TypedDict('D', {'x': int}, False) # E: Unexpected arguments to TypedDict()
[builtins fixtures/dict.pyi]
[case testTypedDictWithTotalFalse]
from mypy_extensions import TypedDict
D = TypedDict('D', {'x': int, 'y': str}, total=False)
def f(d: D) -> None:
reveal_type(d) # N: Revealed type is 'TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})'
f({})