File: check-typeddict.test

package info (click to toggle)
mypy 1.19.1-5
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 22,464 kB
  • sloc: python: 114,757; ansic: 13,343; cpp: 11,380; makefile: 254; sh: 31
file content (4549 lines) | stat: -rw-r--r-- 150,498 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
-- Create Instance

[case testCanCreateTypedDictInstanceWithKeywordArguments]
from typing 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-typeddict.pyi]
[targets __main__]

[case testCanCreateTypedDictInstanceWithDictCall]
from typing 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-typeddict.pyi]

[case testCanCreateTypedDictInstanceWithDictLiteral]
from typing 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-typeddict.pyi]

[case testCanCreateTypedDictInstanceWithNoArguments]
from typing import TypedDict, TypeVar, Union
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-typeddict.pyi]


-- Create Instance (Errors)

[case testCannotCreateTypedDictInstanceWithUnknownArgumentPattern]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictInstanceNonLiteralItemName]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictInstanceWithExtraItems]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictInstanceWithMissingItems]
from typing import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
p = Point(x=42)  # E: Missing key "y" for TypedDict "Point"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictInstanceWithIncompatibleItemType]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictInstanceWithInlineTypedDict]
from typing import TypedDict
D = TypedDict('D', {
    'x': TypedDict('E', {  # E: Use dict literal for nested TypedDict
        'y': int
    })
})
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

-- Define TypedDict (Class syntax)

[case testCanCreateTypedDictWithClass]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithSubclass]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithSubclass2]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictClassEmpty]
from typing import TypedDict

class EmptyDict(TypedDict):
    pass

p = EmptyDict()
reveal_type(p)  # N: Revealed type is "TypedDict('__main__.EmptyDict', {})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testCanCreateTypedDictWithClassOldVersion]
# Test that we can use class-syntax to merge function-based TypedDicts
from typing 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: Missing keys ("name", "year") 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]
[typing fixtures/typing-typeddict.pyi]

-- Define TypedDict (Class syntax errors)

[case testCannotCreateTypedDictWithClassOtherBases]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictWithDuplicateBases]
# https://github.com/python/mypy/issues/3673
from typing import TypedDict

class A(TypedDict):
    x: str
    y: int

class B(A, A): # E: Duplicate base class "A"
    z: str

class C(TypedDict, TypedDict): # E: Duplicate base class "TypedDict"
    c1: int
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictWithClassWithOtherStuff]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictWithClassWithFunctionUsedToCrash]
# https://github.com/python/mypy/issues/11079
from typing import TypedDict
class D(TypedDict):
    y: int
    def x(self, key: int):  # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
        pass

d = D(y=1)
reveal_type(d)  # N: Revealed type is "TypedDict('__main__.D', {'y': builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictWithDecoratedFunction]
# flags: --disallow-any-expr
# https://github.com/python/mypy/issues/13066
from typing import TypedDict
class D(TypedDict):
    @classmethod  # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
    def m(self) -> D:
        pass
d = D()
reveal_type(d)  # N: Revealed type is "TypedDict('__main__.D', {})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithClassmethodAlternativeConstructorDoesNotCrash]
# https://github.com/python/mypy/issues/5653
from typing import TypedDict

class Foo(TypedDict):
    bar: str
    @classmethod  # E: Invalid statement in TypedDict definition; expected "field_name: field_type"
    def baz(cls) -> "Foo": ...
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictTypeWithUnderscoreItemName]
from typing import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int, '_fallback': object})
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithClassUnderscores]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictWithDuplicateKey1]
from typing import TypedDict

class Bad(TypedDict):
    x: int
    x: str # E: Duplicate TypedDict key "x"

b: Bad
reveal_type(b) # N: Revealed type is "TypedDict('__main__.Bad', {'x': builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictWithDuplicateKey2]
from typing import TypedDict

D1 = TypedDict("D1", {
    "x": int,
    "x": int,  # E: Duplicate TypedDict key "x"
})
D2 = TypedDict("D2", {"x": int, "x": str})  # E: Duplicate TypedDict key "x"

d1: D1
d2: D2
reveal_type(d1) # N: Revealed type is "TypedDict('__main__.D1', {'x': builtins.int})"
reveal_type(d2) # N: Revealed type is "TypedDict('__main__.D2', {'x': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithClassOverwriting]
from typing import TypedDict

class Point1(TypedDict):
    x: int
class Point2(TypedDict):
    x: float
class Bad(Point1, Point2): # E: Overwriting 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]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithClassOverwriting2]
from typing import TypedDict

class Point1(TypedDict):
    x: int
class Point2(Point1):
    x: float # E: Overwriting TypedDict field "x" while extending

p2: Point2
reveal_type(p2) # N: Revealed type is "TypedDict('__main__.Point2', {'x': builtins.float})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


-- Subtyping

[case testCanConvertTypedDictToItself]
from typing import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
def identity(p: Point) -> Point:
    return p
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCanConvertTypedDictToEquivalentTypedDict]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotConvertTypedDictToSimilarTypedDictWithNarrowerItemTypes]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotConvertTypedDictToSimilarTypedDictWithWiderItemTypes]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotConvertTypedDictToSimilarTypedDictWithIncompatibleItemTypes]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCanConvertTypedDictToNarrowerTypedDict]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotConvertTypedDictToWiderTypedDict]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCanConvertTypedDictToCompatibleMapping]
from typing import Mapping, TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
def as_mapping(p: Point) -> Mapping[str, object]:
    return p
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotConvertTypedDictToIncompatibleMapping]
from typing import Mapping, TypedDict
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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAcceptsIntForFloatDuckTypes]
from typing import Any, Mapping, TypedDict
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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictDoesNotAcceptsFloatForInt]
from typing import Any, Mapping, TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
def create_point() -> Point:
    return Point(x=1.2, y=2.5)
[out]
main:4: error: Incompatible types (expression has type "float", TypedDict item "x" has type "int")
main:4: error: Incompatible types (expression has type "float", TypedDict item "y" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAcceptsAnyType]
from typing import Any, Mapping, TypedDict
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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictValueTypeContext]
from typing import List, TypedDict
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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotConvertTypedDictToDictOrMutableMapping]
from typing import Dict, MutableMapping, TypedDict
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 typing import Any, TypedDict
Point = TypedDict('Point', {'x': int, 'y': int})
def unprotect(p: Point) -> Any:
    return p
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testAnonymousTypedDictInErrorMessages]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithSimpleProtocol]
from typing import Protocol, 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]
[typing fixtures/typing-typeddict.pyi]
[out]
main:17: error: Argument 1 to "fun2" has incompatible type "A"; expected "StrIntMap"
main:17: note: Following member(s) of "A" have conflicts:
main:17: note:     Expected:
main:17: note:         def __getitem__(self, str, /) -> int
main:17: note:     Got:
main:17: note:         def __getitem__(self, str, /) -> object

[case testTypedDictWithSimpleProtocolInference]
from typing import Protocol, TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]

-- Join

[case testJoinOfTypedDictHasOnlyCommonKeysAndNewFallback]
from typing 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-typeddict.pyi]

[case testJoinOfTypedDictRemovesNonequivalentKeys]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testJoinOfDisjointTypedDictsIsEmptyTypedDict]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testJoinOfTypedDictWithCompatibleMappingIsMapping]
from typing import Mapping, TypedDict
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]
[typing fixtures/typing-typeddict.pyi]

[case testJoinOfTypedDictWithCompatibleMappingSupertypeIsSupertype]
from typing import Sized, TypedDict
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-typeddict.pyi]

[case testJoinOfTypedDictWithIncompatibleTypeIsObject]
from typing import Mapping, TypedDict
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]
[typing fixtures/typing-typeddict.pyi]


-- Meet

[case testMeetOfTypedDictsWithCompatibleCommonKeysHasAllKeysAndNewFallback]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictsWithIncompatibleCommonKeysIsUninhabited]
from typing import TypedDict, 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 "Never"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictsWithNoCommonKeysHasAllKeysAndNewFallback]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]

# TODO: It would be more accurate for the meet to be TypedDict instead.
[case testMeetOfTypedDictWithCompatibleMappingIsUninhabitedForNow]
from typing import TypedDict, 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 "Never"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictWithIncompatibleMappingIsUninhabited]
from typing import TypedDict, 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 "Never"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictWithCompatibleMappingSuperclassIsUninhabitedForNow]
from typing import TypedDict, 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 "TypedDict('__main__.X', {'x': builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictsWithNonTotal]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictsWithNonTotalAndTotal]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictsWithIncompatibleNonTotalAndTotal]
from typing import TypedDict, 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 "Never"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


-- Constraint Solver

[case testTypedDictConstraintsAgainstIterable]
from typing import TypedDict, TypeVar, Iterable
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-typeddict.pyi]

-- TODO: Figure out some way to trigger the ConstraintBuilderVisitor.visit_typeddict_type() path.


-- Special Method: __getitem__

[case testCanGetItemOfTypedDictWithValidStringLiteralKey]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotGetItemOfTypedDictWithInvalidStringLiteralKey]
from typing import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p: TaggedPoint
p['typ']  # E: TypedDict "TaggedPoint" has no key "typ" \
          # N: Did you mean "type"?
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotGetItemOfAnonymousTypedDictWithInvalidStringLiteralKey]
from typing import TypedDict, TypeVar
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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotGetItemOfTypedDictWithNonLiteralKey]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]


-- Special Method: __setitem__

[case testCanSetItemOfTypedDictWithValidStringLiteralKeyAndCompatibleValueType]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotSetItemOfTypedDictWithIncompatibleValueType]
from typing import TypedDict
TaggedPoint = TypedDict('TaggedPoint', {'type': str, 'x': int, 'y': int})
p = TaggedPoint(type='2d', x=42, y=1337)
p['x'] = 'y'  # E: Value of "x" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotSetItemOfTypedDictWithInvalidStringLiteralKey]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotSetItemOfTypedDictWithNonLiteralKey]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]


-- isinstance

[case testTypedDictWithIsInstanceAndIsSubclass]
from typing import TypedDict
D = TypedDict('D', {'x': int})
d: object
if isinstance(d, D):   # E: Cannot use isinstance() with TypedDict type
    reveal_type(d)     # N: Revealed type is "__main__.D"
issubclass(object, D)  # E: Cannot use issubclass() with TypedDict type
[builtins fixtures/isinstancelist.pyi]
[typing fixtures/typing-typeddict.pyi]


-- Scoping

[case testTypedDictInClassNamespace]
# https://github.com/python/mypy/pull/2553#issuecomment-266474341
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInFunction]
from typing import TypedDict
def f() -> None:
    A = TypedDict('A', {'x': int})
A  # E: Name "A" is not defined
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


-- Union simplification / proper subtype checks

[case testTypedDictUnionSimplification]
from typing import TypedDict, TypeVar, Union, Any, cast

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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnionSimplification2]
from typing import TypedDict, TypeVar, Union, Mapping, Any

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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnionUnambiguousCase]
from typing import Union, Literal, Mapping, TypedDict, Any, cast

A = TypedDict('A', {'@type': Literal['a-type'], 'a': str})
B = TypedDict('B', {'@type': Literal['b-type'], 'b': int})

c: Union[A, B] = {'@type': 'a-type', 'a': 'Test'}
reveal_type(c) # N: Revealed type is "Union[TypedDict('__main__.A', {'@type': Literal['a-type'], 'a': builtins.str}), TypedDict('__main__.B', {'@type': Literal['b-type'], 'b': builtins.int})]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnionAmbiguousCaseBothMatch]
from typing import Union, Literal, Mapping, TypedDict, Any, cast

A = TypedDict('A', {'@type': Literal['a-type'], 'value': str})
B = TypedDict('B', {'@type': Literal['b-type'], 'value': str})

c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnionAmbiguousCaseNoMatch]
from typing import Union, Literal, Mapping, TypedDict, Any, cast

A = TypedDict('A', {'@type': Literal['a-type'], 'value': int})
B = TypedDict('B', {'@type': Literal['b-type'], 'value': int})

c: Union[A, B] = {'@type': 'a-type', 'value': 'Test'}  # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \
                                                       # E: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "Union[A, B]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

-- Use dict literals

[case testTypedDictDictLiterals]
from typing 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: Missing key "y" 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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictExplicitTypes]
from typing import TypedDict

Point = TypedDict('Point', {'x': int, 'y': int})

p1a: Point = {'x': 'hi'}  # E: Missing key "y" for TypedDict "Point"
p1b: Point = {}           # E: Missing keys ("x", "y") for TypedDict "Point"

p2: Point
p2 = dict(x='bye')  # E: Missing key "y" for TypedDict "Point"

p3 = Point(x=1, y=2)
if int():
    p3 = {'x': 'hi'}  # E: Missing key "y" for TypedDict "Point"

p4: Point = {'x': 1, 'y': 2}

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithExtraItems]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateAnonymousTypedDictInstanceUsingDictLiteralWithMissingItems]
from typing import TypedDict, 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]
[typing fixtures/typing-typeddict.pyi]


-- Other TypedDict methods


[case testTypedDictGetMethodOverloads]
from typing import TypedDict
from typing_extensions import Required, NotRequired

class D(TypedDict):
    a: int
    b: NotRequired[str]

def test(d: D) -> None:
    reveal_type(d.get)  # N: Revealed type is "Overload(def (k: builtins.str) -> builtins.object, def (builtins.str, builtins.object) -> builtins.object, def [V] (builtins.str, V`4) -> builtins.object)"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictGetMethodTotalFalse]
from typing import TypedDict, Literal
class Unrelated: pass
D = TypedDict('D', {'x': int, 'y': str}, total=False)
d: D
u: Unrelated
x: Literal['x']
y: Literal['y']
z: Literal['z']
x_or_y: Literal['x', 'y']
x_or_z: Literal['x', 'z']
x_or_y_or_z: Literal['x', 'y', 'z']

# test with literal expression
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('z')) # N: Revealed type is "builtins.object"
reveal_type(d.get('x', u)) # N: Revealed type is "Union[builtins.int, __main__.Unrelated]"
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]"

# test with literal type / union of literal types with implicit default
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(z)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y)) # N: Revealed type is "Union[builtins.int, builtins.str, None]"
reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object"

# test with literal type / union of literal types with explicit default
reveal_type(d.get(x, u)) # N: Revealed type is "Union[builtins.int, __main__.Unrelated]"
reveal_type(d.get(y, u)) # N: Revealed type is "Union[builtins.str, __main__.Unrelated]"
reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y, u)) # N: Revealed type is "Union[builtins.int, builtins.str, __main__.Unrelated]"
reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictGetMethodTotalTrue]
from typing import TypedDict, Literal
class Unrelated: pass
D = TypedDict('D', {'x': int, 'y': str}, total=True)
d: D
u: Unrelated
x: Literal['x']
y: Literal['y']
z: Literal['z']
x_or_y: Literal['x', 'y']
x_or_z: Literal['x', 'z']
x_or_y_or_z: Literal['x', 'y', 'z']

# test with literal expression
reveal_type(d.get('x')) # N: Revealed type is "builtins.int"
reveal_type(d.get('y')) # N: Revealed type is "builtins.str"
reveal_type(d.get('z')) # N: Revealed type is "builtins.object"
reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int"
reveal_type(d.get('x', 1)) # N: Revealed type is "builtins.int"
reveal_type(d.get('y', None)) # N: Revealed type is "builtins.str"

# test with literal type / union of literal types with implicit default
reveal_type(d.get(x)) # N: Revealed type is "builtins.int"
reveal_type(d.get(y)) # N: Revealed type is "builtins.str"
reveal_type(d.get(z)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y)) # N: Revealed type is "Union[builtins.int, builtins.str]"
reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object"

# test with literal type / union of literal types with explicit default
reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int"
reveal_type(d.get(y, u)) # N: Revealed type is "builtins.str"
reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y, u)) # N: Revealed type is "Union[builtins.int, builtins.str]"
reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object"

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictGetMethodTotalMixed]
from typing import TypedDict, Literal
from typing_extensions import Required, NotRequired
class Unrelated: pass
D = TypedDict('D', {'x': Required[int], 'y': NotRequired[str]})
d: D
u: Unrelated
x: Literal['x']
y: Literal['y']
z: Literal['z']
x_or_y: Literal['x', 'y']
x_or_z: Literal['x', 'z']
x_or_y_or_z: Literal['x', 'y', 'z']

# test with literal expression
reveal_type(d.get('x')) # N: Revealed type is "builtins.int"
reveal_type(d.get('y')) # N: Revealed type is "Union[builtins.str, None]"
reveal_type(d.get('z')) # N: Revealed type is "builtins.object"
reveal_type(d.get('x', u)) # N: Revealed type is "builtins.int"
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]"

# test with literal type / union of literal types with implicit default
reveal_type(d.get(x)) # N: Revealed type is "builtins.int"
reveal_type(d.get(y)) # N: Revealed type is "Union[builtins.str, None]"
reveal_type(d.get(z)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y)) # N: Revealed type is "Union[builtins.int, builtins.str, None]"
reveal_type(d.get(x_or_z)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y_or_z)) # N: Revealed type is "builtins.object"

# test with literal type / union of literal types with explicit default
reveal_type(d.get(x, u)) # N: Revealed type is "builtins.int"
reveal_type(d.get(y, u)) # N: Revealed type is "Union[builtins.str, __main__.Unrelated]"
reveal_type(d.get(z, u)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y, u)) # N: Revealed type is "Union[builtins.int, builtins.str, __main__.Unrelated]"
reveal_type(d.get(x_or_z, u)) # N: Revealed type is "builtins.object"
reveal_type(d.get(x_or_y_or_z, u)) # N: Revealed type is "builtins.object"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictGetMethodTypeContext]
from typing import List, TypedDict
class A: pass
D = TypedDict('D', {'x': List[int], 'y': int}, total=False)
d: D
reveal_type(d.get('x', [])) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(d.get('x', ['x']))  # N: Revealed type is "Union[builtins.list[builtins.int], builtins.list[builtins.str]]"
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-typeddict.pyi]

[case testTypedDictGetMethodInvalidArgs]
from typing 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 get(self, str, object, /) -> object \
        # N:     def [V] get(self, str, V, /) -> 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 get(self, str, object, /) -> object \
                 # N:     def [V] get(self, str, Union[int, V], /) -> object
x = d.get('z')
reveal_type(x) # N: Revealed type is "builtins.object"
s = ''
y = d.get(s)
reveal_type(y) # N: Revealed type is "builtins.object"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictMissingMethod]
from typing import TypedDict
D = TypedDict('D', {'x': int, 'y': str})
d: D
d.bad(1) # E: "D" has no attribute "bad"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictChainedGetMethodWithDictFallback]
from typing 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-typeddict.pyi]

[case testTypedDictGetDefaultParameterStillTypeChecked]
from typing 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-typeddict.pyi]

[case testTypedDictChainedGetWithEmptyDictDefault]
from typing import TypedDict
C = TypedDict('C', {'a': int}, total=True)
D = TypedDict('D', {'x': C, 'y': str}, total=False)
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-typeddict.pyi]


[case testTypedDictChainedGetWithEmptyDictDefault2]
from typing import TypedDict
C = TypedDict('C', {'a': int}, total=False)
D = TypedDict('D', {'x': C, 'y': str}, total=True)
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 "TypedDict('__main__.C', {'a'?: builtins.int})"
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-typeddict.pyi]


[case testTypedDictChainedGetWithEmptyDictDefault3]
from typing import TypedDict
C = TypedDict('C', {'a': int}, total=True)
D = TypedDict('D', {'x': C, 'y': str}, total=True)
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 "TypedDict('__main__.C', {'a': builtins.int})"
reveal_type(d.get('x', {}).get('a')) # N: Revealed type is "builtins.int"
reveal_type(d.get('x', {})['a']) # N: Revealed type is "builtins.int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictChainedGetWithEmptyDictDefault4]
from typing import TypedDict
C = TypedDict('C', {'a': int}, total=False)
D = TypedDict('D', {'x': C, 'y': str}, total=False)
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-typeddict.pyi]


[case testTypedDictGetMethodChained]
# check that chaining with get like ``.get(key, {}).get(subkey, {})`` works.
from typing import TypedDict, Mapping
from typing_extensions import Required, NotRequired, Never

class Total(TypedDict, total=True):  # no keys optional
    key_one: int
    key_two: str

class Maybe(TypedDict, total=False):  # all keys are optional
    key_one: int
    key_two: str

class Mixed(TypedDict):  # some keys optional
    key_one: Required[int]
    key_two: NotRequired[str]

class Config(TypedDict):
    required_total: Required[Total]
    optional_total: NotRequired[Total]
    required_mixed: Required[Mixed]
    optional_mixed: NotRequired[Mixed]
    required_maybe: Required[Maybe]
    optional_maybe: NotRequired[Maybe]

def test_chaining(d: Config) -> None:
    reveal_type( d.get("required_total", {}) ) # N: Revealed type is "TypedDict('__main__.Total', {'key_one': builtins.int, 'key_two': builtins.str})"
    reveal_type( d.get("optional_total", {}) ) # N: Revealed type is "TypedDict('__main__.Total', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
    reveal_type( d.get("required_maybe", {}) ) # N: Revealed type is "TypedDict('__main__.Maybe', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
    reveal_type( d.get("optional_maybe", {}) ) # N: Revealed type is "TypedDict('__main__.Maybe', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"
    reveal_type( d.get("required_mixed", {}) ) # N: Revealed type is "TypedDict('__main__.Mixed', {'key_one': builtins.int, 'key_two'?: builtins.str})"
    reveal_type( d.get("optional_mixed", {}) ) # N: Revealed type is "TypedDict('__main__.Mixed', {'key_one'?: builtins.int, 'key_two'?: builtins.str})"

    reveal_type( d.get("required_total", {}).get("key_one")  )  # N: Revealed type is "builtins.int"
    reveal_type( d.get("required_total", {}).get("key_two")  )  # N: Revealed type is "builtins.str"
    reveal_type( d.get("required_total", {}).get("bad_key")  )  # N: Revealed type is "builtins.object"
    reveal_type( d.get("optional_total", {}).get("key_one")  )  # N: Revealed type is "Union[builtins.int, None]"
    reveal_type( d.get("optional_total", {}).get("key_two")  )  # N: Revealed type is "Union[builtins.str, None]"
    reveal_type( d.get("optional_total", {}).get("bad_key")  )  # N: Revealed type is "builtins.object"

    reveal_type( d.get("required_maybe", {}).get("key_one")  )  # N: Revealed type is "Union[builtins.int, None]"
    reveal_type( d.get("required_maybe", {}).get("key_two")  )  # N: Revealed type is "Union[builtins.str, None]"
    reveal_type( d.get("required_maybe", {}).get("bad_key")  )  # N: Revealed type is "builtins.object"
    reveal_type( d.get("optional_maybe", {}).get("key_one")  )  # N: Revealed type is "Union[builtins.int, None]"
    reveal_type( d.get("optional_maybe", {}).get("key_two")  )  # N: Revealed type is "Union[builtins.str, None]"
    reveal_type( d.get("optional_maybe", {}).get("bad_key")  )  # N: Revealed type is "builtins.object"

    reveal_type( d.get("required_mixed", {}).get("key_one")  )  # N: Revealed type is "builtins.int"
    reveal_type( d.get("required_mixed", {}).get("key_two")  )  # N: Revealed type is "Union[builtins.str, None]"
    reveal_type( d.get("required_mixed", {}).get("bad_key")  )  # N: Revealed type is "builtins.object"
    reveal_type( d.get("optional_mixed", {}).get("key_one")  )  # N: Revealed type is "Union[builtins.int, None]"
    reveal_type( d.get("optional_mixed", {}).get("key_two")  )  # N: Revealed type is "Union[builtins.str, None]"
    reveal_type( d.get("optional_mixed", {}).get("bad_key")  )  # N: Revealed type is "builtins.object"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictGetWithNestedUnionOfTypedDicts]
# https://github.com/python/mypy/issues/19902
from typing import TypedDict, Union
from typing_extensions import TypeAlias, NotRequired
class A(TypedDict):
    key: NotRequired[int]

class B(TypedDict):
    key: NotRequired[int]

class C(TypedDict):
    key: NotRequired[int]

A_or_B: TypeAlias = Union[A, B]
A_or_B_or_C: TypeAlias = Union[A_or_B, C]

def test(d: A_or_B_or_C) -> None:
    reveal_type(d.get("key"))  # N: Revealed type is "Union[builtins.int, None]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

-- Totality (the "total" keyword argument)

[case testTypedDictWithTotalTrue]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithInvalidTotalArgument]
from typing import TypedDict
A = TypedDict('A', {'x': int}, total=0) # E: "total" argument must be a True or False literal
B = TypedDict('B', {'x': int}, total=bool) # E: "total" argument must be a True or False literal
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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithTotalFalse]
from typing 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({})
f({'x': 1})
f({'y': ''})
f({'x': 1, 'y': ''})
f({'x': 1, 'z': ''}) # E: Extra key "z" for TypedDict "D"
f({'x': ''}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictConstructorWithTotalFalse]
from typing import TypedDict
D = TypedDict('D', {'x': int, 'y': str}, total=False)
def f(d: D) -> None: pass
reveal_type(D()) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
reveal_type(D(x=1)) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
f(D(y=''))
f(D(x=1, y=''))
f(D(x=1, z='')) # E: Extra key "z" for TypedDict "D"
f(D(x='')) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictIndexingWithNonRequiredKey]
from typing import TypedDict
D = TypedDict('D', {'x': int, 'y': str}, total=False)
d: D
reveal_type(d['x']) # N: Revealed type is "builtins.int"
reveal_type(d['y']) # N: Revealed type is "builtins.str"
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]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictSubtypingWithTotalFalse]
from typing import TypedDict
A = TypedDict('A', {'x': int})
B = TypedDict('B', {'x': int}, total=False)
C = TypedDict('C', {'x': int, 'y': str}, total=False)
def fa(a: A) -> None: pass
def fb(b: B) -> None: pass
def fc(c: C) -> None: pass
a: A
b: B
c: C
fb(b)
fc(c)
fb(c)
fb(a) # E: Argument 1 to "fb" has incompatible type "A"; expected "B"
fa(b) # E: Argument 1 to "fa" has incompatible type "B"; expected "A"
fc(b) # E: Argument 1 to "fc" has incompatible type "B"; expected "C"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictJoinWithTotalFalse]
from typing import TypedDict, TypeVar
A = TypedDict('A', {'x': int})
B = TypedDict('B', {'x': int}, total=False)
C = TypedDict('C', {'x': int, 'y': str}, total=False)
T = TypeVar('T')
def j(x: T, y: T) -> T: return x
a: A
b: B
c: C
reveal_type(j(a, b)) \
    # N: Revealed type is "TypedDict({})"
reveal_type(j(b, b)) \
    # N: Revealed type is "TypedDict({'x'?: builtins.int})"
reveal_type(j(c, c)) \
    # N: Revealed type is "TypedDict({'x'?: builtins.int, 'y'?: builtins.str})"
reveal_type(j(b, c)) \
    # N: Revealed type is "TypedDict({'x'?: builtins.int})"
reveal_type(j(c, b)) \
    # N: Revealed type is "TypedDict({'x'?: builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictClassWithTotalArgument]
from typing import TypedDict
class D(TypedDict, total=False):
    x: int
    y: str
d: D
reveal_type(d) # N: Revealed type is "TypedDict('__main__.D', {'x'?: builtins.int, 'y'?: builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictClassWithInvalidTotalArgument]
from typing import TypedDict
class D(TypedDict, total=1): # E: "total" argument must be a True or False literal
    x: int
class E(TypedDict, total=bool): # E: "total" argument must be a True or False literal
    x: int
class F(TypedDict, total=xyz): # E: Name "xyz" is not defined \
                               # E: "total" argument must be a True or False literal
    x: int
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictClassInheritanceWithTotalArgument]
from typing import TypedDict
class A(TypedDict):
    x: int
class B(TypedDict, A, total=False):
    y: int
class C(TypedDict, B, total=True):
    z: str
c: C
reveal_type(c) # N: Revealed type is "TypedDict('__main__.C', {'x': builtins.int, 'y'?: builtins.int, 'z': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testNonTotalTypedDictInErrorMessages]
from typing import TypedDict

A = TypedDict('A', {'x': int, 'y': str}, total=False)
B = TypedDict('B', {'x': int, 'z': str, 'a': int}, total=False)
C = TypedDict('C', {'x': int, 'z': str, 'a': str}, total=False)
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]
[typing fixtures/typing-typeddict.pyi]

[case testNonTotalTypedDictCanBeEmpty]
# flags: --warn-unreachable
from typing import TypedDict

class A(TypedDict):
    ...

class B(TypedDict, total=False):
    x: int

a: A = {}
b: B = {}

if not a:
    reveal_type(a) # N: Revealed type is "TypedDict('__main__.A', {})"

if not b:
    reveal_type(b) # N: Revealed type is "TypedDict('__main__.B', {'x'?: builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

-- Create Type (Errors)

[case testCannotCreateTypedDictTypeWithTooFewArguments]
from typing import TypedDict
Point = TypedDict('Point')  # E: Too few arguments for TypedDict()
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithTooManyArguments]
from typing import TypedDict
Point = TypedDict('Point', {'x': int, 'y': int}, dict)  # E: Unexpected arguments to TypedDict()
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithInvalidName]
from typing import TypedDict
Point = TypedDict(dict, {'x': int, 'y': int})  # E: TypedDict() expects a string literal as the first argument
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithInvalidItems]
from typing import TypedDict
Point = TypedDict('Point', {'x'})  # E: TypedDict() expects a dictionary literal as the second argument
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithKwargs]
from typing import TypedDict
d = {'x': int, 'y': int}
Point = TypedDict('Point', {**d})  # E: Invalid TypedDict() field name
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithBytes]
from typing import TypedDict
Point = TypedDict(b'Point', {'x': int, 'y': int})  # E: TypedDict() expects a string literal as the first argument
# This technically works at runtime but doesn't make sense.
Point2 = TypedDict('Point2', {b'x': int})  # E: Invalid TypedDict() field name
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

-- NOTE: The following code works at runtime but is not yet supported by mypy.
--       Keyword arguments may potentially be supported in the future.
[case testCannotCreateTypedDictTypeWithNonpositionalArgs]
from typing import TypedDict
Point = TypedDict(typename='Point', fields={'x': int, 'y': int})  # E: Unexpected arguments to TypedDict()
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithInvalidItemName]
from typing import TypedDict
Point = TypedDict('Point', {int: int, int: int})  # E: Invalid TypedDict() field name
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithInvalidItemType]
from typing import TypedDict
Point = TypedDict('Point', {'x': 1, 'y': 1})  # E: Invalid type: try using Literal[1] instead?
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCannotCreateTypedDictTypeWithInvalidName2]
from typing import TypedDict
X = TypedDict('Y', {'x': int})  # E: First argument "Y" to TypedDict() does not match variable name "X"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


-- Overloading

[case testTypedDictOverloading]
from typing import overload, Iterable, TypedDict

A = TypedDict('A', {'x': int})

@overload
def f(x: Iterable[str]) -> str: ...
@overload
def f(x: int) -> int: ...
def f(x): pass

a: A
reveal_type(f(a))  # N: Revealed type is "builtins.str"
reveal_type(f(1))  # N: Revealed type is "builtins.int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverloading2]
from typing import overload, Iterable, TypedDict

A = TypedDict('A', {'x': int})

@overload
def f(x: Iterable[int]) -> None: ...
@overload
def f(x: int) -> None: ...
def f(x): pass

a: A
f(a)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[out]
main:12: error: Argument 1 to "f" has incompatible type "A"; expected "Iterable[int]"
main:12: note: Following member(s) of "A" have conflicts:
main:12: note:     Expected:
main:12: note:         def __iter__(self) -> Iterator[int]
main:12: note:     Got:
main:12: note:         def __iter__(self) -> Iterator[str]

[case testTypedDictOverloading3]
from typing import TypedDict, overload

A = TypedDict('A', {'x': int})

@overload
def f(x: str) -> None: ...
@overload
def f(x: int) -> None: ...
def f(x): pass

a: A
f(a)  # E: No overload variant of "f" matches argument type "A" \
      # N: Possible overload variants: \
      # N:     def f(x: str) -> None \
      # N:     def f(x: int) -> None
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverloading4]
from typing import TypedDict, overload

A = TypedDict('A', {'x': int})
B = TypedDict('B', {'x': str})

@overload
def f(x: A) -> int: ...
@overload
def f(x: int) -> str: ...
def f(x): pass

a: A
b: B
reveal_type(f(a)) # N: Revealed type is "builtins.int"
reveal_type(f(1)) # N: Revealed type is "builtins.str"
f(b) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverloading5]
from typing import TypedDict, overload

A = TypedDict('A', {'x': int})
B = TypedDict('B', {'y': str})
C = TypedDict('C', {'y': int})

@overload
def f(x: A) -> None: ...
@overload
def f(x: B) -> None: ...
def f(x): pass

a: A
b: B
c: C
f(a)
f(b)
f(c) # E: Argument 1 to "f" has incompatible type "C"; expected "A"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverloading6]
from typing import TypedDict, overload

A = TypedDict('A', {'x': int})
B = TypedDict('B', {'y': str})

@overload
def f(x: A) -> int: ...
@overload
def f(x: B) -> str: ...
def f(x): pass

a: A
b: B
reveal_type(f(a)) # N: Revealed type is "builtins.int"
reveal_type(f(b)) # N: Revealed type is "builtins.str"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


-- Special cases

[case testForwardReferenceInTypedDict]
from typing import TypedDict, Mapping
X = TypedDict('X', {'b': 'B', 'c': 'C'})
class B: pass
class C(B): pass
x: X
reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})"
m1: Mapping[str, object] = x
m2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type "X", variable has type "Mapping[str, B]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testForwardReferenceInClassTypedDict]
from typing import TypedDict, Mapping
class X(TypedDict):
    b: 'B'
    c: 'C'
class B: pass
class C(B): pass
x: X
reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'b': __main__.B, 'c': __main__.C})"
m1: Mapping[str, object] = x
m2: Mapping[str, B] = x # E: Incompatible types in assignment (expression has type "X", variable has type "Mapping[str, B]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testForwardReferenceToTypedDictInTypedDict]
from typing import TypedDict, Mapping
X = TypedDict('X', {'a': 'A'})
A = TypedDict('A', {'b': int})
x: X
reveal_type(x) # N: Revealed type is "TypedDict('__main__.X', {'a': TypedDict('__main__.A', {'b': builtins.int})})"
reveal_type(x['a']['b']) # N: Revealed type is "builtins.int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testSelfRecursiveTypedDictInheriting]
from typing import TypedDict

def test() -> None:
    class MovieBase(TypedDict):
        name: str
        year: int

    class Movie(MovieBase):
        director: 'Movie' # E: Cannot resolve name "Movie" (possible cyclic definition) \
                          # N: Recursive types are not allowed at function scope
    m: Movie
    reveal_type(m['director']['name']) # N: Revealed type is "Any"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testSubclassOfRecursiveTypedDict]
from typing import List, TypedDict

def test() -> None:
    class Command(TypedDict):
        subcommands: List['Command']  # E: Cannot resolve name "Command" (possible cyclic definition) \
                                      # N: Recursive types are not allowed at function scope

    class HelpCommand(Command):
        pass

    hc = HelpCommand(subcommands=[])
    reveal_type(hc)  # N: Revealed type is "TypedDict('__main__.HelpCommand@7', {'subcommands': builtins.list[Any]})"
[builtins fixtures/list.pyi]
[typing fixtures/typing-typeddict.pyi]
[out]

[case testTypedDictForwardAsUpperBound]
from typing import TypedDict, TypeVar, Generic
T = TypeVar('T', bound='M')
class G(Generic[T]):
    x: T

yb: G[int] # E: Type argument "int" of "G" must be a subtype of "M"
yg: G[M]
z: int = G[M]().x['x']  # type: ignore[used-before-def]

class M(TypedDict):
    x: int
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[out]

[case testTypedDictWithImportCycleForward]
import a
[file a.py]
from typing import TypedDict
from b import f

N = TypedDict('N', {'a': str})
[file b.py]
import a

def f(x: a.N) -> None:
    reveal_type(x)
    reveal_type(x['a'])
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[out]
tmp/b.py:4: note: Revealed type is "TypedDict('a.N', {'a': builtins.str})"
tmp/b.py:5: note: Revealed type is "builtins.str"

[case testTypedDictImportCycle]

import b
[file a.py]
class C:
    pass

from b import tp
x: tp
reveal_type(x['x'])  # N: Revealed type is "builtins.int"

reveal_type(tp)  # N: Revealed type is "def (*, x: builtins.int) -> TypedDict('b.tp', {'x': builtins.int})"
tp(x='no')  # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")

[file b.py]
from a import C
from typing import TypedDict

tp = TypedDict('tp', {'x': int})
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]
[out]

[case testTypedDictAsStarStarArg]
from typing import TypedDict

A = TypedDict('A', {'x': int, 'y': str})
class B: pass

def f1(x: int, y: str) -> None: ...
def f2(x: int, y: int) -> None: ...
def f3(x: B, y: str) -> None: ...
def f4(x: int) -> None: pass
def f5(x: int, y: str, z: int) -> None: pass
def f6(x: int, z: str) -> None: pass

a: A
f1(**a)
f2(**a) # E: Argument "y" to "f2" has incompatible type "str"; expected "int"
f3(**a) # E: Argument "x" to "f3" has incompatible type "int"; expected "B"
f4(**a) # E: Extra argument "y" from **args for "f4"
f5(**a) # E: Missing positional arguments "y", "z" in call to "f5"
f6(**a) # E: Extra argument "y" from **args for "f6"
f1(1, **a) # E: "f1" gets multiple values for keyword argument "x"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAsStarStarArgConstraints]
from typing import TypedDict, TypeVar, Union

T = TypeVar('T')
S = TypeVar('S')
def f1(x: T, y: S) -> Union[T, S]: ...

A = TypedDict('A', {'y': int, 'x': str})
a: A
reveal_type(f1(**a)) # N: Revealed type is "Union[builtins.str, builtins.int]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAsStarStarArgCalleeKwargs]
from typing import TypedDict

A = TypedDict('A', {'x': int, 'y': str})
B = TypedDict('B', {'x': str, 'y': str})

def f(**kwargs: str) -> None: ...
def g(x: int, **kwargs: str) -> None: ...

a: A
b: B
f(**a) # E: Argument 1 to "f" has incompatible type "**A"; expected "str"
f(**b)
g(**a)
g(**b) # E: Argument "x" to "g" has incompatible type "str"; expected "int"
g(1, **a) # E: "g" gets multiple values for keyword argument "x"
g(1, **b) # E: "g" gets multiple values for keyword argument "x" \
          # E: Argument "x" to "g" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAsStarStarTwice]
from typing import TypedDict

A = TypedDict('A', {'x': int, 'y': str})
B = TypedDict('B', {'z': bytes})
C = TypedDict('C', {'x': str, 'z': bytes})

def f1(x: int, y: str, z: bytes) -> None: ...
def f2(x: int, y: float, z: bytes) -> None: ...
def f3(x: int, y: str, z: float) -> None: ...

a: A
b: B
c: C
f1(**a, **b)
f1(**b, **a)
f2(**a, **b) # E: Argument "y" to "f2" has incompatible type "str"; expected "float"
f3(**a, **b) # E: Argument "z" to "f3" has incompatible type "bytes"; expected "float"
f3(**b, **a) # E: Argument "z" to "f3" has incompatible type "bytes"; expected "float"
f1(**a, **c) # E: "f1" gets multiple values for keyword argument "x" \
             # E: Argument "x" to "f1" has incompatible type "str"; expected "int"
f1(**c, **a) # E: "f1" gets multiple values for keyword argument "x" \
             # E: Argument "x" to "f1" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAsStarStarAndDictAsStarStar]
from typing import Any, Dict, TypedDict

TD = TypedDict('TD', {'x': int, 'y': str})

def f1(x: int, y: str, z: bytes) -> None: ...
def f2(x: int, y: str) -> None: ...

td: TD
d: Dict[Any, Any]

f1(**td, **d)
f1(**d, **td)
f2(**td, **d)
f2(**d, **td)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictNonMappingMethods]
from typing import List, TypedDict

A = TypedDict('A', {'x': int, 'y': List[int]})
a: A

reveal_type(a.copy()) # N: Revealed type is "TypedDict('__main__.A', {'x': builtins.int, 'y': builtins.list[builtins.int]})"
a.has_key('x') # E: "A" has no attribute "has_key"
# TODO: Better error message
a.clear() # E: "A" has no attribute "clear"

a.setdefault('invalid', 1) # E: TypedDict "A" has no key "invalid"
reveal_type(a.setdefault('x', 1)) # N: Revealed type is "builtins.int"
reveal_type(a.setdefault('y', [])) # N: Revealed type is "builtins.list[builtins.int]"
a.setdefault('y', '') # E: Argument 2 to "setdefault" of "TypedDict" has incompatible type "str"; expected "list[int]"
x = ''
a.setdefault(x, 1) # E: Expected TypedDict key to be string literal
alias = a.setdefault
alias(x, 1) # E: Argument 1 has incompatible type "str"; expected "Never"

a.update({})
a.update({'x': 1})
a.update({'x': ''}) # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
a.update({'x': 1, 'y': []})
a.update({'x': 1, 'y': [1]})
a.update({'z': 1}) # E: Unexpected TypedDict key "z"
a.update({'z': 1, 'zz': 1}) # E: Unexpected TypedDict keys ("z", "zz")
a.update({'z': 1, 'x': 1}) # E: Expected TypedDict key "x" but found keys ("z", "x")
d = {'x': 1}
a.update(d) # E: Argument 1 to "update" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'x'?: int, 'y'?: list[int]})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictPopMethod]
from typing import List, TypedDict

A = TypedDict('A', {'x': int, 'y': List[int]}, total=False)
B = TypedDict('B', {'x': int})
a: A
b: B

reveal_type(a.pop('x')) # N: Revealed type is "builtins.int"
reveal_type(a.pop('y', [])) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(a.pop('x', '')) # N: Revealed type is "Union[builtins.int, Literal['']?]"
reveal_type(a.pop('x', (1, 2))) # N: Revealed type is "Union[builtins.int, tuple[Literal[1]?, Literal[2]?]]"
a.pop('invalid', '') # E: TypedDict "A" has no key "invalid"
b.pop('x') # E: Key "x" of TypedDict "B" cannot be deleted
x = ''
b.pop(x) # E: Expected TypedDict key to be string literal
pop = b.pop
pop('x') # E: Argument 1 has incompatible type "str"; expected "Never"
pop('invalid') # E: Argument 1 has incompatible type "str"; expected "Never"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictDel]
from typing import List, TypedDict

A = TypedDict('A', {'x': int, 'y': List[int]}, total=False)
B = TypedDict('B', {'x': int})
a: A
b: B

del a['x']
del a['invalid'] # E: TypedDict "A" has no key "invalid"
del b['x'] # E: Key "x" of TypedDict "B" cannot be deleted
s = ''
del a[s] # E: Expected TypedDict key to be string literal
del b[s] # E: Expected TypedDict key to be string literal
alias = b.__delitem__
alias('x')
alias(s)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testPluginUnionsOfTypedDicts]
from typing import TypedDict, Union

class TDA(TypedDict):
    a: int
    b: str

class TDB(TypedDict):
    a: int
    b: int
    c: int

td: Union[TDA, TDB]

reveal_type(td.get('a'))  # N: Revealed type is "builtins.int"
reveal_type(td.get('b'))  # N: Revealed type is "Union[builtins.str, builtins.int]"
reveal_type(td.get('c'))  # N: Revealed type is "builtins.object"

reveal_type(td['a'])  # N: Revealed type is "builtins.int"
reveal_type(td['b'])  # N: Revealed type is "Union[builtins.str, builtins.int]"
reveal_type(td['c'])  # N: Revealed type is "Union[Any, builtins.int]" \
                      # E: TypedDict "TDA" has no key "c"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testPluginUnionsOfTypedDictsNonTotal]
from typing import TypedDict, Union

class TDA(TypedDict, total=False):
    a: int
    b: str

class TDB(TypedDict, total=False):
    a: int
    b: int
    c: int

td: Union[TDA, TDB]

reveal_type(td.pop('a'))  # N: Revealed type is "builtins.int"
reveal_type(td.pop('b'))  # N: Revealed type is "Union[builtins.str, builtins.int]"
reveal_type(td.pop('c'))  # N: Revealed type is "Union[Any, builtins.int]" \
                          # E: TypedDict "TDA" has no key "c"

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithTypingExtensions]
from typing_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]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateTypedDictWithTypingProper]
from typing 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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOptionalUpdate]
from typing import TypedDict, Union

class A(TypedDict):
    x: int

d: A
d.update({'x': 1})
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDict]
# mypy: strict-equality
from typing import TypedDict, Dict

class Config(TypedDict):
    a: str
    b: str

x: Dict[str, str]
y: Config

x == y
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictNonOverlapping]
# mypy: strict-equality
from typing import TypedDict, Dict

class Config(TypedDict):
    a: str
    b: int

x: Dict[str, str]
y: Config

x == y  # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "Config")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictNonTotal]
# mypy: strict-equality
from typing import TypedDict, Dict

class Config(TypedDict, total=False):
    a: str
    b: int

x: Dict[str, str]
y: Config

x == y
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictNonTotalNonOverlapping]
# mypy: strict-equality
from typing import TypedDict, Dict

class Config(TypedDict, total=False):
    a: int
    b: int

x: Dict[str, str]
y: Config

x == y  # E: Non-overlapping equality check (left operand type: "dict[str, str]", right operand type: "Config")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictEmpty]
# mypy: strict-equality
from typing import TypedDict

class Config(TypedDict):
    a: str
    b: str

x: Config
x == {}  # E: Non-overlapping equality check (left operand type: "Config", right operand type: "dict[Never, Never]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictNonTotalEmpty]
# mypy: strict-equality
from typing import TypedDict

class Config(TypedDict, total=False):
    a: str
    b: str

x: Config
x == {}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictNonStrKey]
# mypy: strict-equality
from typing import TypedDict, Dict, Union

class Config(TypedDict):
    a: str
    b: str

x: Config
y: Dict[Union[str, int], str]
x == y
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictOverload]
from typing import overload, TypedDict, Dict

class Map(TypedDict):
    x: int
    y: str

@overload
def func(x: Map) -> int: ...
@overload
def func(x: Dict[str, str]) -> str: ...
def func(x):
    pass
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictOverloadBad]
from typing import overload, TypedDict, Dict

class Map(TypedDict, total=False):
    x: int
    y: str

@overload
def func(x: Map) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
@overload
def func(x: Dict[str, str]) -> str: ...
def func(x):
    pass
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictOverloadMappingBad]
from typing import overload, TypedDict, Mapping

class Map(TypedDict, total=False):
    x: int
    y: str

@overload
def func(x: Map) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types
@overload
def func(x: Mapping[str, str]) -> str: ...
def func(x):
    pass
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictOverlapWithDictOverloadNonStrKey]
from typing import overload, TypedDict, Dict

class Map(TypedDict):
    x: str
    y: str

@overload
def func(x: Map) -> int: ...
@overload
def func(x: Dict[int, str]) -> str: ...
def func(x):
    pass
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictIsInstance]
from typing import TypedDict, Union

class User(TypedDict):
    id: int
    name: str

u: Union[str, User]
u2: User

if isinstance(u, dict):
    reveal_type(u)  # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
else:
    reveal_type(u)  # N: Revealed type is "builtins.str"

assert isinstance(u2, dict)
reveal_type(u2)  # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictIsInstanceABCs]
from typing import TypedDict, Union, Mapping, Iterable

class User(TypedDict):
    id: int
    name: str

u: Union[int, User]
u2: User

if isinstance(u, Iterable):
    reveal_type(u)  # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
else:
    reveal_type(u)  # N: Revealed type is "builtins.int"

assert isinstance(u2, Mapping)
reveal_type(u2)  # N: Revealed type is "TypedDict('__main__.User', {'id': builtins.int, 'name': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testTypedDictLiteralTypeKeyInCreation]
from typing import TypedDict, Final, Literal

class Value(TypedDict):
    num: int

num: Final = 'num'
v: Value = {num: 5}
v = {num: ''}  # E: Incompatible types (expression has type "str", TypedDict item "num" has type "int")

bad: Final = 2
v = {bad: 3}  # E: Expected TypedDict key to be string literal
union: Literal['num', 'foo']
v = {union: 2} # E: Expected TypedDict key to be string literal
num2: Literal['num']
v = {num2: 2}
bad2: Literal['bad']
v = {bad2: 2}  # E: Missing key "num" for TypedDict "Value" \
               # E: Extra key "bad" for TypedDict "Value"

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testOperatorContainsNarrowsTypedDicts_unionWithList]
from __future__ import annotations
from typing import assert_type, final, TypedDict, Union

@final
class D(TypedDict):
    foo: int


d_or_list: D | list[str]

if 'foo' in d_or_list:
    assert_type(d_or_list, Union[D, list[str]])
elif 'bar' in d_or_list:
    assert_type(d_or_list, list[str])
else:
    assert_type(d_or_list, list[str])

[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testOperatorContainsNarrowsTypedDicts_total]
from __future__ import annotations
from typing import assert_type, final, Literal, TypedDict, TypeVar, Union

@final
class D1(TypedDict):
    foo: int


@final
class D2(TypedDict):
    bar: int


d: D1 | D2

if 'foo' in d:
    assert_type(d, D1)
else:
    assert_type(d, D2)

foo_or_bar: Literal['foo', 'bar']
if foo_or_bar in d:
    assert_type(d, Union[D1, D2])
else:
    assert_type(d, Union[D1, D2])

foo_or_invalid: Literal['foo', 'invalid']
if foo_or_invalid in d:
    assert_type(d, D1)
    # won't narrow 'foo_or_invalid'
    assert_type(foo_or_invalid, Literal['foo', 'invalid'])
else:
    assert_type(d, Union[D1, D2])
    # won't narrow 'foo_or_invalid'
    assert_type(foo_or_invalid, Literal['foo', 'invalid'])

TD = TypeVar('TD', D1, D2)

def f(arg: TD) -> None:
    value: int
    if 'foo' in arg:
        assert_type(arg['foo'], int)
    else:
        assert_type(arg['bar'], int)


[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testOperatorContainsNarrowsTypedDicts_final]
# flags: --warn-unreachable
from __future__ import annotations
from typing import assert_type, final, TypedDict, Union

@final
class DFinal(TypedDict):
    foo: int


class DNotFinal(TypedDict):
    bar: int


d_not_final: DNotFinal

if 'bar' in d_not_final:
    assert_type(d_not_final, DNotFinal)
else:
    spam = 'ham'  # E: Statement is unreachable

if 'spam' in d_not_final:
    assert_type(d_not_final, DNotFinal)
else:
    assert_type(d_not_final, DNotFinal)

d_final: DFinal

if 'spam' in d_final:
    spam = 'ham'  # E: Statement is unreachable
else:
    assert_type(d_final, DFinal)

d_union: DFinal | DNotFinal

if 'foo' in d_union:
    assert_type(d_union, Union[DFinal, DNotFinal])
else:
    assert_type(d_union, DNotFinal)

[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testOperatorContainsNarrowsTypedDicts_partialThroughTotalFalse]
from __future__ import annotations
from typing import assert_type, final, Literal, TypedDict, Union

@final
class DTotal(TypedDict):
    required_key: int


@final
class DNotTotal(TypedDict, total=False):
    optional_key: int


d: DTotal | DNotTotal

if 'required_key' in d:
    assert_type(d, DTotal)
else:
    assert_type(d, DNotTotal)

if 'optional_key' in d:
    assert_type(d, DNotTotal)
else:
    assert_type(d, Union[DTotal, DNotTotal])

key: Literal['optional_key', 'required_key']
if key in d:
    assert_type(d, Union[DTotal, DNotTotal])
else:
    assert_type(d, Union[DTotal, DNotTotal])

[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testOperatorContainsNarrowsTypedDicts_partialThroughNotRequired]
from __future__ import annotations
from typing import assert_type, final, TypedDict, Union
from typing_extensions import Required, NotRequired

@final
class D1(TypedDict):
    required_key: Required[int]
    optional_key: NotRequired[int]


@final
class D2(TypedDict):
    abc: int
    xyz: int


d: D1 | D2

if 'required_key' in d:
    assert_type(d, D1)
else:
    assert_type(d, D2)

if 'optional_key' in d:
    assert_type(d, D1)
else:
    assert_type(d, Union[D1, D2])

[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testCannotSubclassFinalTypedDict]
from typing import TypedDict, final

@final
class DummyTypedDict(TypedDict):
    int_val: int
    float_val: float
    str_val: str

class SubType(DummyTypedDict): # E: Cannot inherit from final class "DummyTypedDict"
    pass

[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testCannotSubclassFinalTypedDictWithForwardDeclarations]
from typing import TypedDict, final

@final
class DummyTypedDict(TypedDict):
    forward_declared: "ForwardDeclared"

class SubType(DummyTypedDict): # E: Cannot inherit from final class "DummyTypedDict"
    pass

class ForwardDeclared: pass

[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testTypedDictTypeNarrowingWithFinalKey]
from typing import Final, Optional, TypedDict

KEY_NAME: Final = "bar"
class Foo(TypedDict):
    bar: Optional[str]

foo = Foo(bar="hello")
if foo["bar"] is not None:
    reveal_type(foo["bar"])     # N: Revealed type is "builtins.str"
    reveal_type(foo[KEY_NAME])  # N: Revealed type is "builtins.str"
if foo[KEY_NAME] is not None:
    reveal_type(foo["bar"])     # N: Revealed type is "builtins.str"
    reveal_type(foo[KEY_NAME])  # N: Revealed type is "builtins.str"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictDoubleForwardClass]
from typing import Any, List, TypedDict

class Foo(TypedDict):
    bar: Bar
    baz: Bar

Bar = List[Any]

foo: Foo
reveal_type(foo['bar'])  # N: Revealed type is "builtins.list[Any]"
reveal_type(foo['baz'])  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictDoubleForwardFunc]
from typing import Any, List, TypedDict

Foo = TypedDict('Foo', {'bar': 'Bar', 'baz': 'Bar'})

Bar = List[Any]

foo: Foo
reveal_type(foo['bar'])   # N: Revealed type is "builtins.list[Any]"
reveal_type(foo['baz'])  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictDoubleForwardMixed]
from typing import Any, List, TypedDict

Bar = List[Any]

class Foo(TypedDict):
    foo: Toto
    bar: Bar
    baz: Bar

Toto = int

foo: Foo
reveal_type(foo['foo'])  # N: Revealed type is "builtins.int"
reveal_type(foo['bar'])  # N: Revealed type is "builtins.list[Any]"
reveal_type(foo['baz'])  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testAssignTypedDictAsAttribute]
from typing import TypedDict

class A:
    def __init__(self) -> None:
        self.b = TypedDict('b', {'x': int, 'y': str})  # E: TypedDict type as attribute is not supported

reveal_type(A().b)  # N: Revealed type is "Any"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAsUpperBoundAndIndexedAssign]
from typing import TypeVar, Generic, TypedDict


class BaseDict(TypedDict, total=False):
    foo: int


_DICT_T = TypeVar('_DICT_T', bound=BaseDict)


class SomeGeneric(Generic[_DICT_T]):
    def __init__(self, data: _DICT_T) -> None:
        self._data: _DICT_T = data

    def set_state(self) -> None:
        self._data['foo'] = 1
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictCreatedWithEmptyDict]
from typing import TypedDict

class TD(TypedDict, total=False):
    foo: int
    bar: int

d: TD = dict()
d2: TD = dict(foo=1)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictBytesKey]
from typing import TypedDict

class TD(TypedDict):
    foo: int

d: TD = {b'foo': 2} # E: Expected TypedDict key to be string literal
d[b'foo'] = 3 # E: TypedDict key must be a string literal; expected one of ("foo") \
    # E: Argument 1 to "__setitem__" has incompatible type "bytes"; expected "str"
d[b'foo'] # E: TypedDict key must be a string literal; expected one of ("foo")
d[3] # E: TypedDict key must be a string literal; expected one of ("foo")
d[True] # E: TypedDict key must be a string literal; expected one of ("foo")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUppercaseKey]
from typing import TypedDict

Foo = TypedDict('Foo', {'camelCaseKey': str})
value: Foo = {}  # E: Missing key "camelCaseKey" for TypedDict "Foo"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithDeferredFieldTypeEval]
from typing import Generic, TypeVar, TypedDict, NotRequired

class Foo(TypedDict):
    y: NotRequired[int]
    x: Outer[Inner[ForceDeferredEval]]

var: Foo
reveal_type(var)  # N: Revealed type is "TypedDict('__main__.Foo', {'y'?: builtins.int, 'x': __main__.Outer[__main__.Inner[__main__.ForceDeferredEval]]})"

T1 = TypeVar("T1")
class Outer(Generic[T1]): pass

T2 = TypeVar("T2", bound="ForceDeferredEval")
class Inner(Generic[T2]): pass

class ForceDeferredEval: pass
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictRequiredUnimportedAny]
# flags: --disallow-any-unimported
from typing import NotRequired, TypedDict, ReadOnly
from nonexistent import Foo  # type: ignore[import-not-found]
class Bar(TypedDict):
    foo: NotRequired[Foo]  # E: Type of variable becomes "Any" due to an unfollowed import
    bar: ReadOnly[Foo]  # E: Type of variable becomes "Any" due to an unfollowed import
    baz: NotRequired[ReadOnly[Foo]]  # E: Type of variable becomes "Any" due to an unfollowed import
[typing fixtures/typing-typeddict.pyi]

-- Required[]

[case testDoesRecognizeRequiredInTypedDictWithClass]
from typing import TypedDict
from typing import Required
class Movie(TypedDict, total=False):
    title: Required[str]
    year: int
m = Movie(title='The Matrix')
m = Movie()  # E: Missing key "title" for TypedDict "Movie"
[typing fixtures/typing-typeddict.pyi]

[case testDoesRecognizeRequiredInTypedDictWithAssignment]
from typing import TypedDict
from typing import Required
Movie = TypedDict('Movie', {
    'title': Required[str],
    'year': int,
}, total=False)
m = Movie(title='The Matrix')
m = Movie()  # E: Missing key "title" for TypedDict "Movie"
[typing fixtures/typing-typeddict.pyi]

[case testDoesDisallowRequiredOutsideOfTypedDict]
from typing import Required
x: Required[int] = 42  # E: Required[] can be only used in a TypedDict definition
[typing fixtures/typing-typeddict.pyi]

[case testDoesOnlyAllowRequiredInsideTypedDictAtTopLevel]
from typing import TypedDict
from typing import Union
from typing import Required
Movie = TypedDict('Movie', {
    'title': Union[
        Required[str],  # E: Required[] can be only used in a TypedDict definition
        bytes
    ],
    'year': int,
}, total=False)
[typing fixtures/typing-typeddict.pyi]

[case testDoesDisallowRequiredInsideRequired]
from typing import TypedDict
from typing import Union
from typing import Required
Movie = TypedDict('Movie', {
    'title': Required[Union[
        Required[str],  # E: Required[] can be only used in a TypedDict definition
        bytes
    ]],
    'year': int,
}, total=False)
[typing fixtures/typing-typeddict.pyi]

[case testRequiredOnlyAllowsOneItem]
from typing import TypedDict
from typing import Required
class Movie(TypedDict, total=False):
    title: Required[str, bytes]  # E: Required[] must have exactly one type argument
    year: int
[typing fixtures/typing-typeddict.pyi]

[case testRequiredExplicitAny]
# flags: --disallow-any-explicit
from typing import TypedDict
from typing import Required
Foo = TypedDict("Foo", {"a.x": Required[int]})
[typing fixtures/typing-typeddict.pyi]

-- NotRequired[]

[case testDoesRecognizeNotRequiredInTypedDictWithClass]
from typing import TypedDict
from typing import NotRequired
class Movie(TypedDict):
    title: str
    year: NotRequired[int]
m = Movie(title='The Matrix')
m = Movie()  # E: Missing key "title" for TypedDict "Movie"
[typing fixtures/typing-typeddict.pyi]

[case testDoesRecognizeNotRequiredInTypedDictWithAssignment]
from typing import TypedDict
from typing import NotRequired
Movie = TypedDict('Movie', {
    'title': str,
    'year': NotRequired[int],
})
m = Movie(title='The Matrix')
m = Movie()  # E: Missing key "title" for TypedDict "Movie"
[typing fixtures/typing-typeddict.pyi]

[case testDoesDisallowNotRequiredOutsideOfTypedDict]
from typing import NotRequired
x: NotRequired[int] = 42  # E: NotRequired[] can be only used in a TypedDict definition
[typing fixtures/typing-typeddict.pyi]

[case testDoesOnlyAllowNotRequiredInsideTypedDictAtTopLevel]
from typing import TypedDict
from typing import Union
from typing import NotRequired
Movie = TypedDict('Movie', {
    'title': Union[
        NotRequired[str],  # E: NotRequired[] can be only used in a TypedDict definition
        bytes
    ],
    'year': int,
})
[typing fixtures/typing-typeddict.pyi]

[case testDoesDisallowNotRequiredInsideNotRequired]
from typing import TypedDict
from typing import Union
from typing import NotRequired
Movie = TypedDict('Movie', {
    'title': NotRequired[Union[
        NotRequired[str],  # E: NotRequired[] can be only used in a TypedDict definition
        bytes
    ]],
    'year': int,
})
[typing fixtures/typing-typeddict.pyi]

[case testNotRequiredOnlyAllowsOneItem]
from typing import TypedDict
from typing import NotRequired
class Movie(TypedDict):
    title: NotRequired[str, bytes]  # E: NotRequired[] must have exactly one type argument
    year: int
[typing fixtures/typing-typeddict.pyi]

[case testNotRequiredExplicitAny]
# flags: --disallow-any-explicit
from typing import TypedDict
from typing import NotRequired
Foo = TypedDict("Foo", {"a.x": NotRequired[int]})
[typing fixtures/typing-typeddict.pyi]

-- Union dunders

[case testTypedDictUnionGetItem]
from typing import TypedDict, Union

class Foo1(TypedDict):
    z: str
    a: int
class Foo2(TypedDict):
    z: str
    b: int

def func(foo: Union[Foo1, Foo2]) -> str:
    reveal_type(foo["z"])  # N: Revealed type is "builtins.str"
    # ok, but type is incorrect:
    reveal_type(foo.__getitem__("z"))  # N: Revealed type is "builtins.object"

    reveal_type(foo["a"])  # N: Revealed type is "Union[builtins.int, Any]" \
                           # E: TypedDict "Foo2" has no key "a"
    reveal_type(foo["b"])  # N: Revealed type is "Union[Any, builtins.int]" \
                           # E: TypedDict "Foo1" has no key "b"
    reveal_type(foo["missing"])  # N: Revealed type is "Any" \
                                 # E: TypedDict "Foo1" has no key "missing" \
                                 # E: TypedDict "Foo2" has no key "missing"
    reveal_type(foo[1])  # N: Revealed type is "Any" \
                         # E: TypedDict key must be a string literal; expected one of ("z", "a") \
                         # E: TypedDict key must be a string literal; expected one of ("z", "b")

    return foo["z"]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictUnionSetItem]
from typing import TypedDict, Union

class Foo1(TypedDict):
    z: str
    a: int
class Foo2(TypedDict):
    z: str
    b: int

def func(foo: Union[Foo1, Foo2]):
    foo["z"] = "a"  # ok
    foo.__setitem__("z", "a")  # ok

    foo["z"] = 1  # E: Value of "z" has incompatible type "int"; expected "str"

    foo["a"] = 1  # E: TypedDict "Foo2" has no key "a"
    foo["b"] = 2  # E: TypedDict "Foo1" has no key "b"

    foo["missing"] = 1  # E: TypedDict "Foo1" has no key "missing" \
                        # E: TypedDict "Foo2" has no key "missing"
    foo[1] = "m"  # E: TypedDict key must be a string literal; expected one of ("z", "a") \
                  # E: TypedDict key must be a string literal; expected one of ("z", "b") \
                  # E: Argument 1 to "__setitem__" has incompatible type "int"; expected "str"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictUnionDelItem]
from typing import TypedDict, Union

class Foo1(TypedDict):
    z: str
    a: int
class Foo2(TypedDict):
    z: str
    b: int

def func(foo: Union[Foo1, Foo2]):
    del foo["z"]  # E: Key "z" of TypedDict "Foo1" cannot be deleted \
                  # E: Key "z" of TypedDict "Foo2" cannot be deleted
    foo.__delitem__("z")  # E: Key "z" of TypedDict "Foo1" cannot be deleted \
                          # E: Key "z" of TypedDict "Foo2" cannot be deleted

    del foo["a"]  # E: Key "a" of TypedDict "Foo1" cannot be deleted \
                  # E: TypedDict "Foo2" has no key "a"
    del foo["b"]  # E: TypedDict "Foo1" has no key "b" \
                  # E: Key "b" of TypedDict "Foo2" cannot be deleted

    del foo["missing"]  # E: TypedDict "Foo1" has no key "missing" \
                        # E: TypedDict "Foo2" has no key "missing"
    del foo[1]  # E: Argument 1 to "__delitem__" has incompatible type "int"; expected "str" \
                # E: Expected TypedDict key to be string literal

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictTypeVarUnionSetItem]
from typing import TypedDict, Union, TypeVar

F1 = TypeVar('F1', bound='Foo1')
F2 = TypeVar('F2', bound='Foo2')

class Foo1(TypedDict):
    z: str
    a: int
class Foo2(TypedDict):
    z: str
    b: int

def func(foo: Union[F1, F2]):
    foo["z"] = "a"  # ok
    foo["z"] = 1  # E: Value of "z" has incompatible type "int"; expected "str"

    foo["a"] = 1  # E: TypedDict "Foo2" has no key "a"
    foo["b"] = 2  # E: TypedDict "Foo1" has no key "b"

    foo["missing"] = 1  # E: TypedDict "Foo1" has no key "missing" \
                        # E: TypedDict "Foo2" has no key "missing"
    foo[1] = "m"  # E: TypedDict key must be a string literal; expected one of ("z", "a") \
                  # E: TypedDict key must be a string literal; expected one of ("z", "b") \
                  # E: Argument 1 to "__setitem__" has incompatible type "int"; expected "str"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictCreation]
from typing import TypedDict, Generic, TypeVar

T = TypeVar("T")

class TD(TypedDict, Generic[T]):
    key: int
    value: T

tds: TD[str]
reveal_type(tds)  # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})"

tdi = TD(key=0, value=0)
reveal_type(tdi)  # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})"
TD[str](key=0, value=0)  # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
TD[str]({"key": 0, "value": 0})  # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictInference]
from typing import TypedDict, Generic, TypeVar, List

T = TypeVar("T")

class TD(TypedDict, Generic[T]):
    key: int
    value: T

def foo(x: TD[T]) -> List[T]: ...

reveal_type(foo(TD(key=1, value=2)))  # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(foo({"key": 1, "value": 2}))  # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(foo(dict(key=1, value=2)))  # N: Revealed type is "builtins.list[builtins.int]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictExtending]
from typing import TypedDict, Generic, TypeVar, List

T = TypeVar("T")
class TD(TypedDict, Generic[T]):
    key: int
    value: T

S = TypeVar("S")
class STD(TD[List[S]]):
    other: S

std: STD[str]
reveal_type(std)  # N: Revealed type is "TypedDict('__main__.STD', {'key': builtins.int, 'value': builtins.list[builtins.str], 'other': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictExtendingErrors]
from typing import TypedDict, Generic, TypeVar

T = TypeVar("T")
class Base(TypedDict, Generic[T]):
    x: T
class Sub(Base[{}]):  # E: Invalid TypedDict type argument \
                      # E: Type expected within [...] \
                      # E: Invalid base class "Base"
    y: int
s: Sub
reveal_type(s)  # N: Revealed type is "TypedDict('__main__.Sub', {'y': builtins.int})"

class Sub2(Base[int, str]):  # E: Invalid number of type arguments for "Base" \
                             # E: "Base" expects 1 type argument, but 2 given
    y: int
s2: Sub2
reveal_type(s2)  # N: Revealed type is "TypedDict('__main__.Sub2', {'x': Any, 'y': builtins.int})"

class Sub3(Base):  # OK
    y: int
s3: Sub3
reveal_type(s3)  # N: Revealed type is "TypedDict('__main__.Sub3', {'x': Any, 'y': builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAttributeOnClassObject]
from typing import TypedDict

class TD(TypedDict):
    x: str
    y: str

reveal_type(TD.__iter__)  # N: Revealed type is "def (typing._TypedDict) -> typing.Iterator[builtins.str]"
reveal_type(TD.__annotations__)  # N: Revealed type is "typing.Mapping[builtins.str, builtins.object]"
reveal_type(TD.values)  # N: Revealed type is "def (self: typing.Mapping[builtins.str, builtins.object]) -> typing.Iterable[builtins.object]"
[builtins fixtures/dict-full.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictAlias]
# flags: --disallow-any-generics
from typing import TypedDict, Generic, TypeVar, List

T = TypeVar("T")
class TD(TypedDict, Generic[T]):
    key: int
    value: T

Alias = TD[List[T]]

ad: Alias[str]
reveal_type(ad)  # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.list[builtins.str]})"
Alias[str](key=0, value=0)  # E: Incompatible types (expression has type "int", TypedDict item "value" has type "list[str]")

# Generic aliases are *always* filled with Any, so this is different from TD(...) call.
Alias(key=0, value=0)  # E: Missing type parameters for generic type "Alias" \
                       # E: Incompatible types (expression has type "int", TypedDict item "value" has type "list[Any]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictMultipleGenerics]
# See https://github.com/python/mypy/issues/13755
from typing import Generic, TypeVar, TypedDict

T = TypeVar("T")
Foo = TypedDict("Foo", {"bar": T})
class Stack(Generic[T]): pass

a = Foo[str]
b = Foo[int]
reveal_type(a)  # N: Revealed type is "def (*, bar: builtins.str) -> TypedDict('__main__.Foo', {'bar': builtins.str})"
reveal_type(b)  # N: Revealed type is "def (*, bar: builtins.int) -> TypedDict('__main__.Foo', {'bar': builtins.int})"

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testGenericTypedDictCallSyntax]
from typing import TypedDict, TypeVar

T = TypeVar("T")
TD = TypedDict("TD", {"key": int, "value": T})
reveal_type(TD)  # N: Revealed type is "def [T] (*, key: builtins.int, value: T`1) -> TypedDict('__main__.TD', {'key': builtins.int, 'value': T`1})"

tds: TD[str]
reveal_type(tds)  # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.str})"

tdi = TD(key=0, value=0)
reveal_type(tdi)  # N: Revealed type is "TypedDict('__main__.TD', {'key': builtins.int, 'value': builtins.int})"
TD[str](key=0, value=0)  # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
TD[str]({"key": 0, "value": 0})  # E: Incompatible types (expression has type "int", TypedDict item "value" has type "str")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictSelfItemNotAllowed]
from typing import Self, TypedDict, Optional

class TD(TypedDict):
    val: int
    next: Optional[Self]  # E: Self type cannot be used in TypedDict item type
TDC = TypedDict("TDC", {"val": int, "next": Optional[Self]})  # E: Self type cannot be used in TypedDict item type

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testUnionOfEquivalentTypedDictsInferred]
from typing import TypedDict, Dict

D = TypedDict("D", {"foo": int}, total=False)

def f(d: Dict[str, D]) -> None:
    args = d["a"]
    args.update(d.get("b", {}))  # OK
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testUnionOfEquivalentTypedDictsDeclared]
from typing import TypedDict, Union

class A(TypedDict, total=False):
    name: str
class B(TypedDict, total=False):
    name: str

def foo(data: Union[A, B]) -> None: ...
foo({"name": "Robert"})  # OK
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testUnionOfEquivalentTypedDictsEmpty]
from typing import TypedDict, Union

class Foo(TypedDict, total=False):
    foo: str
class Bar(TypedDict, total=False):
    bar: str

def foo(body: Union[Foo, Bar] = {}) -> None:  # OK
    ...
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testUnionOfEquivalentTypedDictsDistinct]
from typing import TypedDict, Union, Literal

class A(TypedDict):
    type: Literal['a']
    value: bool
class B(TypedDict):
    type: Literal['b']
    value: str

Response = Union[A, B]
def method(message: Response) -> None: ...

method({'type': 'a', 'value': True})  # OK
method({'type': 'b', 'value': 'abc'})  # OK
method({'type': 'a', 'value': 'abc'})  # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \
                                       # E: Argument 1 to "method" has incompatible type "dict[str, str]"; expected "Union[A, B]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testUnionOfEquivalentTypedDictsNested]
from typing import TypedDict, Union

class A(TypedDict, total=False):
    foo: C
class B(TypedDict, total=False):
    foo: D
class C(TypedDict, total=False):
    c: str
class D(TypedDict, total=False):
    d: str

def foo(data: Union[A, B]) -> None: ...
foo({"foo": {"c": "foo"}})  # OK
foo({"foo": {"e": "foo"}})  # E: Type of TypedDict is ambiguous, none of ("A", "B") matches cleanly \
                            # E: Argument 1 to "foo" has incompatible type "dict[str, dict[str, str]]"; expected "Union[A, B]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictMissingEmptyKey]
from typing import TypedDict

class A(TypedDict):
    my_attr_1: str
    my_attr_2: int

d: A
d['']  # E: TypedDict "A" has no key ""
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictFlexibleUpdate]
from typing import TypedDict

A = TypedDict("A", {"foo": int, "bar": int})
B = TypedDict("B", {"foo": int})

a = A({"foo": 1, "bar": 2})
b = B({"foo": 2})
a.update({"foo": 2})
a.update(b)
a.update(a)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictStrictUpdate]
# flags: --extra-checks
from typing import TypedDict

A = TypedDict("A", {"foo": int, "bar": int})
B = TypedDict("B", {"foo": int})

a = A({"foo": 1, "bar": 2})
b = B({"foo": 2})
a.update({"foo": 2})  # OK
a.update(b)  # E: Argument 1 to "update" of "TypedDict" has incompatible type "B"; expected "TypedDict({'foo': int, 'bar'?: int})"
a.update(a)  # OK
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictFlexibleUpdateUnion]
from typing import TypedDict, Union

A = TypedDict("A", {"foo": int, "bar": int})
B = TypedDict("B", {"foo": int})
C = TypedDict("C", {"bar": int})

a = A({"foo": 1, "bar": 2})
u: Union[B, C]
a.update(u)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictFlexibleUpdateUnionExtra]
from typing import TypedDict, Union

A = TypedDict("A", {"foo": int, "bar": int})
B = TypedDict("B", {"foo": int, "extra": int})
C = TypedDict("C", {"bar": int, "extra": int})

a = A({"foo": 1, "bar": 2})
u: Union[B, C]
a.update(u)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictFlexibleUpdateUnionStrict]
# flags: --extra-checks
from typing import TypedDict, Union, NotRequired

A = TypedDict("A", {"foo": int, "bar": int})
A1 = TypedDict("A1", {"foo": int, "bar": NotRequired[int]})
A2 = TypedDict("A2", {"foo": NotRequired[int], "bar": int})
B = TypedDict("B", {"foo": int})
C = TypedDict("C", {"bar": int})

a = A({"foo": 1, "bar": 2})
u: Union[B, C]
a.update(u)  # E: Argument 1 to "update" of "TypedDict" has incompatible type "Union[B, C]"; expected "Union[TypedDict({'foo': int, 'bar'?: int}), TypedDict({'foo'?: int, 'bar': int})]"
u2: Union[A1, A2]
a.update(u2)  # OK
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackSame]
# flags: --extra-checks
from typing import TypedDict

class Foo(TypedDict):
    a: int
    b: int

foo1: Foo = {"a": 1, "b": 1}
foo2: Foo = {**foo1, "b": 2}
foo3 = Foo(**foo1, b=2)
foo4 = Foo({**foo1, "b": 2})
foo5 = Foo(dict(**foo1, b=2))
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackCompatible]
# flags: --extra-checks
from typing import TypedDict

class Foo(TypedDict):
    a: int

class Bar(TypedDict):
    a: int
    b: int

foo: Foo = {"a": 1}
bar: Bar = {**foo, "b": 2}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackIncompatible]
from typing import TypedDict

class Foo(TypedDict):
    a: int
    b: str

class Bar(TypedDict):
    a: int
    b: int

foo: Foo = {"a": 1, "b": "a"}
bar1: Bar = {**foo, "b": 2}  # Incompatible item is overridden
bar2: Bar = {**foo, "a": 2}  # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackNotRequiredKeyIncompatible]
from typing import TypedDict, NotRequired

class Foo(TypedDict):
    a: NotRequired[str]

class Bar(TypedDict):
    a: NotRequired[int]

foo: Foo = {}
bar: Bar = {**foo}  # E: Incompatible types (expression has type "str", TypedDict item "a" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictUnpackMissingOrExtraKey]
from typing import TypedDict

class Foo(TypedDict):
    a: int

class Bar(TypedDict):
    a: int
    b: int

foo1: Foo = {"a": 1}
bar1: Bar = {"a": 1, "b": 1}
foo2: Foo = {**bar1}  # E: Extra key "b" for TypedDict "Foo"
bar2: Bar = {**foo1}  # E: Missing key "b" for TypedDict "Bar"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackNotRequiredKeyExtra]
from typing import TypedDict, NotRequired

class Foo(TypedDict):
    a: int

class Bar(TypedDict):
    a: int
    b: NotRequired[int]

foo1: Foo = {"a": 1}
bar1: Bar = {"a": 1}
foo2: Foo = {**bar1}  # E: Extra key "b" for TypedDict "Foo"
bar2: Bar = {**foo1}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackRequiredKeyMissing]
from typing import TypedDict, NotRequired

class Foo(TypedDict):
    a: NotRequired[int]

class Bar(TypedDict):
    a: int

foo: Foo = {"a": 1}
bar: Bar = {**foo}  # E: Missing key "a" for TypedDict "Bar"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackMultiple]
# flags: --extra-checks
from typing import TypedDict

class Foo(TypedDict):
    a: int

class Bar(TypedDict):
    b: int

class Baz(TypedDict):
    a: int
    b: int
    c: int

foo: Foo = {"a": 1}
bar: Bar = {"b": 1}
baz: Baz = {**foo, **bar, "c": 1}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackNested]
from typing import TypedDict

class Foo(TypedDict):
    a: int
    b: int

class Bar(TypedDict):
    c: Foo
    d: int

foo: Foo = {"a": 1, "b": 1}
bar: Bar = {"c": foo, "d": 1}
bar2: Bar = {**bar, "c": {**bar["c"], "b": 2}, "d": 2}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackNestedError]
from typing import TypedDict

class Foo(TypedDict):
    a: int
    b: int

class Bar(TypedDict):
    c: Foo
    d: int

foo: Foo = {"a": 1, "b": 1}
bar: Bar = {"c": foo, "d": 1}
bar2: Bar = {**bar, "c": {**bar["c"], "b": "wrong"}, "d": 2}  # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackOverrideRequired]
from typing import TypedDict

Details = TypedDict('Details', {'first_name': str, 'last_name': str})
DetailsSubset = TypedDict('DetailsSubset', {'first_name': str, 'last_name': str}, total=False)
defaults: Details = {'first_name': 'John', 'last_name': 'Luther'}

def generate(data: DetailsSubset) -> Details:
    return {**defaults, **data}  # OK
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackUntypedDict]
from typing import Any, Dict, TypedDict

class Bar(TypedDict):
    pass

foo: Dict[str, Any] = {}
bar: Bar = {**foo}  # E: Unsupported type "dict[str, Any]" for ** expansion in TypedDict
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackIntoUnion]
from typing import TypedDict, Union

class Foo(TypedDict):
    a: int

class Bar(TypedDict):
    b: int

foo: Foo = {'a': 1}
foo_or_bar: Union[Foo, Bar] = {**foo}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackFromUnion]
from typing import TypedDict, Union

class Foo(TypedDict):
    a: int
    b: int

class Bar(TypedDict):
    b: int

foo_or_bar: Union[Foo, Bar] = {'b': 1}
foo: Bar = {**foo_or_bar}  # E: Extra key "a" for TypedDict "Bar"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackUnionRequiredMissing]
from typing import TypedDict, NotRequired, Union

class Foo(TypedDict):
    a: int
    b: int

class Bar(TypedDict):
    a: int
    b: NotRequired[int]

foo_or_bar: Union[Foo, Bar] = {"a": 1}
foo: Foo = {**foo_or_bar}  # E: Missing key "b" for TypedDict "Foo"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackInference]
from typing import TypedDict, Generic, TypeVar

class Foo(TypedDict):
    a: int
    b: str

T = TypeVar("T")
class TD(TypedDict, Generic[T]):
    a: T
    b: str

foo: Foo
bar = TD(**foo)
reveal_type(bar)  # N: Revealed type is "TypedDict('__main__.TD', {'a': builtins.int, 'b': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackStrictMode]
# flags: --extra-checks
from typing import TypedDict, NotRequired

class Foo(TypedDict):
    a: int

class Bar(TypedDict):
    a: int
    b: NotRequired[int]

foo: Foo
bar: Bar = {**foo}  # E: Non-required key "b" not explicitly found in any ** item
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackAny]
from typing import Any, TypedDict, NotRequired, Dict, Union

class Foo(TypedDict):
    a: int
    b: NotRequired[int]

x: Any
y: Dict[Any, Any]
z: Union[Any, Dict[Any, Any]]
t1: Foo = {**x}  # E: Missing key "a" for TypedDict "Foo"
t2: Foo = {**y}  # E: Missing key "a" for TypedDict "Foo"
t3: Foo = {**z}  # E: Missing key "a" for TypedDict "Foo"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackError]
from typing import TypedDict

class Foo(TypedDict):
    a: int

def foo(x: int) -> Foo: ...

f: Foo = {**foo("no")}  # E: Argument 1 to "foo" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictWith__or__method]
from typing import Dict, TypedDict

class Foo(TypedDict):
    key: int

foo1: Foo = {'key': 1}
foo2: Foo = {'key': 2}

reveal_type(foo1 | foo2)  # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
reveal_type(foo1 | {'key': 1})  # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
reveal_type(foo1 | {'key': 'a'})  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
reveal_type(foo1 | {})  # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"

d1: Dict[str, int]
d2: Dict[int, str]

reveal_type(foo1 | d1)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
foo1 | d2  # E: Unsupported operand types for | ("Foo" and "dict[int, str]")


class Bar(TypedDict):
    key: int
    value: str

bar: Bar
reveal_type(bar | {})  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type(bar | {'key': 1, 'value': 'v'})  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type(bar | {'key': 1})  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type(bar | {'value': 'v'})  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type(bar | {'key': 'a'})  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
reveal_type(bar | {'value': 1})  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
reveal_type(bar | {'key': 'a', 'value': 1})  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"

reveal_type(bar | foo1)  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type(bar | d1)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
bar | d2  # E: Unsupported operand types for | ("Bar" and "dict[int, str]")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testTypedDictWith__or__method_error]
from typing import TypedDict

class Foo(TypedDict):
    key: int

foo: Foo = {'key': 1}
foo | 1

class SubDict(dict): ...
reveal_type(foo | SubDict())
[out]
main:7: error: No overload variant of "__or__" of "TypedDict" matches argument type "int"
main:7: note: Possible overload variants:
main:7: note:     def __or__(self, TypedDict({'key'?: int}), /) -> Foo
main:7: note:     def __or__(self, dict[str, Any], /) -> dict[str, object]
main:10: note: Revealed type is "builtins.dict[builtins.str, builtins.object]"
[builtins fixtures/dict-full.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testTypedDictWith__ror__method]
from typing import Dict, TypedDict

class Foo(TypedDict):
    key: int

foo: Foo = {'key': 1}

reveal_type({'key': 1} | foo)  # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
reveal_type({'key': 'a'} | foo)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
reveal_type({} | foo)  # N: Revealed type is "TypedDict('__main__.Foo', {'key': builtins.int})"
{1: 'a'} | foo  # E: Dict entry 0 has incompatible type "int": "str"; expected "str": "Any"

d1: Dict[str, int]
d2: Dict[int, str]

reveal_type(d1 | foo)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
d2 | foo  # E: Unsupported operand types for | ("dict[int, str]" and "Foo")
1 | foo  # E: No overload variant of "__ror__" of "TypedDict" matches argument type "int" \
         # N: Possible overload variants: \
         # N:     def __ror__(self, TypedDict({'key'?: int}), /) -> Foo \
         # N:     def __ror__(self, dict[str, Any], /) -> dict[str, object]

class Bar(TypedDict):
    key: int
    value: str

bar: Bar
reveal_type({} | bar)  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type({'key': 1, 'value': 'v'} | bar)  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type({'key': 1} | bar)  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type({'value': 'v'} | bar)  # N: Revealed type is "TypedDict('__main__.Bar', {'key': builtins.int, 'value': builtins.str})"
reveal_type({'key': 'a'} | bar)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
reveal_type({'value': 1} | bar)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
reveal_type({'key': 'a', 'value': 1} | bar)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"

reveal_type(d1 | bar)  # N: Revealed type is "builtins.dict[builtins.str, builtins.object]"
d2 | bar  # E: Unsupported operand types for | ("dict[int, str]" and "Bar")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testTypedDictWith__ior__method]
from typing import Dict, TypedDict

class Foo(TypedDict):
    key: int

foo: Foo = {'key': 1}
foo |= {'key': 2}

foo |= {}
foo |= {'key': 'a', 'b': 'a'}  # E: Expected TypedDict key "key" but found keys ("key", "b")  \
                               # E: Incompatible types (expression has type "str", TypedDict item "key" has type "int")
foo |= {'b': 2}  # E: Unexpected TypedDict key "b"

d1: Dict[str, int]
d2: Dict[int, str]

foo |= d1  # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'key'?: int})"
foo |= d2  # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[int, str]"; expected "TypedDict({'key'?: int})"


class Bar(TypedDict):
    key: int
    value: str

bar: Bar
bar |= {}
bar |= {'key': 1, 'value': 'a'}
bar |= {'key': 'a', 'value': 'a', 'b': 'a'}  # E: Expected TypedDict keys ("key", "value") but found keys ("key", "value", "b") \
                                             # E: Incompatible types (expression has type "str", TypedDict item "key" has type "int")

bar |= foo
bar |= d1  # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[str, int]"; expected "TypedDict({'key'?: int, 'value'?: str})"
bar |= d2  # E: Argument 1 to "__ior__" of "TypedDict" has incompatible type "dict[int, str]"; expected "TypedDict({'key'?: int, 'value'?: str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testGenericTypedDictStrictOptionalExtending]
from typing import Generic, TypeVar, TypedDict, Optional

T = TypeVar("T")
class Foo(TypedDict, Generic[T], total=False):
    a: Optional[str]
    g: Optional[T]

class Bar(Foo[T], total=False):
    other: str

b: Bar[int]
reveal_type(b["a"])  # N: Revealed type is "Union[builtins.str, None]"
reveal_type(b["g"])  # N: Revealed type is "Union[builtins.int, None]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testNoCrashOnUnImportedAnyNotRequired]
# flags: --disallow-any-unimported
from typing import NotRequired, Required, TypedDict
from thismoduledoesntexist import T  # type: ignore[import]

B = TypedDict("B", {  # E: Type of a TypedDict key becomes "Any" due to an unfollowed import
    "T1": NotRequired[T],
    "T2": Required[T],
})
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictWithClassLevelKeywords]
from typing import TypedDict, Generic, TypeVar

T = TypeVar('T')

class Meta(type): ...

class WithMetaKeyword(TypedDict, metaclass=Meta):  # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict"
    ...

class GenericWithMetaKeyword(TypedDict, Generic[T], metaclass=Meta):  # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict"
    ...

# We still don't allow this, because the implementation is much easier
# and it does not make any practical sense to do it:
class WithTypeMeta(TypedDict, metaclass=type):  # E: Unexpected keyword argument "metaclass" for "__init_subclass__" of "TypedDict"
    ...

class OtherKeywords(TypedDict, a=1, b=2, c=3, total=True):  # E: Unexpected keyword argument "a" for "__init_subclass__" of "TypedDict" \
                                                            # E: Unexpected keyword argument "b" for "__init_subclass__" of "TypedDict" \
                                                            # E: Unexpected keyword argument "c" for "__init_subclass__" of "TypedDict"
    ...

class TotalInTheMiddle(TypedDict, a=1, total=True, b=2, c=3):  # E: Unexpected keyword argument "a" for "__init_subclass__" of "TypedDict" \
                                                            # E: Unexpected keyword argument "b" for "__init_subclass__" of "TypedDict" \
                                                            # E: Unexpected keyword argument "c" for "__init_subclass__" of "TypedDict"
    ...
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testCanCreateClassWithFunctionBasedTypedDictBase]
from typing import TypedDict

class Params(TypedDict("Params", {'x': int})):
    pass

p: Params = {'x': 2}
reveal_type(p) # N: Revealed type is "TypedDict('__main__.Params', {'x': builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testInitTypedDictFromType]
from typing import TypedDict, Type
from typing_extensions import Required

class Point(TypedDict, total=False):
    x: Required[int]
    y: int

def func(cls: Type[Point]) -> None:
    reveal_type(cls)  # N: Revealed type is "type[TypedDict('__main__.Point', {'x': builtins.int, 'y'?: builtins.int})]"
    cls(x=1, y=2)
    cls(1, 2)  # E: Too many positional arguments
    cls(x=1)
    cls(y=2)  # E: Missing named argument "x"
    cls(x=1, y=2, error="")  # E: Unexpected keyword argument "error"
[typing fixtures/typing-full.pyi]
[builtins fixtures/tuple.pyi]

[case testInitTypedDictFromTypeGeneric]
from typing import Generic, TypedDict, Type, TypeVar
from typing_extensions import Required

class Point(TypedDict, total=False):
    x: Required[int]
    y: int

T = TypeVar("T", bound=Point)

class A(Generic[T]):
    def __init__(self, a: Type[T]) -> None:
        self.a = a

    def func(self) -> T:
        reveal_type(self.a)  # N: Revealed type is "type[T`1]"
        self.a(x=1, y=2)
        self.a(y=2)  # E: Missing named argument "x"
        return self.a(x=1)
[typing fixtures/typing-full.pyi]
[builtins fixtures/tuple.pyi]

[case testNameUndefinedErrorDoesNotLoseUnpackedKWArgsInformation]
from typing import TypedDict, overload
from typing_extensions import Unpack

class TD(TypedDict, total=False):
    x: int
    y: str

@overload
def f(self, *, x: int) -> None: ...
@overload
def f(self, *, y: str) -> None: ...
def f(self, **kwargs: Unpack[TD]) -> None:
    z  # E: Name "z" is not defined

@overload
def g(self, *, x: float) -> None: ...
@overload
def g(self, *, y: str) -> None: ...
def g(self, **kwargs: Unpack[TD]) -> None:  # E: Overloaded function implementation does not accept all possible arguments of signature 1
    z  # E: Name "z" is not defined

class A:
    def f(self, *, x: int) -> None: ...
    def g(self, *, x: float) -> None: ...
class B(A):
    def f(self, **kwargs: Unpack[TD]) -> None:
        z  # E: Name "z" is not defined
    def g(self, **kwargs: Unpack[TD]) -> None:  # E: Signature of "g" incompatible with supertype "A" \
                                                # N:      Superclass: \
                                                # N:          def g(self, *, x: float) -> None \
                                                # N:      Subclass: \
                                                # N:          def g(*, x: int = ..., y: str = ...) -> None
        z  # E: Name "z" is not defined
reveal_type(B.f)  # N: Revealed type is "def (self: __main__.B, **kwargs: Unpack[TypedDict('__main__.TD', {'x'?: builtins.int, 'y'?: builtins.str})])"
B().f(x=1.0)  # E: Argument "x" to "f" of "B" has incompatible type "float"; expected "int"
[builtins fixtures/primitives.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictUnpackWithParamSpecInference]
from typing import TypedDict, TypeVar, ParamSpec, Callable
from typing_extensions import Unpack

P = ParamSpec("P")
R = TypeVar("R")

def run(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: ...

class Params(TypedDict):
    temperature: float

def test(temperature: int) -> None: ...
def test2(temperature: float, other: str) -> None: ...

class Test:
    def f(self, c: Callable[..., None], **params: Unpack[Params]) -> None:
        run(c, **params)
    def g(self, **params: Unpack[Params]) -> None:
        run(test, **params)  # E: Argument "temperature" to "run" has incompatible type "float"; expected "int"
    def h(self, **params: Unpack[Params]) -> None:
        run(test2, other="yes", **params)
        run(test2, other=0, **params)  # E: Argument "other" to "run" has incompatible type "int"; expected "str"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testTypedDictUnpackSingleWithSubtypingNoCrash]
from typing import Callable, TypedDict
from typing_extensions import Unpack

class Kwargs(TypedDict):
    name: str

def f(**kwargs: Unpack[Kwargs]) -> None:
    pass

class C:
    d: Callable[[Unpack[Kwargs]], None]

# TODO: it is an old question whether we should allow this, for now simply don't crash.
class D(C):
    d = f
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineNoOldStyleAlias]
# flags: --enable-incomplete-feature=InlineTypedDict
X = {"int": int, "str": str}
reveal_type(X)  # N: Revealed type is "builtins.dict[builtins.str, def () -> builtins.object]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineYesMidStyleAlias]
# flags: --enable-incomplete-feature=InlineTypedDict
from typing_extensions import TypeAlias
X: TypeAlias = {"int": int, "str": str}
x: X
reveal_type(x)  # N:  # N: Revealed type is "TypedDict({'int': builtins.int, 'str': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineNoEmpty]
# flags: --enable-incomplete-feature=InlineTypedDict
x: {}  # E: Invalid type comment or annotation
reveal_type(x)  # N: Revealed type is "Any"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineNotRequired]
# flags: --enable-incomplete-feature=InlineTypedDict
from typing import NotRequired

x: {"one": int, "other": NotRequired[int]}
x = {"one": 1}  # OK
y: {"one": int, "other": int}
y = {"one": 1}  # E: Expected TypedDict keys ("one", "other") but found only key "one"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineReadOnly]
# flags: --enable-incomplete-feature=InlineTypedDict
from typing import ReadOnly

x: {"one": int, "other": ReadOnly[int]}
x["one"] = 1  # ok
x["other"] = 1  # E: ReadOnly TypedDict key "other" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineNestedSchema]
# flags: --enable-incomplete-feature=InlineTypedDict
def nested() -> {"one": str, "other": {"a": int, "b": int}}:
    if bool():
        return {"one": "yes", "other": {"a": 1, "b": 2}}  # OK
    else:
        return {"one": "no", "other": {"a": 1, "b": "2"}}  # E: Incompatible types (expression has type "str", TypedDict item "b" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictInlineMergeAnother]
# flags: --enable-incomplete-feature=InlineTypedDict
from typing import TypeVar
from typing_extensions import TypeAlias

T = TypeVar("T")
X: TypeAlias = {"item": T}
x: {"a": int, **X[str], "b": int}
reveal_type(x)  # N: Revealed type is "TypedDict({'a': builtins.int, 'b': builtins.int, 'item': builtins.str})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]


# ReadOnly
# See: https://peps.python.org/pep-0705

[case testTypedDictReadOnly]
# flags: --show-error-codes
from typing import ReadOnly, TypedDict

class TP(TypedDict):
    one: int
    other: ReadOnly[str]

x: TP
reveal_type(x["one"])   # N: Revealed type is "builtins.int"
reveal_type(x["other"]) # N: Revealed type is "builtins.str"
x["one"] = 1  # ok
x["other"] = "a"  # E: ReadOnly TypedDict key "other" TypedDict is mutated  [typeddict-readonly-mutated]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyCreation]
from typing import ReadOnly, TypedDict

class TD(TypedDict):
    x: ReadOnly[int]
    y: int

# Ok:
x = TD({"x": 1, "y": 2})
y = TD(x=1, y=2)
z: TD = {"x": 1, "y": 2}

# Error:
x2 = TD({"x": "a", "y": 2})  # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
y2 = TD(x="a", y=2)          # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
z2: TD = {"x": "a", "y": 2}  # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyDel]
from typing import ReadOnly, TypedDict, NotRequired

class TP(TypedDict):
    required_key: ReadOnly[str]
    optional_key: ReadOnly[NotRequired[str]]

x: TP
del x["required_key"]  # E: Key "required_key" of TypedDict "TP" cannot be deleted
del x["optional_key"]  # E: Key "optional_key" of TypedDict "TP" cannot be deleted
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyMutateMethods]
from typing import ReadOnly, NotRequired, TypedDict

class TP(TypedDict):
    key: ReadOnly[str]
    optional_key: ReadOnly[NotRequired[str]]
    other: ReadOnly[int]
    mutable: bool

x: TP
reveal_type(x.pop("key"))  # N: Revealed type is "builtins.str" \
                           # E: Key "key" of TypedDict "TP" cannot be deleted
reveal_type(x.pop("optional_key"))  # N: Revealed type is "builtins.str" \
                                    # E: Key "optional_key" of TypedDict "TP" cannot be deleted


x.update({"key": "abc", "other": 1, "mutable": True})  # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated
x.setdefault("key", "abc")  # E: ReadOnly TypedDict key "key" TypedDict is mutated
x.setdefault("optional_key", "foo")  # E: ReadOnly TypedDict key "optional_key" TypedDict is mutated
x.setdefault("other", 1)  # E: ReadOnly TypedDict key "other" TypedDict is mutated
x.setdefault("mutable", False)  # ok
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictFromTypingExtensionsReadOnlyMutateMethods]
from typing_extensions import ReadOnly, TypedDict

class TP(TypedDict):
    key: ReadOnly[str]

x: TP
x.update({"key": "abc"})  # E: ReadOnly TypedDict key "key" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictFromMypyExtensionsReadOnlyMutateMethods]
from mypy_extensions import TypedDict
from typing_extensions import ReadOnly

class TP(TypedDict):
    key: ReadOnly[str]

x: TP
x.update({"key": "abc"})  # E: ReadOnly TypedDict key "key" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyMutate__ior__Statements]
from typing import TypedDict
from typing_extensions import ReadOnly

class TP(TypedDict):
    key: ReadOnly[str]
    other: ReadOnly[int]
    mutable: bool

x: TP
x |= {"mutable": True}  # ok
x |= {"key": "a"}  # E: ReadOnly TypedDict key "key" TypedDict is mutated
x |= {"key": "a", "other": 1, "mutable": True}  # E: ReadOnly TypedDict keys ("key", "other") TypedDict are mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testTypedDictReadOnlyMutate__or__Statements]
from typing import TypedDict
from typing_extensions import ReadOnly

class TP(TypedDict):
    key: ReadOnly[str]
    other: ReadOnly[int]
    mutable: bool

x: TP
# These are new objects, not mutation:
x = x | {"mutable": True}
x = x | {"key": "a"}
x = x | {"key": "a", "other": 1, "mutable": True}
y1 = x | {"mutable": True}
y2 = x | {"key": "a"}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict-iror.pyi]

[case testTypedDictReadOnlyMutateWithOtherDicts]
from typing import ReadOnly, TypedDict, Dict

class TP(TypedDict):
    key: ReadOnly[str]
    mutable: bool

class Mutable(TypedDict):
    mutable: bool

class Regular(TypedDict):
    key: str

m: Mutable
r: Regular
d: Dict[str, object]

# Creating new objects is ok:
tp: TP = {**r, **m}
tp1: TP = {**tp, **m}
tp2: TP = {**r, **m}
tp3: TP = {**tp, **r}
tp4: TP = {**tp, **d}  # E: Unsupported type "dict[str, object]" for ** expansion in TypedDict
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictGenericReadOnly]
from typing import ReadOnly, TypedDict, TypeVar, Generic

T = TypeVar('T')

class TP(TypedDict, Generic[T]):
    key: ReadOnly[T]

x: TP[int]
reveal_type(x["key"])   # N: Revealed type is "builtins.int"
x["key"] = 1  # E: ReadOnly TypedDict key "key" TypedDict is mutated
x["key"] = "a"  # E: ReadOnly TypedDict key "key" TypedDict is mutated \
                # E: Value of "key" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyOtherTypedDict]
from typing import ReadOnly, TypedDict

class First(TypedDict):
    field: int

class TP(TypedDict):
    key: ReadOnly[First]

x: TP
reveal_type(x["key"]["field"])   # N: Revealed type is "builtins.int"
x["key"]["field"] = 1  # ok
x["key"] = {"field": 2}  # E: ReadOnly TypedDict key "key" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyInheritance]
from typing import ReadOnly, TypedDict

class Base(TypedDict):
    a: ReadOnly[str]

class Child(Base):
    b: ReadOnly[int]

base: Base
reveal_type(base["a"])   # N: Revealed type is "builtins.str"
base["a"] = "x"  # E: ReadOnly TypedDict key "a" TypedDict is mutated
base["b"]  # E: TypedDict "Base" has no key "b"

child: Child
reveal_type(child["a"])   # N: Revealed type is "builtins.str"
reveal_type(child["b"])   # N: Revealed type is "builtins.int"
child["a"] = "x"  # E: ReadOnly TypedDict key "a" TypedDict is mutated
child["b"] = 1  # E: ReadOnly TypedDict key "b" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlySubtyping]
from typing import ReadOnly, TypedDict

class A(TypedDict):
    key: ReadOnly[str]

class B(TypedDict):
    key: str

a: A
b: B

def accepts_A(d: A): ...
def accepts_B(d: B): ...

accepts_A(a)
accepts_A(b)
accepts_B(a)  # E: Argument 1 to "accepts_B" has incompatible type "A"; expected "B"
accepts_B(b)
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictRequiredConsistentWithNotRequiredReadOnly]
from typing import NotRequired, ReadOnly, Required, TypedDict

class A(TypedDict):
    x: NotRequired[ReadOnly[str]]

class B(TypedDict):
    x: Required[str]

def f(b: B):
    a: A = b  # ok
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyCall]
from typing import ReadOnly, TypedDict

TP = TypedDict("TP", {"one": int, "other": ReadOnly[str]})

x: TP
reveal_type(x["one"])   # N: Revealed type is "builtins.int"
reveal_type(x["other"]) # N: Revealed type is "builtins.str"
x["one"] = 1  # ok
x["other"] = "a"  # E: ReadOnly TypedDict key "other" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyABCSubtypes]
from typing import ReadOnly, TypedDict, Mapping, Dict, MutableMapping

class TP(TypedDict):
    one: int
    other: ReadOnly[int]

def accepts_mapping(m: Mapping[str, object]): ...
def accepts_mutable_mapping(mm: MutableMapping[str, object]): ...
def accepts_dict(d: Dict[str, object]): ...

x: TP
accepts_mapping(x)
accepts_mutable_mapping(x)  # E: Argument 1 to "accepts_mutable_mapping" has incompatible type "TP"; expected "MutableMapping[str, object]"
accepts_dict(x)  # E: Argument 1 to "accepts_dict" has incompatible type "TP"; expected "dict[str, object]"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyAndNotRequired]
from typing import ReadOnly, TypedDict, NotRequired

class TP(TypedDict):
    one: ReadOnly[NotRequired[int]]
    two: NotRequired[ReadOnly[str]]

x: TP
reveal_type(x)  # N: Revealed type is "TypedDict('__main__.TP', {'one'?=: builtins.int, 'two'?=: builtins.str})"
reveal_type(x.get("one"))  # N: Revealed type is "Union[builtins.int, None]"
reveal_type(x.get("two"))  # N: Revealed type is "Union[builtins.str, None]"
x["one"] = 1  # E: ReadOnly TypedDict key "one" TypedDict is mutated
x["two"] = "a"  # E: ReadOnly TypedDict key "two" TypedDict is mutated
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testMeetOfTypedDictsWithReadOnly]
from typing import TypeVar, Callable, TypedDict, ReadOnly
XY = TypedDict('XY', {'x': ReadOnly[int], 'y': int})
YZ = TypedDict('YZ', {'y': int, 'z': ReadOnly[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]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyUnpack]
from typing import TypedDict
from typing_extensions import Unpack, ReadOnly

class TD(TypedDict):
    x: ReadOnly[int]
    y: str

def func(**kwargs: Unpack[TD]):
    kwargs["x"] = 1  # E: ReadOnly TypedDict key "x" TypedDict is mutated
    kwargs["y" ] = "a"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testIncorrectTypedDictSpecialFormsUsage]
from typing import ReadOnly, TypedDict, NotRequired, Required

x: ReadOnly[int]     # E: ReadOnly[] can be only used in a TypedDict definition
y: Required[int]     # E: Required[] can be only used in a TypedDict definition
z: NotRequired[int]  # E: NotRequired[] can be only used in a TypedDict definition

class TP(TypedDict):
    a: ReadOnly[ReadOnly[int]]              # E: "ReadOnly[]" type cannot be nested
    b: ReadOnly[NotRequired[ReadOnly[str]]] # E: "ReadOnly[]" type cannot be nested
    c: NotRequired[Required[int]]           # E: "Required[]" type cannot be nested
    d: Required[NotRequired[int]]           # E: "NotRequired[]" type cannot be nested
    e: Required[ReadOnly[NotRequired[int]]] # E: "NotRequired[]" type cannot be nested
    f: ReadOnly[ReadOnly[ReadOnly[int]]]    # E: "ReadOnly[]" type cannot be nested
    g: Required[Required[int]]              # E: "Required[]" type cannot be nested
    h: NotRequired[NotRequired[int]]        # E: "NotRequired[]" type cannot be nested

    j: NotRequired[ReadOnly[Required[ReadOnly[int]]]]  # E: "Required[]" type cannot be nested \
                                                       # E: "ReadOnly[]" type cannot be nested

    k: ReadOnly  # E: "ReadOnly[]" must have exactly one type argument
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAnnotatedWithSpecialForms]
from typing import NotRequired, ReadOnly, Required, TypedDict
from typing_extensions import Annotated

class A(TypedDict):
    a: Annotated[NotRequired[ReadOnly[int]], ""]  # ok
    b: NotRequired[ReadOnly[Annotated[int, ""]]]  # ok
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictReadOnlyCovariant]
from typing import ReadOnly, TypedDict, Union

class A(TypedDict):
    a: ReadOnly[Union[int, str]]

class A2(TypedDict):
    a: ReadOnly[int]

class B(TypedDict):
    a: int

class B2(TypedDict):
    a: Union[int, str]

class B3(TypedDict):
    a: int

def fa(a: A) -> None: ...
def fa2(a: A2) -> None: ...

b: B = {"a": 1}
fa(b)
fa2(b)
b2: B2 = {"a": 1}
fa(b2)
fa2(b2)  # E: Argument 1 to "fa2" has incompatible type "B2"; expected "A2"

class C(TypedDict):
    a: ReadOnly[Union[int, str]]
    b: Union[str, bytes]

class D(TypedDict):
    a: int
    b: str

d: D = {"a": 1, "b": "x"}
c: C = d  # E: Incompatible types in assignment (expression has type "D", variable has type "C")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]


[case testTypedDictFinalAndClassVar]
from typing import TypedDict, Final, ClassVar

class My(TypedDict):
    a: Final      # E: Final[...] can't be used inside a TypedDict
    b: Final[int] # E: Final[...] can't be used inside a TypedDict
    c: ClassVar       # E: ClassVar[...] can't be used inside a TypedDict
    d: ClassVar[int]  # E: ClassVar[...] can't be used inside a TypedDict

Func = TypedDict('Func', {
    'a': Final,         # E: Final[...] can't be used inside a TypedDict
    'b': Final[int],    # E: Final[...] can't be used inside a TypedDict
    'c': ClassVar,      # E: ClassVar[...] can't be used inside a TypedDict
    'd': ClassVar[int], # E: ClassVar[...] can't be used inside a TypedDict
})
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictNestedInClassAndInherited]
from typing import TypedDict

class Base:
    class Params(TypedDict):
        name: str

class Derived(Base):
    pass

class DerivedOverride(Base):
    class Params(Base.Params):
        pass

Base.Params(name="Robert")
Derived.Params(name="Robert")
DerivedOverride.Params(name="Robert")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testEnumAsClassMemberNoCrash]
# https://github.com/python/mypy/issues/18736
from typing import TypedDict

class Base:
    def __init__(self, namespace: dict[str, str]) -> None:
        # Not a bug: trigger defer
        names = {n: n for n in namespace if fail}  # E: Name "fail" is not defined
        self.d = TypedDict("d", names)  # E: TypedDict type as attribute is not supported \
                                        # E: TypedDict() expects a dictionary literal as the second argument
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAlias]
from typing import NotRequired, TypedDict
from typing_extensions import TypeAlias

class Base(TypedDict):
    foo: int

Base1 = Base
class Child1(Base1):
    bar: NotRequired[int]
c11: Child1 = {"foo": 0}
c12: Child1 = {"foo": 0, "bar": 1}
c13: Child1 = {"foo": 0, "bar": 1, "baz": "error"}  # E: Extra key "baz" for TypedDict "Child1"

Base2: TypeAlias = Base
class Child2(Base2):
    bar: NotRequired[int]
c21: Child2 = {"foo": 0}
c22: Child2 = {"foo": 0, "bar": 1}
c23: Child2 = {"foo": 0, "bar": 1, "baz": "error"}  # E: Extra key "baz" for TypedDict "Child2"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAliasInheritance]
from typing import TypedDict
from typing_extensions import TypeAlias

class A(TypedDict):
    x: str
class B(TypedDict):
    y: int

B1 = B
B2: TypeAlias = B

class C(A, B1):
    pass
c1: C = {"y": 1}  # E: Missing key "x" for TypedDict "C"
c2: C = {"x": "x", "y": 2}
c3: C = {"x": 1, "y": 2}  # E: Incompatible types (expression has type "int", TypedDict item "x" has type "str")

class D(A, B2):
    pass
d1: D = {"y": 1}  # E: Missing key "x" for TypedDict "D"
d2: D = {"x": "x", "y": 2}
d3: D = {"x": 1, "y": 2}  # E: Incompatible types (expression has type "int", TypedDict item "x" has type "str")
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAliasDuplicateBases]
from typing import TypedDict
from typing_extensions import TypeAlias

class A(TypedDict):
    x: str

A1 = A
A2 = A
A3: TypeAlias = A

class E(A1, A2): pass  # E: Duplicate base class "A"
class F(A1, A3): pass # E: Duplicate base class "A"
class G(A, A1): pass # E: Duplicate base class "A"

class H(A, list): pass  # E: All bases of a new TypedDict must be TypedDict types
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAliasGeneric]
from typing import Generic, TypedDict, TypeVar
from typing_extensions import TypeAlias

_T = TypeVar("_T")

class A(Generic[_T], TypedDict):
    x: _T

# This is by design - no_args aliases are only supported for instances
A0 = A
class B(A0[str]):  # E: Bad number of arguments for type alias, expected 0, given 1
    y: int

A1 = A[_T]
A2: TypeAlias = A[_T]
Aint = A[int]

class C(A1[_T]):
    y: str
c1: C[int] = {"x": 0, "y": "a"}
c2: C[int] = {"x": "no", "y": "a"}  # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")

class D(A2[_T]):
    y: str
d1: D[int] = {"x": 0, "y": "a"}
d2: D[int] = {"x": "no", "y": "a"}  # E: Incompatible types (expression has type "str", TypedDict item "x" has type "int")

class E(Aint):
    y: str
e1: E = {"x": 0, "y": "a"}
e2: E = {"x": "no", "y": "a"}
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAliasAsInstanceAttribute]
from typing import TypedDict

class Dicts:
    class TF(TypedDict, total=False):
        user_id: int
    TotalFalse = TF

dicts = Dicts()
reveal_type(dicts.TF)  # N: Revealed type is "def (*, user_id: builtins.int =) -> TypedDict('__main__.Dicts.TF', {'user_id'?: builtins.int})"
reveal_type(dicts.TotalFalse)  # N: Revealed type is "def (*, user_id: builtins.int =) -> TypedDict('__main__.Dicts.TF', {'user_id'?: builtins.int})"
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testRecursiveNestedTypedDictInference]
from typing import TypedDict, Sequence
from typing_extensions import NotRequired

class Component(TypedDict):
    type: str
    components: NotRequired[Sequence['Component']]

inputs: Sequence[Component] = [{
    'type': 'tuple',
    'components': [
        {'type': 'uint256'},
        {'type': 'address'},
    ]
}]
[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]

[case testTypedDictAssignableToWiderContext]
from typing import TypedDict, Union

class TD(TypedDict):
    x: int

x: Union[TD, dict[str, str]] = {"x": "foo"}
y: Union[TD, dict[str, int]] = {"x": "foo"}  # E: Dict entry 0 has incompatible type "str": "str"; expected "str": "int"

def ok(d: Union[TD, dict[str, str]]) -> None: ...
ok({"x": "foo"})

def bad(d: Union[TD, dict[str, int]]) -> None: ...
bad({"x": "foo"})  # E: Dict entry 0 has incompatible type "str": "str"; expected "str": "int"

[builtins fixtures/dict.pyi]
[typing fixtures/typing-typeddict.pyi]