File: check-inference.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 (4263 lines) | stat: -rw-r--r-- 117,204 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
-- Inferring locals/globals with simple types
-- ------------------------------------------


[case testInferSimpleGvarType]
class A: pass
class B: pass

x = A()
y = B()
if int():
    x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
if int():
    x = A()
if int():
    x = y   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
if int():
    x = x
[case testInferSimpleLvarType]
import typing
def f() -> None:
    x = A()
    y = B()
    if int():
        x = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        x = A()
        x = y   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        x = x
class A: pass
class B: pass
[out]

[case testLvarInitializedToVoid]
import typing
def f() -> None:
    a = g()    # E: "g" does not return a value (it only ever returns None)
    #b, c = g() # "g" does not return a value (it only ever returns None) TODO

def g() -> None: pass
[out]

[case testInferringLvarTypeFromArgument]
import typing
def f(a: 'A') -> None:
    b = a
    if int():
        b = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        b = a
        a = b

class A: pass
class B: pass
[out]

[case testInferringLvarTypeFromGvar]

g: B

def f() -> None:
    a = g
    if int():
        a = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
        a = B()

class A: pass
class B: pass
[out]

[case testInferringImplicitDynamicTypeForLvar]
import typing
def f() -> None:
    a = g()
    None(a) # E: "None" not callable
    a.x()

def g(): pass
[out]

[case testInferringExplicitDynamicTypeForLvar]
from typing import Any
g: Any

def f(a: Any) -> None:
    b = g
    None(b) # E: "None" not callable
    a.x()
[out]


-- Inferring types of local variables with complex types
-- -----------------------------------------------------


[case testInferringTupleTypeForLvar]

def f() -> None:
    a = A(), B()
    aa: A
    bb: B
    if int():
        bb = a[0] # E: Incompatible types in assignment (expression has type "A", variable has type "B")
        aa = a[1] # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        aa = a[0]
        bb = a[1]

class A: pass
class B: pass
[builtins fixtures/tuple.pyi]
[out]

[case testInferringTupleTypeForLvarWithNones]
import typing
def f() -> None:
    a = A(), None
    b = None, A()

class A: pass
[builtins fixtures/tuple.pyi]
[out]

[case testInferringGenericTypeForLvar]
from typing import TypeVar, Generic
T = TypeVar('T')
class A(Generic[T]): pass
a_i: A[int]
a_s: A[str]

def f() -> None:
    a_int = A() # type: A[int]
    a = a_int
    if int():
        a = a_s # E: Incompatible types in assignment (expression has type "A[str]", variable has type "A[int]")
        a = a_i
[builtins fixtures/tuple.pyi]
[out]

[case testInferringFunctionTypeForLvar]
import typing
def f() -> None:
    a = g
    a(B()) # E: Argument 1 has incompatible type "B"; expected "A"
    a(A())

def g(a: 'A') -> None: pass

class A: pass
class B: pass
[out]

[case testInferringFunctionTypeForLvarFromTypeObject]
import typing
def f() -> None:
    a = A
    a(A()) # E: Too many arguments
    a()
    t = a # type: type

class A: pass
[out]


-- Inferring variable types in multiple definition
-- -----------------------------------------------


[case testInferringLvarTypesInMultiDef]
import typing
def f() -> None:
    a, b = A(), B()
    if int():
        a = b   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")

        a = A()
        b = B()

class A: pass
class B: pass
[out]

[case testInferringLvarTypesInTupleAssignment]
from typing import Tuple
def f() -> None:
    t: Tuple[A, B]
    a, b = t
    if int():
        a = b   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")

        a = A()
        b = B()

class A: pass
class B: pass
[builtins fixtures/tuple.pyi]
[out]

[case testInferringLvarTypesInNestedTupleAssignment1]
from typing import Tuple
def f() -> None:
    t: Tuple[A, B]
    a1, (a, b) = A(), t
    if int():
        a = b   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")

        a = A()
        b = B()

class A: pass
class B: pass
[builtins fixtures/tuple.pyi]
[out]

[case testInferringLvarTypesInNestedTupleAssignment2]
import typing
def f() -> None:
    a, (b, c) = A(), (B(), C())
    if int():
        a = b   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
        c = A() # E: Incompatible types in assignment (expression has type "A", variable has type "C")

        a = A()
        b = B()
        c = C()

class A: pass
class B: pass
class C: pass
[out]

[case testInferringLvarTypesInNestedListAssignment]
import typing
def f() -> None:
    a, (b, c) = A(), [B(), C()]
    if int():
        a = b   # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
        b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
        c = A() # E: Incompatible types in assignment (expression has type "A", variable has type "C")

        a = A()
        b = B()
        c = C()

class A: pass
class B: pass
class C: pass
[out]

[case testInferringLvarTypesInMultiDefWithNoneTypes]
import typing
def f() -> None:
    a, b = A(), None
    c, d = None, A()

class A: pass
[out]

[case testInferringLvarTypesInNestedTupleAssignmentWithNoneTypes]
import typing
def f() -> None:
    a1, (a2, b) = A(), (A(), None)

class A: pass
[out]

[case testClassObjectsNotUnpackableWithoutIterableMetaclass]
from typing import Type

class Foo: ...
A: Type[Foo] = Foo
a, b = Foo  # E: "type[Foo]" object is not iterable
c, d = A  # E: "type[Foo]" object is not iterable

class Meta(type): ...
class Bar(metaclass=Meta): ...
B: Type[Bar] = Bar
e, f = Bar  # E: "type[Bar]" object is not iterable
g, h = B  # E: "type[Bar]" object is not iterable

reveal_type(a)  # E: Cannot determine type of "a"  # N: Revealed type is "Any"
reveal_type(b)  # E: Cannot determine type of "b"  # N: Revealed type is "Any"
reveal_type(c)  # E: Cannot determine type of "c"  # N: Revealed type is "Any"
reveal_type(d)  # E: Cannot determine type of "d"  # N: Revealed type is "Any"
reveal_type(e)  # E: Cannot determine type of "e"  # N: Revealed type is "Any"
reveal_type(f)  # E: Cannot determine type of "f"  # N: Revealed type is "Any"
reveal_type(g)  # E: Cannot determine type of "g"  # N: Revealed type is "Any"
reveal_type(h)  # E: Cannot determine type of "h"  # N: Revealed type is "Any"
[out]

[case testInferringLvarTypesUnpackedFromIterableClassObject]
from typing import Iterator, Type, TypeVar, Union, overload
class Meta(type):
    def __iter__(cls) -> Iterator[int]:
        yield from [1, 2, 3]

class Meta2(type):
    def __iter__(cls) -> Iterator[str]:
        yield from ["foo", "bar", "baz"]

class Meta3(type): ...

class Foo(metaclass=Meta): ...
class Bar(metaclass=Meta2): ...
class Baz(metaclass=Meta3): ...
class Spam: ...

class Eggs(metaclass=Meta):
    @overload
    def __init__(self, x: int) -> None: ...
    @overload
    def __init__(self, x: int, y: int, z: int) -> None: ...
    def __init__(self, x: int, y: int = ..., z: int = ...) -> None: ...

A: Type[Foo] = Foo
B: Type[Union[Foo, Bar]] = Foo
C: Union[Type[Foo], Type[Bar]] = Foo
D: Type[Union[Foo, Baz]] = Foo
E: Type[Union[Foo, Spam]] = Foo
F: Type[Eggs] = Eggs
G: Type[Union[Foo, Eggs]] = Foo

a, b, c = Foo
d, e, f = A
g, h, i = B
j, k, l = C
m, n, o = D  # E: "type[Baz]" object is not iterable
p, q, r = E  # E: "type[Spam]" object is not iterable
s, t, u = Eggs
v, w, x = F
y, z, aa = G

for var in [a, b, c, d, e, f, s, t, u, v, w, x, y, z, aa]:
    reveal_type(var)  # N: Revealed type is "builtins.int"

for var2 in [g, h, i, j, k, l]:
    reveal_type(var2)  # N: Revealed type is "Union[builtins.int, builtins.str]"

for var3 in [m, n, o, p, q, r]:
    reveal_type(var3)  # N: Revealed type is "Union[builtins.int, Any]"

T = TypeVar("T", bound=Type[Foo])

def check(x: T) -> T:
    a, b, c = x
    for var in [a, b, c]:
        reveal_type(var)  # N: Revealed type is "builtins.int"
    return x

T2 = TypeVar("T2", bound=Type[Union[Foo, Bar]])

def check2(x: T2) -> T2:
    a, b, c = x
    for var in [a, b, c]:
        reveal_type(var)  # N: Revealed type is "Union[builtins.int, builtins.str]"
    return x

T3 = TypeVar("T3", bound=Union[Type[Foo], Type[Bar]])

def check3(x: T3) -> T3:
    a, b, c = x
    for var in [a, b, c]:
        reveal_type(var)  # N: Revealed type is "Union[builtins.int, builtins.str]"
    return x
[out]

[case testInferringLvarTypesUnpackedFromIterableClassObjectWithGenericIter]
from typing import Iterator, Type, TypeVar

T = TypeVar("T")
class Meta(type):
    def __iter__(self: Type[T]) -> Iterator[T]: ...
class Foo(metaclass=Meta): ...

A, B, C = Foo
reveal_type(A)  # N: Revealed type is "__main__.Foo"
reveal_type(B)  # N: Revealed type is "__main__.Foo"
reveal_type(C)  # N: Revealed type is "__main__.Foo"
[out]

[case testInferringLvarTypesInMultiDefWithInvalidTuple]
from typing import Tuple
t: Tuple[object, object, object]

def f() -> None:
    a, b = t         # Fail
    c, d, e, f = t   # Fail
    g, h, i = t
[builtins fixtures/tuple.pyi]
[out]
main:5: error: Too many values to unpack (2 expected, 3 provided)
main:6: error: Need more than 3 values to unpack (4 expected)

[case testInvalidRvalueTypeInInferredMultipleLvarDefinition]
import typing
def f() -> None:
    a, b = f   # E: "Callable[[], None]" object is not iterable
    c, d = A() # E: "A" object is not iterable
class A: pass
[builtins fixtures/for.pyi]
[out]

[case testInvalidRvalueTypeInInferredNestedTupleAssignment]
import typing
def f() -> None:
    a1, (a2, b) = A(), f   # E: "Callable[[], None]" object is not iterable
    a3, (c, d) = A(), A() # E: "A" object is not iterable
class A: pass
[builtins fixtures/for.pyi]
[out]

[case testInferringMultipleLvarDefinitionWithListRvalue]
from typing import List

class C: pass
class D: pass

def f() -> None:
    list_c = [C()]
    list_d = [D()]
    a, b = list_c
    c, d, e = list_d
    if int():
        a = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
        b = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
        c = C() # E: Incompatible types in assignment (expression has type "C", variable has type "D")
        b = c   # E: Incompatible types in assignment (expression has type "D", variable has type "C")

        a = C()
        b = C()
        c = D()
        d = D()
        e = D()

        a = b
        c = d
        d = e
[builtins fixtures/for.pyi]
[out]

[case testInferringNestedTupleAssignmentWithListRvalue]
from typing import List

class C: pass
class D: pass

def f() -> None:
    list_c = [C()]
    list_d = [D()]
    c1, (a, b) = C(), list_c
    c2, (c, d, e) = C(), list_d
    if int():
        a = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
        b = D() # E: Incompatible types in assignment (expression has type "D", variable has type "C")
        c = C() # E: Incompatible types in assignment (expression has type "C", variable has type "D")
        b = c   # E: Incompatible types in assignment (expression has type "D", variable has type "C")

        a = C()
        b = C()
        c = D()
        d = D()
        e = D()

        a = b
        c = d
        d = e
[builtins fixtures/for.pyi]
[out]

[case testInferringMultipleLvarDefinitionWithImplicitDynamicRvalue]
import typing
def f() -> None:
    a, b = g()
    a.x
    b.x
def g(): pass

[case testInferringMultipleLvarDefinitionWithExplicitDynamicRvalue]
from typing import Any
def f(d: Any) -> None:
    a, b = d
    a.x
    b.x

[case testInferringTypesFromIterable]
from typing import Iterable
class Nums(Iterable[int]):
    def __iter__(self): pass
    def __next__(self): pass
a, b = Nums()
reveal_type(a)  # N: Revealed type is "builtins.int"
reveal_type(b)  # N: Revealed type is "builtins.int"
if int():
    a = b = 1
if int():
    a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
if int():
    b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[builtins fixtures/for.pyi]

[case testInferringTypesFromIterableStructuralSubtyping1]
from typing import Iterator
class Nums:
    def __iter__(self) -> Iterator[int]: pass
a, b = Nums()
reveal_type(a)  # N: Revealed type is "builtins.int"
reveal_type(b)  # N: Revealed type is "builtins.int"
if int():
    a = b = 1
if int():
    a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
if int():
    b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[builtins fixtures/for.pyi]

[case testInferringTypesFromIterableStructuralSubtyping2]
from typing import Self
class Nums:
    def __iter__(self) -> Self: pass
    def __next__(self) -> int: pass
a, b = Nums()
reveal_type(a)  # N: Revealed type is "builtins.int"
reveal_type(b)  # N: Revealed type is "builtins.int"
if int():
    a = b = 1
if int():
    a = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
if int():
    b = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[builtins fixtures/tuple.pyi]


-- Type variable inference for generic functions
-- ---------------------------------------------


[case testInferSimpleGenericFunction]
from typing import Tuple, TypeVar
T = TypeVar('T')
a: A
b: B
c: Tuple[A, object]

def id(a: T) -> T: pass

if int():
    b = id(a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    a = id(b) # E: Incompatible types in assignment (expression has type "B", variable has type "A")
if int():
    a = id(c) # E: Incompatible types in assignment (expression has type "tuple[A, object]", variable has type "A")

if int():
    a = id(a)
    b = id(b)
    c = id(c)

class A: pass
class B: pass
[builtins fixtures/tuple.pyi]

[case testInferringGenericFunctionTypeForLvar]
from typing import TypeVar
T = TypeVar('T')
def f() -> None:
    a = id
    b: int
    c: str
    if int():
        b = a(c) # E: Incompatible types in assignment (expression has type "str", variable has type "int")
        b = a(b)
        c = a(c)
def id(x: T) -> T:
    return x
[out]

[case testUnderspecifiedInferenceResult]
# flags: --no-strict-optional
from typing import TypeVar
T = TypeVar('T')
class A: pass
a: A

def ff() -> None:
    x = f() # E: Need type annotation for "x"
    reveal_type(x) # N: Revealed type is "Any"

def f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar
def g(a: T) -> None: pass

g(None) # Ok
f()     # Ok because not used to infer local variable type
g(a)
[out]

[case testInferenceWithMultipleConstraints]
from typing import TypeVar

class A: pass
class B(A): pass

T = TypeVar('T')
a: A
b: B

def f(a: T, b: T) -> T: pass

if int():
    b = f(a, b) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
if int():
    b = f(b, a) # E: Incompatible types in assignment (expression has type "A", variable has type "B")
if int():
    a = f(a, b)
if int():
    a = f(b, a)

[case testInferenceWithMultipleVariables]
from typing import Tuple, TypeVar
T = TypeVar('T')
S = TypeVar('S')

def f(a: T, b: S) -> Tuple[T, S]: pass

class A: pass
class B: pass

a: A
b: B
taa: Tuple[A, A]
tab: Tuple[A, B]
tba: Tuple[B, A]

if int():
    taa = f(a, b) # E: Argument 2 to "f" has incompatible type "B"; expected "A"
if int():
    taa = f(b, a) # E: Argument 1 to "f" has incompatible type "B"; expected "A"
if int():
    tba = f(a, b) # E: Argument 1 to "f" has incompatible type "A"; expected "B" \
                  # E: Argument 2 to "f" has incompatible type "B"; expected "A"

if int():
    tab = f(a, b)
if int():
    tba = f(b, a)
[builtins fixtures/tuple.pyi]

[case testConstraintSolvingWithSimpleGenerics]
from typing import TypeVar, Generic
T = TypeVar('T')
ao: A[object]
ab: A[B]
ac: A[C]

def f(a: 'A[T]') -> 'A[T]': pass

def g(a: T) -> T: pass

class A(Generic[T]): pass
class B: pass
class C: pass

if int():
    ab = f(ao) # E: Argument 1 to "f" has incompatible type "A[object]"; expected "A[B]"
    ao = f(ab) # E: Argument 1 to "f" has incompatible type "A[B]"; expected "A[object]"
if int():
    ab = f(ac) # E: Argument 1 to "f" has incompatible type "A[C]"; expected "A[B]"
if int():
    ab = g(ao) # E: Argument 1 to "g" has incompatible type "A[object]"; expected "A[B]"
    ao = g(ab) # E: Argument 1 to "g" has incompatible type "A[B]"; expected "A[object]"

if int():
    ab = f(ab)
    ac = f(ac)
    ao = f(ao)

if int():
    ab = g(ab)
    ao = g(ao)
[case testConstraintSolvingFailureWithSimpleGenerics]
from typing import TypeVar, Generic
T = TypeVar('T')
ao: A[object]
ab: A[B]

def f(a: 'A[T]', b: 'A[T]') -> None: pass

class A(Generic[T]): pass
class B: pass


f(ao, ab) # E: Cannot infer value of type parameter "T" of "f"
f(ab, ao) # E: Cannot infer value of type parameter "T" of "f"
f(ao, ao)
f(ab, ab)

[case testTypeInferenceWithCalleeDefaultArgs]
# flags: --no-strict-optional
from typing import TypeVar
T = TypeVar('T')
a = None # type: A
o = None # type: object

def f(a: T = None) -> T: pass
def g(a: T, b: T = None) -> T: pass

class A: pass

if int():
    a = f(o)    # E: Incompatible types in assignment (expression has type "object", variable has type "A")
if int():
    a = g(a, o) # E: Incompatible types in assignment (expression has type "object", variable has type "A")

if int():
    o = f()
if int():
    o = f(o)
if int():
    a = f(a)
if int():
    a = g(a)


-- Generic function inference with multiple inheritance
-- ----------------------------------------------------


[case testGenericFunctionInferenceWithMultipleInheritance]
from typing import TypeVar

class I: pass
class J: pass

class A(I, J): pass
class B(I, J): pass
class C(I): pass
class D(J): pass

T = TypeVar('T')
def f(a: T, b: T) -> T: pass
def g(x: I) -> None: pass

a = f(A(), C())
g(a)
b = f(A(), B())
g(b)
c = f(A(), D())
g(c) # E: Argument 1 to "g" has incompatible type "J"; expected "I"
d = f(D(), A())
g(d) # E: Argument 1 to "g" has incompatible type "J"; expected "I"
e = f(D(), C())
g(e) # E: Argument 1 to "g" has incompatible type "object"; expected "I"

[case testGenericFunctionInferenceWithMultipleInheritance2]
from typing import TypeVar

class I: pass
class J: pass

class A(I): pass
class B(A, J): pass
class C(I, J): pass

T = TypeVar('T')
def f(a: T, b: T) -> T: pass
def g(x: I) -> None: pass
def h(x: J) -> None: pass

a = f(B(), C())
g(a)
h(a) # E: Argument 1 to "h" has incompatible type "I"; expected "J"
b = f(C(), B())
g(b)
h(b) # E: Argument 1 to "h" has incompatible type "I"; expected "J"
c = f(A(), B())
g(a)
h(b) # E: Argument 1 to "h" has incompatible type "I"; expected "J"

[case testGenericFunctionInferenceWithMultipleInheritance3]
from typing import TypeVar

class I: pass
class J: pass
class K(J): pass

class A(K): pass
class B(A, I): pass
class C(I, J): pass

T = TypeVar('T')
def f(a: T, b: T) -> T: pass
def g(x: K) -> None: pass

a = f(B(), C())
g(a) # E: Argument 1 to "g" has incompatible type "J"; expected "K"
b = f(A(), C())
g(b) # E: Argument 1 to "g" has incompatible type "J"; expected "K"
c = f(A(), B())
g(c)

[case testPrecedenceOfFirstBaseAsInferenceResult]
from typing import TypeVar
from abc import abstractmethod, ABCMeta
class A: pass
class B(A, I, J): pass
class C(A, I, J): pass

def f(a: T, b: T) -> T: pass

T = TypeVar('T')
a: A
i: I
j: J

a = f(B(), C())

class I(metaclass=ABCMeta): pass
class J(metaclass=ABCMeta): pass


[builtins fixtures/tuple.pyi]


-- Generic function inference with function arguments
-- --------------------------------------------------


[case testNonOverloadedMapInference]
from typing import TypeVar, Callable, List
t = TypeVar('t')
s = TypeVar('s')
class A: pass
b = bool()
def f(x: bool) -> A: pass
def mymap(f: Callable[[t], s], a: List[t]) -> List[s]: pass

l = mymap(f, [b])
if int():
    l = [A()]
lb = [b]
if int():
    l = lb # E: Incompatible types in assignment (expression has type "list[bool]", variable has type "list[A]")
[builtins fixtures/for.pyi]

[case testGenericFunctionWithTypeTypeAsCallable]
from typing import Callable, Type, TypeVar
T = TypeVar('T')
def f(x: Callable[..., T]) -> T: return x()
class A: pass
x: Type[A]
y = f(x)
reveal_type(y)  # N: Revealed type is "__main__.A"

-- Generic function inference with unions
-- --------------------------------------


[case testUnionInference]
from typing import TypeVar, Union, List
T = TypeVar('T')
U = TypeVar('U')
def f(x: Union[T, int], y: T) -> T: pass
f(1, 'a')() # E: "str" not callable
f('a', 1)() # E: "object" not callable
f('a', 'a')() # E: "str" not callable
f(1, 1)() # E: "int" not callable

def g(x: Union[T, List[T]]) -> List[T]: pass
def h(x: List[str]) -> None: pass
g('a')() # E: "list[str]" not callable

# The next line is a case where there are multiple ways to satisfy a constraint
# involving a Union. Either T = list[str] or T = str would turn out to be valid,
# but mypy doesn't know how to branch on these two options (and potentially have
# to backtrack later) and defaults to T = Never. The result is an
# awkward error message. Either a better error message, or simply accepting the
# call, would be preferable here.
g(['a']) # E: Argument 1 to "g" has incompatible type "list[str]"; expected "list[Never]"

h(g(['a']))

def i(x: Union[List[T], List[U]], y: List[T], z: List[U]) -> None: pass
a = [1]
b = ['b']
i(a, a, b)
i(b, a, b)
i(a, b, b) # E: Argument 1 to "i" has incompatible type "list[int]"; expected "list[str]"
[builtins fixtures/list.pyi]

[case testCallableListJoinInference]
from typing import Any, Callable

def fun() -> None:
    callbacks = [
        callback1,
        callback2,
    ]

    for c in callbacks:
        call(c, 1234) # this must not fail

def callback1(i: int) -> int:
    return i
def callback2(i: int) -> str:
    return 'hello'
def call(c: Callable[[int], Any], i: int) -> None:
    c(i)
[builtins fixtures/list.pyi]
[out]

[case testCallableMeetAndJoin]
from typing import Callable, Any, TypeVar

class A: ...
class B(A): ...

def f(c: Callable[[B], int]) -> None: ...

c: Callable[[A], int]
d: Callable[[B], int]

lst = [c, d]
reveal_type(lst) # N: Revealed type is "builtins.list[def (__main__.B) -> builtins.int]"

T = TypeVar('T')
def meet_test(x: Callable[[T], int], y: Callable[[T], int]) -> T: ...

CA = Callable[[A], A]
CB = Callable[[B], B]

ca: Callable[[CA], int]
cb: Callable[[CB], int]
reveal_type(meet_test(ca, cb)) # N: Revealed type is "def (__main__.A) -> __main__.B"
[builtins fixtures/list.pyi]
[out]

[case testUnionInferenceWithTypeVarValues]
from typing import TypeVar, Union
AnyStr = TypeVar('AnyStr', bytes, str)
def f(x: Union[AnyStr, int], *a: AnyStr) -> None: pass
f('foo')
f('foo', 'bar')
f('foo', b'bar') # E: Value of type variable "AnyStr" of "f" cannot be "Sequence[object]"
f(1)
f(1, 'foo')
f(1, 'foo', b'bar') # E: Value of type variable "AnyStr" of "f" cannot be "Sequence[object]"
[builtins fixtures/primitives.pyi]


[case testUnionTwoPassInference-skip]
from typing import TypeVar, Union, List
T = TypeVar('T')
U = TypeVar('U')
def j(x: Union[List[T], List[U]], y: List[T]) -> List[U]: pass

a = [1]
b = ['b']
# We could infer: Since List[str] <: List[T], we must have T = str.
# Then since List[int] <: Union[List[str], List[U]], and List[int] is
# not a subtype of List[str], we must have U = int.
# This is not currently implemented.
j(a, b)
[builtins fixtures/list.pyi]


[case testUnionContext]
from typing import TypeVar, Union, List
T = TypeVar('T')
def f() -> List[T]: pass
d1 = f() # type: Union[List[int], str]
d2 = f() # type: Union[int, str] # E: Incompatible types in assignment (expression has type "list[Never]", variable has type "Union[int, str]")
def g(x: T) -> List[T]: pass
d3 = g(1) # type: Union[List[int], List[str]]
[builtins fixtures/list.pyi]


[case testGenericFunctionSubtypingWithUnions]
from typing import TypeVar, Union, List
T = TypeVar('T')
S = TypeVar('S')
def k1(x: int, y: List[T]) -> List[Union[T, int]]: pass
def k2(x: S, y: List[T]) -> List[Union[T, int]]: pass
a = k2
if int():
    a = k2
if int():
    a = k1 # E: Incompatible types in assignment (expression has type "Callable[[int, list[T@k1]], list[Union[T@k1, int]]]", variable has type "Callable[[S, list[T@k2]], list[Union[T@k2, int]]]")
b = k1
if int():
    b = k1
if int():
    b = k2
[builtins fixtures/list.pyi]

[case testAmbiguousUnionContextAndMultipleInheritance]
from typing import TypeVar, Union, Generic

_T = TypeVar('_T')

class T(Generic[_T]): pass
class U(Generic[_T]): pass
class V(T[_T], U[_T]): pass

def wait_for(fut: Union[T[_T], U[_T]]) -> _T: ...

reveal_type(wait_for(V[str]()))  # N: Revealed type is "builtins.str"

[case testAmbiguousUnionContextAndMultipleInheritance2]
from typing import TypeVar, Union, Generic

_T = TypeVar('_T')
_S = TypeVar('_S')

class T(Generic[_T, _S]): pass
class U(Generic[_T, _S]): pass
class V(T[_T, _S], U[_T, _S]): pass

def wait_for(fut: Union[T[_T, _S], U[_T, _S]]) -> T[_T, _S]: ...

reveal_type(wait_for(V[int, str]()))  \
    # N: Revealed type is "__main__.T[builtins.int, builtins.str]"


-- Literal expressions
-- -------------------


[case testDictLiteral]
from typing import Dict
class A: pass
class B: pass
def d_ab() -> Dict[A, B]: return {}
def d_aa() -> Dict[A, A]: return {}
a: A
b: B
d = {a:b}
if int():
    d = d_ab()
if int():
    d = d_aa() # E: Incompatible types in assignment (expression has type "dict[A, A]", variable has type "dict[A, B]")
[builtins fixtures/dict.pyi]

[case testSetLiteral]
from typing import Any, Set
a: int
x: Any
def s_i() -> Set[int]: return set()
def s_s() -> Set[str]: return set()
s = {a}
if int():
    s = {x}
if int():
    s = s_i()
if int():
    s = s_s() # E: Incompatible types in assignment (expression has type "set[str]", variable has type "set[int]")
[builtins fixtures/set.pyi]

[case testSetWithStarExpr]
s = {1, 2, *(3, 4)}
t = {1, 2, *s}
reveal_type(s)  # N: Revealed type is "builtins.set[builtins.int]"
reveal_type(t)  # N: Revealed type is "builtins.set[builtins.int]"
[builtins fixtures/set.pyi]

[case testListLiteralWithFunctionsErasesNames]
def f1(x: int) -> int: ...
def g1(y: int) -> int: ...
def h1(x: int) -> int: ...

list_1 = [f1, g1]
list_2 = [f1, h1]
reveal_type(list_1)  # N: Revealed type is "builtins.list[def (builtins.int) -> builtins.int]"
reveal_type(list_2)  # N: Revealed type is "builtins.list[def (x: builtins.int) -> builtins.int]"

def f2(x: int, z: str) -> int: ...
def g2(y: int, z: str) -> int: ...
def h2(x: int, z: str) -> int: ...

list_3 = [f2, g2]
list_4 = [f2, h2]
reveal_type(list_3)  # N: Revealed type is "builtins.list[def (builtins.int, z: builtins.str) -> builtins.int]"
reveal_type(list_4)  # N: Revealed type is "builtins.list[def (x: builtins.int, z: builtins.str) -> builtins.int]"
[builtins fixtures/list.pyi]

[case testListLiteralWithSimilarFunctionsErasesName]
from typing import Union

class A: ...
class B(A): ...
class C: ...
class D: ...

def f(x: Union[A, C], y: B) -> A: ...
def g(z: Union[B, D], y: A) -> B: ...
def h(x: Union[B, D], y: A) -> B: ...

list_1 = [f, g]
list_2 = [f, h]
reveal_type(list_1)  # N: Revealed type is "builtins.list[def (__main__.B, y: __main__.B) -> __main__.A]"
reveal_type(list_2)  # N: Revealed type is "builtins.list[def (x: __main__.B, y: __main__.B) -> __main__.A]"
[builtins fixtures/list.pyi]

[case testListLiteralWithNameOnlyArgsDoesNotEraseNames]
def f(*, x: int) -> int: ...
def g(*, y: int) -> int: ...
def h(*, x: int) -> int: ...

list_1 = [f, g]  # E: List item 0 has incompatible type "def f(*, x: int) -> int"; expected "def g(*, y: int) -> int"
list_2 = [f, h]
[builtins fixtures/list.pyi]


-- For statements
-- --------------


[case testInferenceOfFor1]
a: A
b: B

class A: pass
class B: pass

for x in [A()]:
    b = x # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    a = x

for y in []: # E: Need type annotation for "y"
    a = y
    reveal_type(y)  # N: Revealed type is "Any"
[builtins fixtures/for.pyi]

[case testInferenceOfFor2]
class A: pass
class B: pass
class C: pass

a: A
b: B
c: C
for x, (y, z) in [(A(), (B(), C()))]:
    b = x # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    c = y # E: Incompatible types in assignment (expression has type "B", variable has type "C")
    a = z # E: Incompatible types in assignment (expression has type "C", variable has type "A")
    a = x
    b = y
    c = z
for xx, yy, zz in [(A(), B())]: # E: Need more than 2 values to unpack (3 expected)
    pass
for xx, (yy, zz) in [(A(), B())]: # E: "B" object is not iterable
    pass
for xxx, yyy in [(None, None)]:
    pass
[builtins fixtures/for.pyi]

[case testInferenceOfFor3]
class A: pass
class B: pass

a: A
b: B

for x, y in [[A()]]:
    b = x # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    b = y # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    a = x
    a = y

for e, f in [[]]:  # E: Need type annotation for "e" \
                   # E: Need type annotation for "f"
    reveal_type(e)  # N: Revealed type is "Any"
    reveal_type(f)  # N: Revealed type is "Any"

[builtins fixtures/for.pyi]

[case testForStatementInferenceWithVoid]
def f() -> None: pass

for x in f(): # E: "f" does not return a value (it only ever returns None)
    pass
[builtins fixtures/for.pyi]

[case testReusingInferredForIndex]
import typing

class A: pass
class B: pass

for a in [A()]: pass
a = A()
if int():
    a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
    for a in []: pass
    a = A()
    a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
[builtins fixtures/for.pyi]

[case testReusingInferredForIndex2]
# flags: --allow-redefinition

def f() -> None:
    for a in [A()]: pass
    a = A()
    a
    if int():
        a = B() \
            # E: Incompatible types in assignment (expression has type "B", variable has type "A")
    for a in []: pass # E: Need type annotation for "a"
    a = A()
    if int():
        a = B() \
            # E: Incompatible types in assignment (expression has type "B", variable has type "A")
class A: pass
class B: pass
[builtins fixtures/for.pyi]
[out]

[case testReusingInferredForIndex3]
# flags: --disallow-redefinition
def f() -> None:
    for a in [A()]: pass
    a = A()
    a
    if int():
        a = B() \
            # E: Incompatible types in assignment (expression has type "B", variable has type "A")
    for a in []: pass
    a = A()
    if int():
        a = B() \
            # E: Incompatible types in assignment (expression has type "B", variable has type "A")
class A: pass
class B: pass
[builtins fixtures/for.pyi]
[out]

[case testForStatementIndexNarrowing]
from typing import TypedDict

class X(TypedDict):
    hourly: int
    daily: int

x: X
for a in ("hourly", "daily"):
    reveal_type(a)  # N: Revealed type is "Union[Literal['hourly']?, Literal['daily']?]"
    reveal_type(x[a])  # N: Revealed type is "builtins.int"
    reveal_type(a.upper())  # N: Revealed type is "builtins.str"
    c = a
    reveal_type(c)  # N: Revealed type is "builtins.str"
    a = "monthly"
    reveal_type(a)  # N: Revealed type is "builtins.str"
    a = "yearly"
    reveal_type(a)  # N: Revealed type is "builtins.str"
    a = 1  # E: Incompatible types in assignment (expression has type "int", variable has type "str")
    reveal_type(a)  # N: Revealed type is "builtins.str"
    d = a
    reveal_type(d)  # N: Revealed type is "builtins.str"

b: str
for b in ("hourly", "daily"):
    reveal_type(b)  # N: Revealed type is "builtins.str"
    reveal_type(b.upper())  # N: Revealed type is "builtins.str"
[builtins fixtures/for.pyi]
[typing fixtures/typing-full.pyi]


-- Regression tests
-- ----------------


[case testMultipleAssignmentWithPartialDefinition]
a: A
if int():
    x, a = a, a
    if int():
        x = a
    a = x
    if int():
        x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
    a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
class A: pass

[case testMultipleAssignmentWithPartialDefinition2]
a: A
if int():
    a, x = [a, a]
    if int():
        x = a
    a = x
    if int():
        x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
    a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
class A: pass
[builtins fixtures/for.pyi]

[case testMultipleAssignmentWithPartialDefinition3]
from typing import Any, cast
a: A
if int():
    x, a = cast(Any, a)
    if int():
        x = a
    a = x
    if int():
        x = object()
    a = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
class A: pass

[case testInferGlobalDefinedInBlock]
class A: pass
class B: pass

if int():
    a = A()
    if int():
        a = A()
    if int():
        a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")

[case testAssigningAnyStrToNone]
from typing import Tuple, TypeVar
AnyStr = TypeVar('AnyStr', str, bytes)

def f(x: AnyStr) -> Tuple[AnyStr]: pass
x = None
(x,) = f('')
reveal_type(x)  # N: Revealed type is "builtins.str"
[builtins fixtures/tuple.pyi]


-- Inferring attribute types
-- -------------------------


[case testInferAttributeType]
import typing
class A:
    a = B()
class B: pass

A().a = B()
A().a = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")

[case testInferAttributeTypeAndAssignInInit]
import typing
class A:
    a = B()
    def __init__(self) -> None:
        self.a = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")
        self.a = B()
class B: pass
[out]

[case testInferAttributeInInit]
import typing
class B: pass
class A:
    def __init__(self) -> None:
        self.a = A()
        self.b = B()
a = A()
a.a = A()
a.b = B()
a.a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
a.b = A() # E: Incompatible types in assignment (expression has type "A", variable has type "B")

[case testInferAttributeInInitUsingChainedAssignment]
import typing
class B: pass
class A:
    def __init__(self) -> None:
        self.a = self.b = A()
a = A()
a.a = A()
a.b = A()
a.a = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")
a.b = B() # E: Incompatible types in assignment (expression has type "B", variable has type "A")


-- Lambdas
-- -------


[case testInferLambdaType]
from typing import List, Callable
li = [1]
l = lambda: li
f1 = l # type: Callable[[], List[int]]
f2 = l # type: Callable[[], List[str]] # E: Incompatible types in assignment (expression has type "Callable[[], list[int]]", variable has type "Callable[[], list[str]]")
[builtins fixtures/list.pyi]

[case testInferLambdaType2]
from typing import List, Callable
l = lambda: [B()]
f1 = l # type: Callable[[], List[B]]
f2 = l # type: Callable[[], List[A]] # E: Incompatible types in assignment (expression has type "Callable[[], list[B]]", variable has type "Callable[[], list[A]]")

class A: pass
class B: pass
[builtins fixtures/list.pyi]

[case testUninferableLambda]
from typing import TypeVar, Callable
X = TypeVar('X')
def f(x: Callable[[X], X]) -> X: pass
y = f(lambda x: x)  # E: Need type annotation for "y"

[case testUninferableLambdaWithTypeError]
from typing import TypeVar, Callable
X = TypeVar('X')
def f(x: Callable[[X], X], y: str) -> X: pass
y = f(lambda x: x, 1) # E: Need type annotation for "y" \
                      # E: Argument 2 to "f" has incompatible type "int"; expected "str"

[case testInferLambdaNone]
# flags: --no-strict-optional
from typing import Callable
def f(x: Callable[[], None]) -> None: pass
def g(x: Callable[[], int]) -> None: pass
a = lambda: None
f(a)
g(a)
b = lambda: None  # type: Callable[[], None]
f(b)
g(b)

[case testLambdaDefaultContext]
from typing import Callable
def f(a: Callable[..., None] = lambda *a, **k: None):
    pass

def g(a: Callable[..., None] = lambda *a, **k: 1):  # E: Incompatible default for argument "a" (default has type "def (*a: Any, **k: Any) -> int", argument has type "Callable[..., None]")
    pass
[builtins fixtures/dict.pyi]

[case testLambdaVarargContext]
# Should not crash
from typing import Callable
def f(a: Callable[[int, int, int], int] = lambda *a, **k: 1):
    pass
[builtins fixtures/dict.pyi]

[case testLambdaDeferredSpecialCase]
from typing import Callable

class A:
    def f(self) -> None:
        h(lambda: self.x)

    def g(self) -> None:
        self.x = 1

def h(x: Callable[[], int]) -> None:
    pass

[case testLambdaJoinWithDynamicConstructor]
from typing import Any, Union

class Wrapper:
    def __init__(self, x: Any) -> None: ...

def f(cond: bool) -> Any:
    f = Wrapper if cond else lambda x: x
    reveal_type(f)  # N: Revealed type is "Union[def (x: Any) -> __main__.Wrapper, def (x: Any) -> Any]"
    return f(3)

def g(cond: bool) -> Any:
    f = lambda x: x if cond else Wrapper
    reveal_type(f)  # N: Revealed type is "def (x: Any) -> Union[Any, def (x: Any) -> __main__.Wrapper]"
    return f(3)

def h(cond: bool) -> Any:
    f = (lambda x: x) if cond else Wrapper
    reveal_type(f)  # N: Revealed type is "Union[def (x: Any) -> Any, def (x: Any) -> __main__.Wrapper]"
    return f(3)

-- Boolean operators
-- -----------------

[case testOrOperationWithGenericOperands]
from typing import List
a: List[A]
o: List[object]
a2 = a or []
if int():
    a = a2
    a2 = o # E: Incompatible types in assignment (expression has type "list[object]", variable has type "list[A]")
class A: pass
[builtins fixtures/list.pyi]


-- Accessing variable before its type has been inferred
-- ----------------------------------------------------


[case testAccessGlobalVarBeforeItsTypeIsAvailable]
import typing
x.y  # E: Cannot determine type of "x"  # E: Name "x" is used before definition
x = object()
x.y  # E: "object" has no attribute "y"

[case testAccessDataAttributeBeforeItsTypeIsAvailable]

a: A
a.x.y  # E: Cannot determine type of "x"
class A:
   def __init__(self) -> None:
       self.x = object()
a.x.y  # E: "object" has no attribute "y"


-- Ducktype declarations
-- ---------------------


[case testListWithDucktypeCompatibility]
from typing import List, _promote
class A: pass
@_promote(A)
class B: pass
a: List[A]
x1 = [A(), B()]
x2 = [B(), A()]
x3 = [B(), B()]
if int():
    a = x1
if int():
    a = x2
if int():
    a = x3 \
     # E: Incompatible types in assignment (expression has type "list[B]", variable has type "list[A]") \
     # N: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \
     # N: Consider using "Sequence" instead, which is covariant
[builtins fixtures/list.pyi]
[typing fixtures/typing-medium.pyi]

[case testListWithDucktypeCompatibilityAndTransitivity]
from typing import List, _promote
class A: pass
@_promote(A)
class B: pass
@_promote(B)
class C: pass
a: List[A]
x1 = [A(), C()]
x2 = [C(), A()]
x3 = [B(), C()]
if int():
    a = x1
if int():
    a = x2
if int():
    a = x3 \
     # E: Incompatible types in assignment (expression has type "list[B]", variable has type "list[A]") \
     # N: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \
     # N: Consider using "Sequence" instead, which is covariant
[builtins fixtures/list.pyi]
[typing fixtures/typing-medium.pyi]


-- Inferring type of variable when initialized to an empty collection
-- ------------------------------------------------------------------


[case testInferListInitializedToEmpty]
a = []
a.append(1)
a.append('')  # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyUsingUpdate]
a = []
a.extend([''])
a.append(0)  # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndNotAnnotated]
a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndReadBeforeAppend]
a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
if a: pass
a.xyz  # E: "list[Any]" has no attribute "xyz"
a.append('')
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndIncompleteTypeInAppend]
a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
a.append([])
a()  # E: "list[Any]" not callable
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndMultipleAssignment]
a, b = [], []
a.append(1)
b.append('')
a() # E: "list[int]" not callable
b() # E: "list[str]" not callable
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyInFunction]
def f() -> None:
   a = []
   a.append(1)
   a.append('')  # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndNotAnnotatedInFunction]
def f() -> None:
    a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")

def g() -> None: pass

a = []
a.append(1)
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndReadBeforeAppendInFunction]
def f() -> None:
    a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
    if a: pass
    a.xyz  # E: "list[Any]" has no attribute "xyz"
    a.append('')
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyInClassBody]
class A:
   a = []
   a.append(1)
   a.append('')  # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndNotAnnotatedInClassBody]
class A:
    a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")

class B:
    a = []
    a.append(1)
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyInMethod]
class A:
    def f(self) -> None:
        a = []
        a.append(1)
        a.append('')  # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndNotAnnotatedInMethod]
class A:
    def f(self) -> None:
        a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyInMethodViaAttribute]
class A:
    def f(self) -> None:
        # Attributes aren't supported right now.
        self.a = []
        self.a.append(1)
        self.a.append('')  # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyInClassBodyAndOverridden]
from typing import List

class A:
    def __init__(self) -> None:
        self.x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")

class B(A):
    @property
    def x(self) -> List[int]:  # E: Cannot override writeable attribute with read-only property
        return [123]
[builtins fixtures/list.pyi]

[case testInferSetInitializedToEmpty]
a = set()
a.add(1)
a.add('')  # E: Argument 1 to "add" of "set" has incompatible type "str"; expected "int"
[builtins fixtures/set.pyi]

[case testInferSetInitializedToEmptyUsingDiscard]
a = set()
a.discard('')
a.add(0)  # E: Argument 1 to "add" of "set" has incompatible type "int"; expected "str"
[builtins fixtures/set.pyi]

[case testInferSetInitializedToEmptyUsingUpdate]
a = set()
a.update({0})
a.add('')  # E: Argument 1 to "add" of "set" has incompatible type "str"; expected "int"
[builtins fixtures/set.pyi]

[case testInferDictInitializedToEmpty]
a = {}
a[1] = ''
a() # E: "dict[int, str]" not callable
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyUsingUpdate]
a = {}
a.update({'': 42})
a() # E: "dict[str, int]" not callable
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyUsingUpdateError]
a = {}  # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
a.update([1, 2])  # E: Argument 1 to "update" of "dict" has incompatible type "list[int]"; expected "SupportsKeysAndGetItem[Any, Any]" \
                  # N: "list" is missing following "SupportsKeysAndGetItem" protocol member: \
                  # N:     keys
a()  # E: "dict[Any, Any]" not callable
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyAndIncompleteTypeInUpdate]
a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
a[1] = {}
b = {} # E: Need type annotation for "b" (hint: "b: dict[<type>, <type>] = ...")
b[{}] = 1
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyAndUpdatedFromMethod]
# flags: --no-local-partial-types
map = {}
def add() -> None:
    map[1] = 2
[builtins fixtures/dict.pyi]

[case testInferDictInitializedToEmptyAndUpdatedFromMethodUnannotated]
# flags: --no-local-partial-types
map = {}
def add():
    map[1] = 2
[builtins fixtures/dict.pyi]

[case testSpecialCaseEmptyListInitialization]
def f(blocks: Any): # E: Name "Any" is not defined \
                    # N: Did you forget to import it from "typing"? (Suggestion: "from typing import Any")
    to_process = []
    to_process = list(blocks)
[builtins fixtures/list.pyi]

[case testSpecialCaseEmptyListInitialization2]
def f(blocks: object):
    to_process = []
    to_process = list(blocks) # E: No overload variant of "list" matches argument type "object" \
                              # N: Possible overload variants: \
                              # N:     def [T] __init__(self) -> list[T] \
                              # N:     def [T] __init__(self, x: Iterable[T]) -> list[T]
[builtins fixtures/list.pyi]

[case testInferListInitializedToEmptyAndAssigned]
a = []
if bool():
    a = [1]
reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"

def f():
    return [1]
b = []
if bool():
    b = f()
reveal_type(b) # N: Revealed type is "builtins.list[Any]"

d = {}
if bool():
    d = {1: 'x'}
reveal_type(d) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"

dd = {} # E: Need type annotation for "dd" (hint: "dd: dict[<type>, <type>] = ...")
if bool():
    dd = [1] # E: Incompatible types in assignment (expression has type "list[int]", variable has type "dict[Any, Any]")
reveal_type(dd) # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testInferOrderedDictInitializedToEmpty]
from collections import OrderedDict

o = OrderedDict()
o[1] = 'x'
reveal_type(o) # N: Revealed type is "collections.OrderedDict[builtins.int, builtins.str]"

d = {1: 'x'}
oo = OrderedDict()
oo.update(d)
reveal_type(oo) # N: Revealed type is "collections.OrderedDict[builtins.int, builtins.str]"
[builtins fixtures/dict.pyi]

[case testEmptyCollectionAssignedToVariableTwiceIncremental]
x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
y = x
x = []
reveal_type(x) # N: Revealed type is "builtins.list[Any]"
d = {} # E: Need type annotation for "d" (hint: "d: dict[<type>, <type>] = ...")
z = d
d = {}
reveal_type(d) # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]
[out2]
main:1: error: Need type annotation for "x" (hint: "x: list[<type>] = ...")
main:4: note: Revealed type is "builtins.list[Any]"
main:5: error: Need type annotation for "d" (hint: "d: dict[<type>, <type>] = ...")
main:8: note: Revealed type is "builtins.dict[Any, Any]"

[case testEmptyCollectionAssignedToVariableTwiceNoReadIncremental]
x = [] # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
x = []
[builtins fixtures/list.pyi]
[out2]
main:1: error: Need type annotation for "x" (hint: "x: list[<type>] = ...")

[case testInferAttributeInitializedToEmptyAndAssigned]
class C:
    def __init__(self) -> None:
        self.a = []
        if bool():
            self.a = [1]
reveal_type(C().a)  # N: Revealed type is "builtins.list[builtins.int]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAppended]
class C:
    def __init__(self) -> None:
        self.a = []
        if bool():
            self.a.append(1)
reveal_type(C().a)  # N: Revealed type is "builtins.list[builtins.int]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAssignedItem]
class C:
    def __init__(self) -> None:
        self.a = {}
        if bool():
            self.a[0] = 'yes'
reveal_type(C().a)  # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
[builtins fixtures/dict.pyi]

[case testInferAttributeInitializedToNoneAndAssigned]
class C:
    def __init__(self) -> None:
        self.a = None
        if bool():
            self.a = 1
reveal_type(C().a)  # N: Revealed type is "Union[builtins.int, None]"

[case testInferAttributeInitializedToEmptyNonSelf]
class C:
    def __init__(self) -> None:
        self.a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
        if bool():
            a = self
            a.a = [1]
            a.a.append(1)
reveal_type(C().a)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAssignedOtherMethod]
class C:
    def __init__(self) -> None:
        self.a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
    def meth(self) -> None:
        self.a = [1]
reveal_type(C().a)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAppendedOtherMethod]
class C:
    def __init__(self) -> None:
        self.a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
    def meth(self) -> None:
        self.a.append(1)
reveal_type(C().a)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAssignedItemOtherMethod]
class C:
    def __init__(self) -> None:
        self.a = {}  # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
    def meth(self) -> None:
        self.a[0] = 'yes'
reveal_type(C().a)  # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testInferAttributeInitializedToNoneAndAssignedOtherMethod]
class C:
    def __init__(self) -> None:
        self.a = None
    def meth(self) -> None:
        self.a = 1  # E: Incompatible types in assignment (expression has type "int", variable has type "None")
reveal_type(C().a)  # N: Revealed type is "None"

[case testInferAttributeInitializedToEmptyAndAssignedClassBody]
class C:
    a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
    def __init__(self) -> None:
        self.a = [1]
reveal_type(C().a)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAppendedClassBody]
class C:
    a = []  # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")
    def __init__(self) -> None:
        self.a.append(1)
reveal_type(C().a)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferAttributeInitializedToEmptyAndAssignedItemClassBody]
class C:
    a = {}  # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
    def __init__(self) -> None:
        self.a[0] = 'yes'
reveal_type(C().a)  # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testInferAttributeInitializedToNoneAndAssignedClassBody]
# flags: --no-local-partial-types
class C:
    a = None
    def __init__(self) -> None:
        self.a = 1
reveal_type(C().a)  # N: Revealed type is "Union[builtins.int, None]"

[case testInferListTypeFromEmptyListAndAny]
def f():
    return []

def g() -> None:
    x = []
    if bool():
        x = f()
    reveal_type(x)  # N: Revealed type is "builtins.list[Any]"

    y = []
    y.extend(f())
    reveal_type(y)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferFromEmptyDictWhenUsingIn]
d = {}
if 'x' in d:
    d['x'] = 1
reveal_type(d)  # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"

dd = {}
if 'x' not in dd:
    dd['x'] = 1
reveal_type(dd)  # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
[builtins fixtures/dict.pyi]

[case testInferFromEmptyDictWhenUsingInSpecialCase]
# flags: --no-strict-optional
d = None
if 'x' in d:  # E: "None" has no attribute "__iter__" (not iterable)
    pass
reveal_type(d)  # N: Revealed type is "None"
[builtins fixtures/dict.pyi]

[case testNoWrongUnreachableWarningWithNoStrictOptionalAndFinalInstance]
# flags: --no-strict-optional --warn-unreachable
from typing import final, Optional

@final
class C: ...

x: Optional[C]
if not x:
    x = C()
[builtins fixtures/dict.pyi]

[case testNoWrongUnreachableWarningWithNoStrictOptionalAndEnumLiteral]
# flags: --no-strict-optional --warn-unreachable
from enum import Enum
from typing import Literal, Optional

class E(Enum):
    a = 1

x: Optional[Literal[E.a]]
if not x:
    x = E.a
[builtins fixtures/dict.pyi]

[case testInferFromEmptyListWhenUsingInWithStrictEquality]
# flags: --strict-equality
def f() -> None:
    a = []
    if 1 in a:  # TODO: This should be an error
        a.append('x')
[builtins fixtures/list.pyi]
[typing fixtures/typing-full.pyi]

[case testInferListTypeFromInplaceAdd]
a = []
a += [1]
reveal_type(a)  # N: Revealed type is "builtins.list[builtins.int]"
[builtins fixtures/list.pyi]

[case testInferSetTypeFromInplaceOr]
# flags: --no-strict-optional
a = set()
a |= {'x'}
reveal_type(a)  # N: Revealed type is "builtins.set[builtins.str]"
[builtins fixtures/set.pyi]


-- Inferring types of variables first initialized to None (partial types)
-- ----------------------------------------------------------------------


[case testLocalVariablePartiallyInitializedToNone]
def f() -> None:
    if object():
        x = None
    else:
        x = 1
    x() # E: "int" not callable \
        # E: "None" not callable
[out]

[case testLocalVariablePartiallyTwiceInitializedToNone]
def f() -> None:
    if object():
        x = None
    elif object():
        x = None
    else:
        x = 1
    x() # E: "int" not callable \
        # E: "None" not callable
[out]

[case testLvarInitializedToNoneWithoutType]
import typing
def f() -> None:
    a = None
    a.x() # E: "None" has no attribute "x"
[out]

[case testGvarPartiallyInitializedToNone]
x = None
if object():
    x = 1
x() # E: "int" not callable \
    # E: "None" not callable

[case testPartiallyInitializedToNoneAndThenToPartialList]
x = None
if object():
    # Promote from partial None to partial list.
    x = []
    x.append(1)
x.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testPartiallyInitializedToNoneAndThenReadPartialList]
x = None
if object():
    # Promote from partial None to partial list.
    x = []  # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
    x
[builtins fixtures/list.pyi]

[case testPartiallyInitializedToNoneAndPartialListAndLeftPartial]
def f() -> None:
    x = None
    if object():
        # Promote from partial None to partial list.
        x = []  # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
[builtins fixtures/list.pyi]
[out]

[case testPartiallyInitializedToNoneAndThenToIncompleteType-skip]
# TODO(ddfisher): fix partial type bug and re-enable
from typing import TypeVar,  Dict
T = TypeVar('T')
def f(*x: T) -> Dict[int, T]: pass
x = None  # E: Need type annotation for "x"
if object():
    x = f()
[builtins fixtures/dict.pyi]

[case testPartiallyInitializedVariableDoesNotEscapeScope1]
def f() -> None:
    x = None
    reveal_type(x)  # N: Revealed type is "None"
x = 1
[out]

[case testPartiallyInitializedVariableDoesNotEscapeScope2]
# flags: --no-local-partial-types
x = None
def f() -> None:
    x = None
    x = 1
x()  # E: "None" not callable

[case testAttributePartiallyInitializedToNone]
class A:
    def f(self) -> None:
        self.x = None
        self.x = 1
        self.x() # E: "int" not callable
[out]

[case testAttributePartiallyInitializedToNoneWithMissingAnnotation]
class A:
    def f(self) -> None:
        self.x = None

    def g(self) -> None:
        self.x = 1
        self.x()
[out]
main:6: error: Incompatible types in assignment (expression has type "int", variable has type "None")
main:7: error: "None" not callable

[case testGlobalInitializedToNoneSetFromFunction]
a = None
def f():
    global a
    a = 42
[out]

[case testGlobalInitializedToNoneSetFromMethod]
a = None
class C:
    def m(self):
        global a
        a = 42
[out]

-- More partial type errors
-- ------------------------

[case testPartialTypeErrorSpecialCase1]
# flags: --no-local-partial-types
# This used to crash.
class A:
    x = None
    def f(self) -> None:
        for a in self.x:  # E: "None" has no attribute "__iter__" (not iterable)
            pass
[builtins fixtures/for.pyi]

[case testPartialTypeErrorSpecialCase2]
# This used to crash.
class A:
    x = []  # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
    def f(self) -> None:
        for a in self.x:
            pass
[builtins fixtures/for.pyi]

[case testPartialTypeErrorSpecialCase3]
# flags: --no-local-partial-types
class A:
    x = None
    def f(self) -> None:
        for a in A.x:  # E: "None" has no attribute "__iter__" (not iterable)
            pass
[builtins fixtures/for.pyi]

[case testPartialTypeErrorSpecialCase4]
# This used to crash.
arr = []
arr.append(arr.append(1))
[builtins fixtures/list.pyi]
[out]
main:3: error: "append" of "list" does not return a value (it only ever returns None)

-- Multipass
-- ---------


[case testMultipassAndAccessVariableBeforeDefinition]
def f() -> None:
    y = x
    y() # E: "int" not callable
x = 1
[out]

[case testMultipassAndAccessInstanceVariableBeforeDefinition]
class A:
    def f(self) -> None:
        y = self.x
        y() # E: "int" not callable

    def g(self) -> None:
        self.x = 1
[out]

[case testMultipassAndTopLevelVariable]
y = x # E: Cannot determine type of "x"  # E: Name "x" is used before definition
y()
x = 1+int()
[out]

[case testMultipassAndDecoratedMethod]
from typing import Callable, TypeVar

T = TypeVar('T')

class A:
    def f(self) -> None:
        self.g() # E: Too few arguments for "g" of "A"
        self.g(1)
    @dec
    def g(self, x: str) -> None: pass

def dec(f: Callable[[A, str], T]) -> Callable[[A, int], T]: pass
[out]

[case testMultipassAndDefineAttributeBasedOnNotReadyAttribute]
class A:
    def f(self) -> None:
        self.y = self.x

    def g(self) -> None:
        self.x = 1

    def h(self) -> None:
        self.y() # E: "int" not callable
[out]

[case testMultipassAndDefineAttributeBasedOnNotReadyAttribute2]
class A:
    def f(self) -> None:
        self.y = self.x
        self.z = self.y
        self.z() # E
        self.y() # E

    def g(self) -> None:
        self.x = 1

    def h(self) -> None:
        self.y() # E
[out]
main:5: error: "int" not callable
main:6: error: "int" not callable
main:12: error: "int" not callable

[case testMultipassAndPartialTypes]
def f() -> None:
    x = []
    y
    x.append(1)
    x.append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
    x.append(y) # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
y = ''
[builtins fixtures/list.pyi]
[out]

[case testMultipassAndPartialTypes2]
s = ''
n = 0
def f() -> None:
    global s, n
    x = []
    x.append(y)
    s = x[0]
    n = x[0] # E: Incompatible types in assignment (expression has type "str", variable has type "int")
    x.append(1) # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
y = ''
[builtins fixtures/list.pyi]
[out]

[case testMultipassAndPartialTypes3]
from typing import Dict
def g(d: Dict[str, int]) -> None: pass
def f() -> None:
    x = {}
    x[1] = y
    g(x) # E: Argument 1 to "g" has incompatible type "dict[int, str]"; expected "dict[str, int]"
    x[1] = 1 # E: Incompatible types in assignment (expression has type "int", target has type "str")
    x[1] = ''
y = ''
[builtins fixtures/dict.pyi]
[out]

[case testMultipassAndPartialTypes4]
from typing import Dict
def g(d: Dict[str, int]) -> None: pass
def f() -> None:
    x = {}
    y
    x[1] = 1
    g(x) # E: Argument 1 to "g" has incompatible type "dict[int, int]"; expected "dict[str, int]"
y = ''
[builtins fixtures/dict.pyi]
[out]

[case testMultipassAndCircularDependency]
class A:
    def f(self) -> None:
        self.x = self.y # E: Cannot determine type of "y"

    def g(self) -> None:
        self.y = self.x
[out]

[case testMultipassAndPartialTypesSpecialCase1]
def f() -> None:
    y = o
    x = []
    x.append(y)
    x() # E: "list[int]" not callable
o = 1
[builtins fixtures/list.pyi]
[out]

[case testMultipassAndPartialTypesSpecialCase2]
def f() -> None:
    y = o
    x = {}
    x[''] = y
    x() # E: "dict[str, int]" not callable
o = 1
[builtins fixtures/dict.pyi]
[out]

[case testMultipassAndPartialTypesSpecialCase3]
def f() -> None:
    x = {} # E: Need type annotation for "x" (hint: "x: dict[<type>, <type>] = ...")
    y = o
    z = {} # E: Need type annotation for "z" (hint: "z: dict[<type>, <type>] = ...")
o = 1
[builtins fixtures/dict.pyi]
[out]

[case testMultipassAndPartialTypesSpecialCase4]
def f() -> None:
    y = o
    x = None
    x = y
    x() # E: "int" not callable
o = 1
[out]

[case testMultipassAndPartialTypesSpecialCase5]
def f() -> None:
    x = None
    y = o
    x = y
    x() # E: "int" not callable
o = 1
[out]

[case testMultipassAndClassAttribute]
class S:
    def foo(self) -> int:
        return R.X

class R:
    X = 2

[case testMultipassAndMultipleFiles]
import m
def f() -> None:
    x()
x = 0
[file m.py]
def g() -> None:
    y()
y = 0
[out]
tmp/m.py:2: error: "int" not callable
main:3: error: "int" not callable

[case testForwardReferenceToDecoratedClassMethod]
from typing import TypeVar, Callable

T = TypeVar('T')
def dec() -> Callable[[T], T]: pass

A.g  # E: Cannot determine type of "g"  # E: Name "A" is used before definition

class A:
    @classmethod
    def f(cls) -> None:
        reveal_type(cls.g)  # N: Revealed type is "def (x: builtins.str)"

    @classmethod
    @dec()
    def g(cls, x: str) -> None:
        pass

    @classmethod
    def h(cls) -> None:
        reveal_type(cls.g)  # N: Revealed type is "def (x: builtins.str)"

reveal_type(A.g)  # N: Revealed type is "def (x: builtins.str)"
[builtins fixtures/classmethod.pyi]


-- Tests for special cases of unification
-- --------------------------------------


[case testUnificationRedundantUnion]
from typing import Union
a: Union[int, str]
b: Union[str, tuple]
def f(): pass
def g(x: Union[int, str]): pass
c = a if f() else b
g(c) # E: Argument 1 to "g" has incompatible type "Union[int, str, tuple[Any, ...]]"; expected "Union[int, str]"
[builtins fixtures/tuple.pyi]

[case testUnificationMultipleInheritance]
class A: pass
class B:
    def foo(self): pass
class C(A, B): pass
def f(): pass
a1 = B() if f() else C()
a1.foo()
a2 = C() if f() else B()
a2.foo()

[case testUnificationMultipleInheritanceAmbiguous]
# Show that join_instances_via_supertype() breaks ties using the first base class.
class A1: pass
class B1:
    def foo1(self): pass
class C1(A1, B1): pass

class A2: pass
class B2:
    def foo2(self): pass
class C2(A2, B2): pass

class D1(C1, C2): pass
class D2(C2, C1): pass

def f(): pass

a1 = D1() if f() else D2()
a1.foo1()
a2 = D2() if f() else D1()
a2.foo2()

[case testUnificationEmptyListLeft]
def f(): pass
a = [] if f() else [0]
a() # E: "list[int]" not callable
[builtins fixtures/list.pyi]

[case testUnificationEmptyListRight]
def f(): pass
a = [0] if f() else []
a() # E: "list[int]" not callable
[builtins fixtures/list.pyi]

[case testUnificationEmptyListLeftInContext]
from typing import List
def f(): pass
a = [] if f() else [0] # type: list[int]
a() # E: "list[int]" not callable
[builtins fixtures/list.pyi]

[case testUnificationEmptyListRightInContext]
# TODO Find an example that really needs the context
from typing import List
def f(): pass
a = [0] if f() else [] # type: list[int]
a() # E: "list[int]" not callable
[builtins fixtures/list.pyi]

[case testUnificationEmptySetLeft]
def f(): pass
a = set() if f() else {0}
a() # E: "set[int]" not callable
[builtins fixtures/set.pyi]

[case testUnificationEmptyDictLeft]
def f(): pass
a = {} if f() else {0: 0}
a() # E: "dict[int, int]" not callable
[builtins fixtures/dict.pyi]

[case testUnificationEmptyDictRight]
def f(): pass
a = {0: 0} if f() else {}
a() # E: "dict[int, int]" not callable
[builtins fixtures/dict.pyi]

[case testUnificationDictWithEmptyListLeft]
def f(): pass
a = {0: []} if f() else {0: [0]}
a() # E: "dict[int, list[int]]" not callable
[builtins fixtures/dict.pyi]

[case testUnificationDictWithEmptyListRight]
def f(): pass
a = {0: [0]} if f() else {0: []}
a() # E: "dict[int, list[int]]" not callable
[builtins fixtures/dict.pyi]

[case testMisguidedSetItem]
from typing import Generic, Sequence, TypeVar
T = TypeVar('T')
class C(Sequence[T], Generic[T]): pass
C[0] = 0
[out]
main:4: error: Unsupported target for indexed assignment ("type[C[T]]")
main:4: error: Invalid type: try using Literal[0] instead?

[case testNoCrashOnPartialMember]
# flags: --no-local-partial-types
class C:
    x = None
    def __init__(self) -> None:
        self.x = []  # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
[builtins fixtures/list.pyi]

[case testNoCrashOnPartialVariable]
from typing import Tuple, TypeVar
T = TypeVar('T', bound=str)

def f(x: T) -> Tuple[T]:
    ...
x = None
(x,) = f('')
reveal_type(x) # N: Revealed type is "builtins.str"
[builtins fixtures/tuple.pyi]

[case testNoCrashOnPartialVariable2]
# flags: --no-local-partial-types
from typing import Tuple, TypeVar
T = TypeVar('T', bound=str)

def f() -> Tuple[T]:
    ...
x = None  # E: Need type annotation for "x"
if int():
    (x,) = f()
[builtins fixtures/tuple.pyi]

[case testNoCrashOnPartialVariable3]
from typing import Tuple, TypeVar
T = TypeVar('T')

def f(x: T) -> Tuple[T, T]:
    ...
x = None
(x, x) = f('')
reveal_type(x) # N: Revealed type is "builtins.str"
[builtins fixtures/tuple.pyi]

[case testRejectsPartialWithUninhabited]
from typing import Generic, TypeVar
T = TypeVar('T')

class Foo(Generic[T]): ...

def check() -> None:
    x = None  # E: Need type annotation for "x"
    if int():
        x = Foo()
        reveal_type(x)  # N: Revealed type is "__main__.Foo[Any]"
    reveal_type(x)  # N: Revealed type is "Union[__main__.Foo[Any], None]"

[case testRejectsPartialWithUninhabited2]
from typing import Generic, TypeVar
T = TypeVar('T')

class Foo(Generic[T]): ...

x = None  # E: Need type annotation for "x"

def check() -> None:
    global x
    x = Foo()
    reveal_type(x)  # N: Revealed type is "__main__.Foo[Any]"

reveal_type(x)  # N: Revealed type is "Union[__main__.Foo[Any], None]"

[case testRejectsPartialWithUninhabited3]
# Without force-rejecting Partial<None>, this crashes:
# https://github.com/python/mypy/issues/16573
from typing import Generic, TypeVar
T = TypeVar('T')

class Foo(Generic[T]): ...

def check() -> None:
    client = None  # E: Need type annotation for "client"

    if client := Foo():
        reveal_type(client)  # N: Revealed type is "__main__.Foo[Any]"

    reveal_type(client)  # N: Revealed type is "Union[__main__.Foo[Any], None]"

    client = 0  # E: Incompatible types in assignment (expression has type "int", variable has type "Optional[Foo[Any]]")
    reveal_type(client)  # N: Revealed type is "Union[__main__.Foo[Any], None]"

[case testRejectsPartialWithUninhabitedIndependently]
from typing import Generic, TypeVar
T = TypeVar('T')

class Foo(Generic[T]): ...

client = None  # E: Need type annotation for "client"

def bad() -> None:
    global client
    client = Foo()
    reveal_type(client)  # N: Revealed type is "__main__.Foo[Any]"

def good() -> None:
    global client
    client = 1  # E: Incompatible types in assignment (expression has type "int", variable has type "Optional[Foo[Any]]")
    reveal_type(client)  # N: Revealed type is "Union[__main__.Foo[Any], None]"

def bad2() -> None:
    global client
    client = Foo()
    reveal_type(client)  # N: Revealed type is "__main__.Foo[Any]"

[case testInferenceNestedTuplesFromGenericIterable]
from typing import Tuple, TypeVar

T = TypeVar('T')

def make_tuple(elem: T) -> Tuple[T]:
    return (elem,)

def main() -> None:
    ((a, b),) = make_tuple((1, 2))
    reveal_type(a) # N: Revealed type is "builtins.int"
    reveal_type(b) # N: Revealed type is "builtins.int"
[builtins fixtures/tuple.pyi]

[case testDontMarkUnreachableAfterInferenceUninhabited]
from typing import TypeVar
T = TypeVar('T')
def f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar

class C:
    x = f() # E: Need type annotation for "x"
    def m(self) -> str:
        return 42 # E: Incompatible return value type (got "int", expected "str")

if bool():
    f()
    1() # E: "int" not callable
[builtins fixtures/list.pyi]
[out]

[case testDontMarkUnreachableAfterInferenceUninhabited2]
from typing import TypeVar, Optional
T = TypeVar('T')
def f(x: Optional[T] = None) -> T: pass

class C:
    x = f() # E: Need type annotation for "x"
    def m(self) -> str:
        return 42 # E: Incompatible return value type (got "int", expected "str")

if bool():
    f()
    1() # E: "int" not callable
[builtins fixtures/list.pyi]
[out]

[case testDontMarkUnreachableAfterInferenceUninhabited3]
from typing import TypeVar, List
T = TypeVar('T')
def f(x: List[T]) -> T: pass

class C:
    x = f([]) # E: Need type annotation for "x"
    def m(self) -> str:
        return 42 # E: Incompatible return value type (got "int", expected "str")

if bool():
    f([])
    1() # E: "int" not callable
[builtins fixtures/list.pyi]
[out]


-- --local-partial-types
-- ---------------------


[case testLocalPartialTypesWithGlobalInitializedToNone]
# flags: --local-partial-types
x = None # E: Need type annotation for "x" (hint: "x: Optional[<type>] = ...")

def f() -> None:
    global x
    x = 1

# TODO: "Any" could be a better type here to avoid multiple error messages
reveal_type(x) # N: Revealed type is "None"

[case testLocalPartialTypesWithGlobalInitializedToNone2]
# flags: --local-partial-types
x = None # E: Need type annotation for "x" (hint: "x: Optional[<type>] = ...")

def f():
    global x
    x = 1

# TODO: "Any" could be a better type here to avoid multiple error messages
reveal_type(x) # N: Revealed type is "None"

[case testLocalPartialTypesWithGlobalInitializedToNone3]
# flags: --local-partial-types --no-strict-optional
x = None

def f() -> None:
    global x
    x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "str")

x = ''
reveal_type(x) # N: Revealed type is "builtins.str"

[case testLocalPartialTypesWithGlobalInitializedToNoneStrictOptional]
# flags: --local-partial-types
x = None

def f() -> None:
    global x
    x = 1 # E: Incompatible types in assignment (expression has type "int", variable has type "Optional[str]")

x = ''
def g() -> None:
    reveal_type(x) # N: Revealed type is "Union[builtins.str, None]"

[case testLocalPartialTypesWithGlobalInitializedToNone4]
# flags: --local-partial-types --no-strict-optional
a = None

def f() -> None:
    reveal_type(a)  # N: Revealed type is "builtins.str"

# TODO: This should probably be 'builtins.str', since there could be a
#     call that causes a non-None value to be assigned
reveal_type(a)  # N: Revealed type is "None"
a = ''
reveal_type(a)  # N: Revealed type is "builtins.str"
[builtins fixtures/list.pyi]

[case testLocalPartialTypesWithClassAttributeInitializedToNone]
# flags: --local-partial-types
class A:
    x = None # E: Need type annotation for "x" (hint: "x: Optional[<type>] = ...")

    def f(self) -> None:
        self.x = 1

[case testLocalPartialTypesWithClassAttributeInitializedToEmptyDict]
# flags: --local-partial-types
class A:
    x = {}  # E: Need type annotation for "x" (hint: "x: dict[<type>, <type>] = ...")

    def f(self) -> None:
        self.x[0] = ''

reveal_type(A().x)  # N: Revealed type is "builtins.dict[Any, Any]"
reveal_type(A.x)  # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testLocalPartialTypesWithGlobalInitializedToEmptyList]
# flags: --local-partial-types
a = []

def f() -> None:
    a[0]
    reveal_type(a)  # N: Revealed type is "builtins.list[builtins.int]"

a.append(1)
reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
[builtins fixtures/list.pyi]

[case testLocalPartialTypesWithGlobalInitializedToEmptyList2]
# flags: --local-partial-types
a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")

def f() -> None:
    a.append(1)
    reveal_type(a)  # N: Revealed type is "builtins.list[Any]"

reveal_type(a) # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testLocalPartialTypesWithGlobalInitializedToEmptyList3]
# flags: --local-partial-types
a = [] # E: Need type annotation for "a" (hint: "a: list[<type>] = ...")

def f():
    a.append(1)

reveal_type(a) # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testLocalPartialTypesWithGlobalInitializedToEmptyDict]
# flags: --local-partial-types
a = {}

def f() -> None:
    a[0]
    reveal_type(a)  # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"

a[0] = ''
reveal_type(a) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
[builtins fixtures/dict.pyi]

[case testLocalPartialTypesWithGlobalInitializedToEmptyDict2]
# flags: --local-partial-types
a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")

def f() -> None:
    a[0] = ''
    reveal_type(a)  # N: Revealed type is "builtins.dict[Any, Any]"

reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testLocalPartialTypesWithGlobalInitializedToEmptyDict3]
# flags: --local-partial-types
a = {} # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")

def f():
    a[0] = ''

reveal_type(a) # N: Revealed type is "builtins.dict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testLocalPartialTypesWithNestedFunction]
# flags: --local-partial-types
def f() -> None:
    a = {}
    def g() -> None:
        a[0] = ''
    reveal_type(a) # N: Revealed type is "builtins.dict[builtins.int, builtins.str]"
[builtins fixtures/dict.pyi]

[case testLocalPartialTypesWithNestedFunction2]
# flags: --local-partial-types
def f() -> None:
    a = []
    def g() -> None:
        a.append(1)
    reveal_type(a) # N: Revealed type is "builtins.list[builtins.int]"
[builtins fixtures/list.pyi]

[case testLocalPartialTypesWithNestedFunction3]
# flags: --local-partial-types --no-strict-optional
def f() -> None:
    a = None
    def g() -> None:
        nonlocal a
        a = ''
    reveal_type(a) # N: Revealed type is "builtins.str"
[builtins fixtures/dict.pyi]

[case testLocalPartialTypesWithInheritance]
# flags: --local-partial-types
from typing import Optional

class A:
    x: Optional[str]

class B(A):
    x = None

reveal_type(B.x) # N: Revealed type is "None"

[case testLocalPartialTypesWithInheritance2]
# flags: --local-partial-types
class A:
    x: str

class B(A):
    x = None  # E: Incompatible types in assignment (expression has type "None", base class "A" defined the type as "str")

[case testLocalPartialTypesWithAnyBaseClass]
# flags: --local-partial-types
from typing import Any

A: Any

class B(A):
    x = None

class C(B):
    y = None

[case testLocalPartialTypesInMultipleMroItems]
# flags: --local-partial-types
from typing import Optional

class A:
    x: Optional[str]

class B(A):
    x = None

class C(B):
    x = None

# TODO: Inferring None below is unsafe (https://github.com/python/mypy/issues/3208)
reveal_type(B.x)  # N: Revealed type is "None"
reveal_type(C.x)  # N: Revealed type is "None"

[case testLocalPartialTypesWithInheritance3]
# flags: --local-partial-types
from typing import Optional

class X: pass
class Y(X): pass

class A:
    x: Optional[X]

class B(A):
    x = None
    x = Y()

reveal_type(B.x) # N: Revealed type is "Union[__main__.Y, None]"

[case testLocalPartialTypesBinderSpecialCase]
# flags: --local-partial-types
from typing import List

def f(x): pass

class A:
    x = None  # E: Need type annotation for "x" (hint: "x: Optional[<type>] = ...")

    def f(self, p: List[str]) -> None:
        self.x = f(p)
        f(z for z in p)
[builtins fixtures/list.pyi]

[case testLocalPartialTypesAccessPartialNoneAttribute]
# flags: --local-partial-types
class C:
    a = None  # E: Need type annotation for "a" (hint: "a: Optional[<type>] = ...")

    def f(self, x) -> None:
        C.a.y  # E: Item "None" of "Optional[Any]" has no attribute "y"

[case testLocalPartialTypesAccessPartialNoneAttribute2]
# flags: --local-partial-types
class C:
    a = None  # E: Need type annotation for "a" (hint: "a: Optional[<type>] = ...")

    def f(self, x) -> None:
        self.a.y  # E: Item "None" of "Optional[Any]" has no attribute "y"

-- Special case for assignment to '_'
-- ----------------------------------

[case testUnusedTargetLocal]
def foo() -> None:
    _ = 0
    _ = ''

[case testUnusedTargetNotGlobal]
_ = 0
_ = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")

[case testUnusedTargetNotClass]
# flags: --allow-redefinition
class C:
    _, _ = 0, 0
    _ = ''
reveal_type(C._) # N: Revealed type is "builtins.str"

[case testUnusedTargetNotClass2]
# flags: --disallow-redefinition
class C:
    _, _ = 0, 0
    _ = ''  # E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(C._) # N: Revealed type is "builtins.int"

[case testUnusedTargetTupleUnpacking]
def foo() -> None:
    _, _ = (0, '')
    _ = 0
    _ = ''
def bar() -> None:
    t = (0, '')
    _, _ = t
    _ = 0
    _ = ''
[builtins fixtures/tuple.pyi]

[case testUnusedTargetMultipleTargets]
def foo() -> None:
    _ = x = 0
    _ = y = ''
    _ = 0
    _ = ''
def bar() -> None:
    x = _ = 0
    y = _ = ''
    _ = 0
    _ = ''
    x + 0
    y + ''
    x + ''  # E: Unsupported operand types for + ("int" and "str")
    y + 0  # E: Unsupported operand types for + ("str" and "int")
[builtins fixtures/primitives.pyi]

[case testUnusedTargetNotImport]
import d, c, b, a
[file _.py]
def f(): pass
[file m.py]
def f(): pass
_ = f
_ = 0  # E: Incompatible types in assignment (expression has type "int", variable has type "Callable[[], Any]")
[file a.py]
def foo() -> None:
    import _
    _.f()
    _ = 0  # E: Incompatible types in assignment (expression has type "int", variable has type Module)
[file b.py]
def foo() -> None:
    import m as _
    _.f()
    _ = 0  # E: Incompatible types in assignment (expression has type "int", variable has type Module)
[file c.py]
def foo() -> None:
    from m import _
    _()
    _ = ''  # E: Incompatible types in assignment (expression has type "str", variable has type "Callable[[], Any]")
[file d.py]
def foo() -> None:
    from m import f as _
    _()
    _ = 0  # E: Incompatible types in assignment (expression has type "int", variable has type "Callable[[], Any]")
[builtins fixtures/module.pyi]

[case testUnderscoreClass]
def foo() -> None:
    class _:
        pass
    _().method()  # E: "_" has no attribute "method"

[case testUnusedTargetForLoop]
def f() -> None:
    a = [(0, '', 0)]
    for _, _, x in a:
        x = 0
        x = ''  # E: Incompatible types in assignment (expression has type "str", variable has type "int")
    _ = 0
    _ = ''
[builtins fixtures/list.pyi]

[case testUnusedTargetWithClause]
class C:
    def __enter__(self) -> int: pass
    def __exit__(self, *args): pass
def f() -> None:
    with C() as _: pass
    _ = 0
    _ = ''
[builtins fixtures/tuple.pyi]

[case testUnusedTargetNotExceptClause]
# Things don't work for except clauses.
# This is due to the implementation, but it's just as well.
def f() -> None:
    try: pass
    except BaseException as _:
        _ = 0  # E: Incompatible types in assignment (expression has type "int", variable has type "BaseException")
        _ = ''  # E: Incompatible types in assignment (expression has type "str", variable has type "BaseException")
[builtins fixtures/exception.pyi]

-- Tests for permissive toplevel checking
-- --------------

[case testPermissiveAttributeOverride1]
# flags: --allow-untyped-globals

class A:
    x = None

class B(A):
    x = 12

class C(A):
    x = '12'

reveal_type(A.x) # N: Revealed type is "Union[Any, None]"
reveal_type(B.x) # N: Revealed type is "builtins.int"
reveal_type(C.x) # N: Revealed type is "builtins.str"

[case testPermissiveAttributeOverride2]
# flags: --allow-untyped-globals

class A:
    x = []

class B(A):
    x = [12]

class C(A):
    x = ['12']

reveal_type(A.x) # N: Revealed type is "builtins.list[Any]"
reveal_type(B.x) # N: Revealed type is "builtins.list[builtins.int]"
reveal_type(C.x) # N: Revealed type is "builtins.list[builtins.str]"

[builtins fixtures/list.pyi]

[case testPermissiveAttribute]
# flags: --allow-untyped-globals

class A:
    x = []
    def f(self) -> None:
        reveal_type(self.x)  # N: Revealed type is "builtins.list[Any]"

[builtins fixtures/list.pyi]

[case testPermissiveGlobalContainer1]
# flags: --allow-untyped-globals --local-partial-types

import a

[file b.py]
x = []
y = {}

def foo() -> None:
    reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
    reveal_type(y)  # N: Revealed type is "builtins.dict[Any, Any]"

[file a.py]
from b import x, y
reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
reveal_type(y)  # N: Revealed type is "builtins.dict[Any, Any]"

[builtins fixtures/dict.pyi]

[case testPermissiveGlobalContainer2]
# flags: --allow-untyped-globals

import a

[file b.py]
x = []
y = {}

def foo() -> None:
    reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
    reveal_type(y)  # N: Revealed type is "builtins.dict[Any, Any]"

[file a.py]
from b import x, y
reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
reveal_type(y)  # N: Revealed type is "builtins.dict[Any, Any]"

[builtins fixtures/dict.pyi]

[case testPermissiveGlobalContainer3]
# flags: --allow-untyped-globals --local-partial-types

import a

[file b.py]
x = []
y = {}
z = y


[file a.py]
from b import x, y
reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
reveal_type(y)  # N: Revealed type is "builtins.dict[Any, Any]"

[builtins fixtures/dict.pyi]
[case testPermissiveGlobalContainer4]
# flags: --allow-untyped-globals

import a

[file b.py]
x = []
y = {}
z = y


[file a.py]
from b import x, y
reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
reveal_type(y)  # N: Revealed type is "builtins.dict[Any, Any]"

[builtins fixtures/dict.pyi]

[case testInheritedAttributeNoStrictOptional]
# flags: --no-strict-optional
class A:
    x: str

class B(A):
    x = None
    x = ''
    reveal_type(x)  # N: Revealed type is "builtins.str"

[case testIncompatibleInheritedAttributeNoStrictOptional]
# flags: --no-strict-optional
class A:
    x: str

class B(A):
    x = None
    x = 2  # E: Incompatible types in assignment (expression has type "int", base class "A" defined the type as "str")

[case testInheritedAttributeStrictOptional]
class A:
    x: str

class B(A):
    x = None  # E: Incompatible types in assignment (expression has type "None", base class "A" defined the type as "str")
    x = ''

[case testNeedAnnotationForCallable]
from typing import TypeVar, Optional, Callable

T = TypeVar('T')

def f(x: Optional[T] = None) -> Callable[..., T]: ...

x = f()  # E: Need type annotation for "x"
y = x

[case testDontNeedAnnotationForCallable]
from typing import TypeVar, Optional, Callable, NoReturn

T = TypeVar('T')

def f() -> Callable[..., NoReturn]: ...

x = f()
reveal_type(x)  # N: Revealed type is "def (*Any, **Any) -> Never"

[case testDeferralInNestedScopes]


def g() -> None:
    def f() -> None:
        x + 'no way'  # E: Unsupported operand types for + ("int" and "str")
    x = int()
    f()

[case testDeferralOfMemberNested]
from typing import Tuple

def f() -> None:
    c: C
    t: Tuple[str, Tuple[str, str]]
    x, (y, c.a) = t  # E: Incompatible types in assignment (expression has type "str", variable has type "int")

class C:
    def __init__(self, a: int) -> None:
        self.a = a
[builtins fixtures/tuple.pyi]

[case testUnionGenericWithBoundedVariable]
from typing import Generic, TypeVar, Union

class A: ...
class B(A): ...

T = TypeVar('T', bound=A)
class Z(Generic[T]):
    def __init__(self, y: T) -> None:
        self.y = y

F = TypeVar('F', bound=A)

def q1(x: Union[F, Z[F]]) -> F:
    if isinstance(x, Z):
        return x.y
    else:
        return x

def q2(x: Union[Z[F], F]) -> F:
    if isinstance(x, Z):
        return x.y
    else:
        return x

b: B
reveal_type(q1(b))  # N: Revealed type is "__main__.B"
reveal_type(q2(b))  # N: Revealed type is "__main__.B"

z: Z[B]
reveal_type(q1(z))  # N: Revealed type is "__main__.B"
reveal_type(q2(z))  # N: Revealed type is "__main__.B"

reveal_type(q1(Z(b)))  # N: Revealed type is "__main__.B"
reveal_type(q2(Z(b)))  # N: Revealed type is "__main__.B"
[builtins fixtures/isinstancelist.pyi]

[case testUnionInvariantSubClassAndCovariantBase]
from typing import Union, Generic, TypeVar

T = TypeVar('T')
T_co = TypeVar('T_co', covariant=True)

class Cov(Generic[T_co]): ...
class Inv(Cov[T]): ...

X = Union[Cov[T], Inv[T]]

def f(x: X[T]) -> T: ...
x: Inv[int]
reveal_type(f(x))  # N: Revealed type is "builtins.int"

[case testOptionalTypeVarAgainstOptional]
from typing import Optional, TypeVar, Iterable, Iterator, List

_T = TypeVar('_T')

def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> List[_T]: ...

x: Optional[str]

y = filter(None, [x])
reveal_type(y)  # N: Revealed type is "builtins.list[builtins.str]"
[builtins fixtures/list.pyi]

[case testPartialDefaultDict]
from collections import defaultdict
x = defaultdict(int)
x[''] = 1
reveal_type(x) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.int]"

y = defaultdict(int) # E: Need type annotation for "y"

z = defaultdict(int)  # E: Need type annotation for "z"
z[''] = ''
reveal_type(z) # N: Revealed type is "collections.defaultdict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testPartialDefaultDictInconsistentValueTypes]
from collections import defaultdict
a = defaultdict(int)  # E: Need type annotation for "a"
a[''] = ''
a[''] = 1
reveal_type(a) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.int]"
[builtins fixtures/dict.pyi]

[case testPartialDefaultDictListValue]
# flags: --no-strict-optional
from collections import defaultdict
a = defaultdict(list)
a['x'].append(1)
reveal_type(a) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"

b = defaultdict(lambda: [])
b[1].append('x')
reveal_type(b) # N: Revealed type is "collections.defaultdict[builtins.int, builtins.list[builtins.str]]"
[builtins fixtures/dict.pyi]

[case testPartialDefaultDictListValueStrictOptional]
from collections import defaultdict
a = defaultdict(list)
a['x'].append(1)
reveal_type(a) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"

b = defaultdict(lambda: [])
b[1].append('x')
reveal_type(b) # N: Revealed type is "collections.defaultdict[builtins.int, builtins.list[builtins.str]]"
[builtins fixtures/dict.pyi]

[case testPartialDefaultDictSpecialCases]
from collections import defaultdict
class A:
    def f(self) -> None:
        self.x = defaultdict(list)
        self.x['x'].append(1)
        reveal_type(self.x) # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"
        self.y = defaultdict(list)  # E: Need type annotation for "y"
        s = self
        s.y['x'].append(1)

x = {} # E: Need type annotation for "x" (hint: "x: dict[<type>, <type>] = ...")
x['x'].append(1)

y = defaultdict(list)  # E: Need type annotation for "y"
y[[]].append(1)
[builtins fixtures/dict.pyi]

[case testPartialDefaultDictSpecialCases2]
from collections import defaultdict

x = defaultdict(lambda: [1]) # E: Need type annotation for "x"
x[1].append('') # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
reveal_type(x) # N: Revealed type is "collections.defaultdict[Any, builtins.list[builtins.int]]"

xx = defaultdict(lambda: {'x': 1}) # E: Need type annotation for "xx"
xx[1]['z'] = 3
reveal_type(xx) # N: Revealed type is "collections.defaultdict[Any, builtins.dict[builtins.str, builtins.int]]"

y = defaultdict(dict)  # E: Need type annotation for "y"
y['x'][1] = [3]

z = defaultdict(int) # E: Need type annotation for "z"
z[1].append('')
reveal_type(z) # N: Revealed type is "collections.defaultdict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testPartialDefaultDictSpecialCase3]
from collections import defaultdict

x = defaultdict(list)
x['a'] = [1, 2, 3]
reveal_type(x)  # N: Revealed type is "collections.defaultdict[builtins.str, builtins.list[builtins.int]]"

y = defaultdict(list)  # E: Need type annotation for "y"
y['a'] = []
reveal_type(y)  # N: Revealed type is "collections.defaultdict[Any, Any]"
[builtins fixtures/dict.pyi]

[case testInferCallableReturningNone1]
# flags: --no-strict-optional
from typing import Callable, TypeVar

T = TypeVar("T")

def f(x: Callable[[], T]) -> T:
    return x()

reveal_type(f(lambda: None))  # N: Revealed type is "None"
reveal_type(f(lambda: 1))  # N: Revealed type is "builtins.int"

def g() -> None: pass

reveal_type(f(g))  # N: Revealed type is "None"

[case testInferCallableReturningNone2]
from typing import Callable, TypeVar

T = TypeVar("T")

def f(x: Callable[[], T]) -> T:
    return x()

reveal_type(f(lambda: None))  # N: Revealed type is "None"
reveal_type(f(lambda: 1))  # N: Revealed type is "builtins.int"

def g() -> None: pass

reveal_type(f(g))  # N: Revealed type is "None"

[case testInferredTypeIsSimpleNestedList]
from typing import Any, Union, List

y: Union[List[Any], Any]
x: Union[List[Any], Any]
x = [y]
reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferredTypeIsSimpleNestedIterable]
from typing import Any, Union, Iterable

y: Union[Iterable[Any], Any]
x: Union[Iterable[Any], Any]
x = [y]
reveal_type(x)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferredTypeIsSimpleNestedListLoop]
from typing import Any, Union, List

def test(seq: List[Union[List, Any]]) -> None:
    k: Union[List, Any]
    for k in seq:
        if bool():
            k = [k]
            reveal_type(k)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testInferredTypeIsSimpleNestedIterableLoop]
from typing import Any, Union, List, Iterable

def test(seq: List[Union[Iterable, Any]]) -> None:
    k: Union[Iterable, Any]
    for k in seq:
        if bool():
            k = [k]
            reveal_type(k)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testErasedTypeRuntimeCoverage]
# https://github.com/python/mypy/issues/11913
from typing import TypeVar, Type, Generic, Callable, Iterable

class DataType: ...

T1 = TypeVar('T1')
T2 = TypeVar("T2", bound=DataType)

def map(__func: T1) -> None: ...

def collection_from_dict_value(model: Type[T2]) -> None:
    map(lambda i: i if isinstance(i, model) else i)
[builtins fixtures/isinstancelist.pyi]

[case testRegression11705_Strict]
# See: https://github.com/python/mypy/issues/11705
from typing import Dict, Optional, NamedTuple
class C(NamedTuple):
    x: int

t: Optional[C]
d: Dict[C, bytes]
x = t and d[t]
reveal_type(x)  # N: Revealed type is "Union[None, builtins.bytes]"
if x:
    reveal_type(x)  # N: Revealed type is "builtins.bytes"
[builtins fixtures/dict.pyi]

[case testRegression11705_NoStrict]
# flags: --no-strict-optional
# See: https://github.com/python/mypy/issues/11705
from typing import Dict, Optional, NamedTuple
class C(NamedTuple):
    x: int

t: Optional[C]
d: Dict[C, bytes]
x = t and d[t]
reveal_type(x)  # N: Revealed type is "builtins.bytes"
if x:
    reveal_type(x)  # N: Revealed type is "builtins.bytes"
[builtins fixtures/dict.pyi]

[case testSuggestPep604AnnotationForPartialNone]
# flags: --local-partial-types --python-version 3.10 --no-force-union-syntax
x = None # E: Need type annotation for "x" (hint: "x: <type> | None = ...")

[case testTupleContextFromIterable]
from typing import TypeVar, Iterable, List, Union

T = TypeVar("T")

def foo(x: List[T]) -> List[T]: ...
x: Iterable[List[Union[int, str]]] = (foo([1]), foo(["a"]))
[builtins fixtures/tuple.pyi]

[case testTupleContextFromIterable2]
from typing import Dict, Iterable, Tuple, Union

def foo(x: Union[Tuple[str, Dict[str, int], str], Iterable[object]]) -> None: ...
foo(("a", {"a": "b"}, "b"))
[builtins fixtures/dict.pyi]

[case testUseSupertypeAsInferenceContext]
from typing import List, Optional

class B:
    x: List[Optional[int]]

class C(B):
    x = [1]

reveal_type(C().x)  # N: Revealed type is "builtins.list[Union[builtins.int, None]]"
[builtins fixtures/list.pyi]

[case testUseSupertypeAsInferenceContextInvalidType]
from typing import List
class P:
    x: List[int]
class C(P):
    x = ['a']  # E: List item 0 has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testUseSupertypeAsInferenceContextPartial]
from typing import List

class A:
    x: List[str]

class B(A):
    x = []

reveal_type(B().x)  # N: Revealed type is "builtins.list[builtins.str]"
[builtins fixtures/list.pyi]

[case testUseSupertypeAsInferenceContextPartialError]
class A:
    x = ['a', 'b']

class B(A):
    x = []
    x.append(2)  # E: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"
[builtins fixtures/list.pyi]

[case testUseSupertypeAsInferenceContextPartialErrorProperty]
from typing import List

class P:
    @property
    def x(self) -> List[int]: ...
class C(P):
    x = []

C.x.append("no")  # E: Argument 1 to "append" of "list" has incompatible type "str"; expected "int"
[builtins fixtures/list.pyi]

[case testUseSupertypeAsInferenceContextConflict]
from typing import List
class P:
    x: List[int]
class M:
    x: List[str]
class C(P, M):
    x = []  # E: Need type annotation for "x" (hint: "x: list[<type>] = ...")
reveal_type(C.x)  # N: Revealed type is "builtins.list[Any]"
[builtins fixtures/list.pyi]

[case testNoPartialInSupertypeAsContext]
class A:
    args = {}  # E: Need type annotation for "args" (hint: "args: dict[<type>, <type>] = ...")
    def f(self) -> None:
        value = {1: "Hello"}
        class B(A):
            args = value
[builtins fixtures/dict.pyi]

[case testInferSimpleLiteralInClassBodyCycle]
import a
[file a.py]
import b
reveal_type(b.B.x)
class A:
    x = 42
[file b.py]
import a
reveal_type(a.A.x)
class B:
    x = 42
[out]
tmp/b.py:2: note: Revealed type is "builtins.int"
tmp/a.py:2: note: Revealed type is "builtins.int"

[case testUnionTypeCallableInference]
from typing import Callable, Type, TypeVar, Union

class A:
    def __init__(self, x: str) -> None: ...

T = TypeVar("T")
def type_or_callable(value: T, tp: Union[Type[T], Callable[[int], T]]) -> T: ...
reveal_type(type_or_callable(A("test"), A))  # N: Revealed type is "__main__.A"

[case testUpperBoundAsInferenceFallback]
from typing import Callable, TypeVar, Any, Mapping, Optional
T = TypeVar("T", bound=Mapping[str, Any])
def raises(opts: Optional[T]) -> T: pass
def assertRaises(cb: Callable[..., object]) -> None: pass
assertRaises(raises)  # OK
[builtins fixtures/dict.pyi]

[case testJoinWithAnyFallback]
from unknown import X  # type: ignore[import]

class A: ...
class B(X, A): ...
class C(B): ...
class D(C): ...
class E(D): ...

reveal_type([E(), D()])  # N: Revealed type is "builtins.list[__main__.D]"
reveal_type([D(), E()])  # N: Revealed type is "builtins.list[__main__.D]"

[case testCallableInferenceAgainstCallablePosVsStar]
from typing import TypeVar, Callable, Tuple

T = TypeVar('T')
S = TypeVar('S')

def f(x: Callable[[T, S], None]) -> Tuple[T, S]: ...
def g(*x: int) -> None: ...
reveal_type(f(g))  # N: Revealed type is "tuple[builtins.int, builtins.int]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallableStarVsPos]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T, S]):
    def __call__(self, __x: T, *args: S) -> None: ...

def f(x: Call[T, S]) -> Tuple[T, S]: ...
def g(*x: int) -> None: ...
reveal_type(f(g))  # N: Revealed type is "tuple[builtins.int, builtins.int]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallableNamedVsStar]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T, S]):
    def __call__(self, *, x: T, y: S) -> None: ...

def f(x: Call[T, S]) -> Tuple[T, S]: ...
def g(**kwargs: int) -> None: ...
reveal_type(f(g))  # N: Revealed type is "tuple[builtins.int, builtins.int]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallableStarVsNamed]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T, S]):
    def __call__(self, *, x: T, **kwargs: S) -> None: ...

def f(x: Call[T, S]) -> Tuple[T, S]: ...
def g(**kwargs: int) -> None: pass
reveal_type(f(g))  # N: Revealed type is "tuple[builtins.int, builtins.int]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallableNamedVsNamed]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T, S]):
    def __call__(self, *, x: T, y: S) -> None: ...

def f(x: Call[T, S]) -> Tuple[T, S]: ...

# Note: order of names is different w.r.t. protocol
def g(*, y: int, x: str) -> None: pass
reveal_type(f(g))  # N: Revealed type is "tuple[builtins.str, builtins.int]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallablePosOnlyVsNamed]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T]):
    def __call__(self, *, x: T) -> None: ...

def f(x: Call[T]) -> Tuple[T, T]: ...

def g(__x: str) -> None: pass
reveal_type(f(g))  # N: Revealed type is "tuple[Never, Never]" \
                   # E: Argument 1 to "f" has incompatible type "Callable[[str], None]"; expected "Call[Never]" \
                   # N: "Call[Never].__call__" has type "def __call__(self, *, x: Never) -> None"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallableNamedVsPosOnly]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T]):
    def __call__(self, __x: T) -> None: ...

def f(x: Call[T]) -> Tuple[T, T]: ...

def g(*, x: str) -> None: pass
reveal_type(f(g))  # N: Revealed type is "tuple[Never, Never]" \
                   # E: Argument 1 to "f" has incompatible type "def g(*, x: str) -> None"; expected "Call[Never]" \
                   # N: "Call[Never].__call__" has type "Callable[[Never], None]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallablePosOnlyVsKwargs]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T]):
    def __call__(self, __x: T) -> None: ...

def f(x: Call[T]) -> Tuple[T, T]: ...

def g(**x: str) -> None: pass
reveal_type(f(g))  # N: Revealed type is "tuple[Never, Never]" \
                   # E: Argument 1 to "f" has incompatible type "def g(**x: str) -> None"; expected "Call[Never]" \
                   # N: "Call[Never].__call__" has type "Callable[[Never], None]"
[builtins fixtures/list.pyi]

[case testCallableInferenceAgainstCallableNamedVsArgs]
from typing import TypeVar, Callable, Tuple, Protocol

T = TypeVar('T', contravariant=True)
S = TypeVar('S', contravariant=True)

class Call(Protocol[T]):
    def __call__(self, *, x: T) -> None: ...

def f(x: Call[T]) -> Tuple[T, T]: ...

def g(*args: str) -> None: pass
reveal_type(f(g))  # N: Revealed type is "tuple[Never, Never]" \
                   # E: Argument 1 to "f" has incompatible type "def g(*args: str) -> None"; expected "Call[Never]" \
                   # N: "Call[Never].__call__" has type "def __call__(self, *, x: Never) -> None"
[builtins fixtures/list.pyi]

[case testInferenceAgainstTypeVarActualBound]
from typing import Callable, TypeVar

T = TypeVar("T")
S = TypeVar("S")
def test(f: Callable[[T], S]) -> Callable[[T], S]: ...

F = TypeVar("F", bound=Callable[..., object])
def dec(f: F) -> F:
    reveal_type(test(f))  # N: Revealed type is "def (Any) -> builtins.object"
    return f

[case testInferenceAgainstTypeVarActualUnionBound]
from typing import Protocol, TypeVar, Union

T_co = TypeVar("T_co", covariant=True)
class SupportsFoo(Protocol[T_co]):
    def foo(self) -> T_co: ...

class A:
    def foo(self) -> A: ...
class B:
    def foo(self) -> B: ...

def foo(f: SupportsFoo[T_co]) -> T_co: ...

ABT = TypeVar("ABT", bound=Union[A, B])
def simpler(k: ABT):
    foo(k)

[case testInferenceWorksWithEmptyCollectionsNested]
from typing import List, TypeVar, NoReturn
T = TypeVar('T')
def f(a: List[T], b: List[T]) -> T: pass
x = ["yes"]
reveal_type(f(x, []))  # N: Revealed type is "builtins.str"
reveal_type(f(["yes"], []))  # N: Revealed type is "builtins.str"

empty: List[NoReturn]
f(x, empty)  # E: Cannot infer value of type parameter "T" of "f"
f(["no"], empty)  # E: Cannot infer value of type parameter "T" of "f"
[builtins fixtures/list.pyi]

[case testInferenceWorksWithEmptyCollectionsUnion]
from typing import Any, Dict, NoReturn, NoReturn, Union

def foo() -> Union[Dict[str, Any], Dict[int, Any]]:
    return {}
[builtins fixtures/dict.pyi]

[case testExistingEmptyCollectionDoesNotUpcast]
from typing import Any, Dict, NoReturn, NoReturn, Union

empty: Dict[NoReturn, NoReturn]

def foo() -> Dict[str, Any]:
    return empty  # E: Incompatible return value type (got "dict[Never, Never]", expected "dict[str, Any]")

def bar() -> Union[Dict[str, Any], Dict[int, Any]]:
    return empty  # E: Incompatible return value type (got "dict[Never, Never]", expected "Union[dict[str, Any], dict[int, Any]]")
[builtins fixtures/dict.pyi]

[case testUpperBoundInferenceFallbackNotOverused]
from typing import TypeVar, Protocol, List

S = TypeVar("S", covariant=True)
class Foo(Protocol[S]):
    def foo(self) -> S: ...
def foo(x: Foo[S]) -> S: ...

T = TypeVar("T", bound="Base")
class Base:
    def foo(self: T) -> T: ...
class C(Base):
    pass

def f(values: List[T]) -> T: ...
x = foo(f([C()]))
reveal_type(x)  # N: Revealed type is "__main__.C"
[builtins fixtures/list.pyi]

[case testInferenceAgainstGenericCallableUnion]
from typing import Callable, TypeVar, List, Union

T = TypeVar("T")
S = TypeVar("S")

def dec(f: Callable[[S], T]) -> Callable[[S], List[T]]: ...
@dec
def func(arg: T) -> Union[T, str]:
    ...
reveal_type(func)  # N: Revealed type is "def [S] (S`1) -> builtins.list[Union[S`1, builtins.str]]"
reveal_type(func(42))  # N: Revealed type is "builtins.list[Union[builtins.int, builtins.str]]"

def dec2(f: Callable[[S], List[T]]) -> Callable[[S], T]: ...
@dec2
def func2(arg: T) -> List[Union[T, str]]:
    ...
reveal_type(func2)  # N: Revealed type is "def [S] (S`4) -> Union[S`4, builtins.str]"
reveal_type(func2(42))  # N: Revealed type is "Union[builtins.int, builtins.str]"
[builtins fixtures/list.pyi]

[case testInferenceAgainstGenericCallbackProtoMultiple]
from typing import Callable, Protocol, TypeVar
from typing_extensions import Concatenate, ParamSpec

V_co = TypeVar("V_co", covariant=True)
class Metric(Protocol[V_co]):
    def __call__(self) -> V_co: ...

T = TypeVar("T")
P = ParamSpec("P")
def simple_metric(func: Callable[Concatenate[int, P], T]) -> Callable[P, T]: ...

@simple_metric
def Negate(count: int, /, metric: Metric[float]) -> float: ...
@simple_metric
def Combine(count: int, m1: Metric[T], m2: Metric[T], /, *more: Metric[T]) -> T: ...

reveal_type(Negate)  # N: Revealed type is "def (metric: __main__.Metric[builtins.float]) -> builtins.float"
reveal_type(Combine)  # N: Revealed type is "def [T] (def () -> T`5, def () -> T`5, *more: def () -> T`5) -> T`5"

def m1() -> float: ...
def m2() -> float: ...
reveal_type(Combine(m1, m2))  # N: Revealed type is "builtins.float"
[builtins fixtures/list.pyi]

[case testInferenceWithUninhabitedType]
from typing import Dict, Generic, List, Never, TypeVar

T = TypeVar("T")

class A(Generic[T]): ...
class B(Dict[T, T]): ...

def func1(a: A[T], b: T) -> T: ...
def func2(a: T, b: A[T]) -> T: ...

def a1(a: A[Dict[str, int]]) -> None:
    reveal_type(func1(a, {}))  # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"
    reveal_type(func2({}, a))  # N: Revealed type is "builtins.dict[builtins.str, builtins.int]"

def a2(check: bool, a: B[str]) -> None:
    reveal_type(a if check else {})  # N: Revealed type is "builtins.dict[builtins.str, builtins.str]"

def a3() -> None:
    a = {}  # E: Need type annotation for "a" (hint: "a: dict[<type>, <type>] = ...")
    b = {1: {}}  # E: Need type annotation for "b"
    c = {1: {}, 2: {"key": {}}}  # E: Need type annotation for "c"
    reveal_type(a)  # N: Revealed type is "builtins.dict[Any, Any]"
    reveal_type(b)  # N: Revealed type is "builtins.dict[builtins.int, builtins.dict[Any, Any]]"
    reveal_type(c)  # N: Revealed type is "builtins.dict[builtins.int, builtins.dict[builtins.str, builtins.dict[Any, Any]]]"

def a4(x: List[str], y: List[Never]) -> None:
    z1 = [x, y]
    z2 = [y, x]
    reveal_type(z1)  # N: Revealed type is "builtins.list[builtins.object]"
    reveal_type(z2)  # N: Revealed type is "builtins.list[builtins.object]"
    z1[1].append("asdf")  # E: "object" has no attribute "append"
[builtins fixtures/dict.pyi]


[case testDeterminismCommutativityWithJoinInvolvingProtocolBaseAndPromotableType]
# flags: --python-version 3.11
# Regression test for https://github.com/python/mypy/issues/16979#issuecomment-1982246306
from __future__ import annotations

from typing import Any, Generic, Protocol, TypeVar, overload, cast
from typing_extensions import Never

T = TypeVar("T")
U = TypeVar("U")

class _SupportsCompare(Protocol):
    def __lt__(self, other: Any, /) -> bool:
        return True

class Comparable(_SupportsCompare):
    pass

comparable: Comparable = Comparable()

from typing import _promote

class floatlike:
    def __lt__(self, other: floatlike, /) -> bool: ...

@_promote(floatlike)
class intlike:
    def __lt__(self, other: intlike, /) -> bool: ...


class A(Generic[T, U]):
    @overload
    def __init__(self: A[T, T], a: T, b: T, /) -> None: ...  # type: ignore[overload-overlap]
    @overload
    def __init__(self: A[T, U], a: T, b: U, /) -> Never: ...
    def __init__(self, *a) -> None: ...

def join(a: T, b: T) -> T: ...

reveal_type(join(intlike(), comparable))  # N: Revealed type is "__main__._SupportsCompare"
reveal_type(join(comparable, intlike()))  # N: Revealed type is "__main__._SupportsCompare"
reveal_type(A(intlike(), comparable))  # N: Revealed type is "__main__.A[__main__._SupportsCompare, __main__._SupportsCompare]"
reveal_type(A(comparable, intlike()))  # N: Revealed type is "__main__.A[__main__._SupportsCompare, __main__._SupportsCompare]"
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-medium.pyi]

[case testTupleJoinFallbackInference]
foo = [
    (1, ("a", "b")),
    (2, []),
]
reveal_type(foo)  # N: Revealed type is "builtins.list[tuple[builtins.int, typing.Sequence[builtins.str]]]"
[builtins fixtures/tuple.pyi]

[case testForLoopIndexVaribaleNarrowing1]
# flags: --local-partial-types
from typing import Union
x: Union[int, str]
x = "abc"
for x in list[int]():
    reveal_type(x)  # N: Revealed type is "builtins.int"
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str]"

[case testForLoopIndexVaribaleNarrowing2]
# flags: --enable-error-code=redundant-expr
from typing import Union
x: Union[int, str]
x = "abc"
for x in list[int]():
    reveal_type(x)  # N: Revealed type is "builtins.int"
reveal_type(x) # N: Revealed type is "Union[builtins.int, builtins.str]"

[case testNarrowInFunctionDefer]
from typing import Optional, Callable, TypeVar

def top() -> None:
    x: Optional[int]
    assert x is not None

    def foo() -> None:
        defer()
        reveal_type(x)  # N: Revealed type is "builtins.int"

T = TypeVar("T")
def deco(fn: Callable[[], T]) -> Callable[[], T]: ...

@deco
def defer() -> int: ...

[case testDeferMethodOfNestedClass]
from typing import Optional, Callable, TypeVar

class Out:
    def meth(self) -> None:
        class In:
            def meth(self) -> None:
                reveal_type(defer())  # N: Revealed type is "builtins.int"

T = TypeVar("T")
def deco(fn: Callable[[], T]) -> Callable[[], T]: ...

@deco
def defer() -> int: ...

[case testVariableDeferredWithNestedFunction]
from typing import Callable, TypeVar

T = TypeVar("T")
def deco(fn: Callable[[], T]) -> Callable[[], T]: ...

@deco
def f() -> None:
    x = 1
    f()  # defer current node
    x = x

    def nested() -> None:
        ...

    # The type below should not be Any.
    reveal_type(x)  # N: Revealed type is "builtins.int"

[case testInferenceMappingTypeVarGet]
from typing import Generic, TypeVar, Union

_T = TypeVar("_T")
_K = TypeVar("_K")
_V = TypeVar("_V")

class Mapping(Generic[_K, _V]):
    def get(self, key: _K, default: Union[_V, _T]) -> Union[_V, _T]: ...

def check(mapping: Mapping[str, _T]) -> None:
    ok1 = mapping.get("", "")
    reveal_type(ok1)  # N: Revealed type is "Union[_T`-1, builtins.str]"
    ok2: Union[_T, str] = mapping.get("", "")
[builtins fixtures/tuple.pyi]

[case testInferWalrusAssignmentAttrInCondition]
class Foo:
    def __init__(self, value: bool) -> None:
        self.value = value

def check_and(maybe: bool) -> None:
    foo = None
    if maybe and (foo := Foo(True)).value:
        reveal_type(foo)  # N: Revealed type is "__main__.Foo"
    else:
        reveal_type(foo)  # N: Revealed type is "Union[__main__.Foo, None]"

def check_and_nested(maybe: bool) -> None:
    foo = None
    bar = None
    baz = None
    if maybe and (foo := (bar := (baz := Foo(True)))).value:
        reveal_type(foo)  # N: Revealed type is "__main__.Foo"
        reveal_type(bar)  # N: Revealed type is "__main__.Foo"
        reveal_type(baz)  # N: Revealed type is "__main__.Foo"
    else:
        reveal_type(foo)  # N: Revealed type is "Union[__main__.Foo, None]"
        reveal_type(bar)  # N: Revealed type is "Union[__main__.Foo, None]"
        reveal_type(baz)  # N: Revealed type is "Union[__main__.Foo, None]"

def check_or(maybe: bool) -> None:
    foo = None
    if maybe or (foo := Foo(True)).value:
        reveal_type(foo)  # N: Revealed type is "Union[__main__.Foo, None]"
    else:
        reveal_type(foo)  # N: Revealed type is "__main__.Foo"

def check_or_nested(maybe: bool) -> None:
    foo = None
    bar = None
    baz = None
    if maybe and (foo := (bar := (baz := Foo(True)))).value:
        reveal_type(foo)  # N: Revealed type is "__main__.Foo"
        reveal_type(bar)  # N: Revealed type is "__main__.Foo"
        reveal_type(baz)  # N: Revealed type is "__main__.Foo"
    else:
        reveal_type(foo)  # N: Revealed type is "Union[__main__.Foo, None]"
        reveal_type(bar)  # N: Revealed type is "Union[__main__.Foo, None]"
        reveal_type(baz)  # N: Revealed type is "Union[__main__.Foo, None]"

[case testInferWalrusAssignmentIndexInCondition]
def check_and(maybe: bool) -> None:
    foo = None
    bar = None
    if maybe and (foo := [1])[(bar := 0)]:
        reveal_type(foo)  # N: Revealed type is "builtins.list[builtins.int]"
        reveal_type(bar)  # N: Revealed type is "builtins.int"
    else:
        reveal_type(foo)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
        reveal_type(bar)  # N: Revealed type is "Union[builtins.int, None]"

def check_and_nested(maybe: bool) -> None:
    foo = None
    bar = None
    baz = None
    if maybe and (foo := (bar := (baz := [1])))[0]:
        reveal_type(foo)  # N: Revealed type is "builtins.list[builtins.int]"
        reveal_type(bar)  # N: Revealed type is "builtins.list[builtins.int]"
        reveal_type(baz)  # N: Revealed type is "builtins.list[builtins.int]"
    else:
        reveal_type(foo)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
        reveal_type(bar)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
        reveal_type(baz)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"

def check_or(maybe: bool) -> None:
    foo = None
    bar = None
    if maybe or (foo := [1])[(bar := 0)]:
        reveal_type(foo)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
        reveal_type(bar)  # N: Revealed type is "Union[builtins.int, None]"
    else:
        reveal_type(foo)  # N: Revealed type is "builtins.list[builtins.int]"
        reveal_type(bar)  # N: Revealed type is "builtins.int"

def check_or_nested(maybe: bool) -> None:
    foo = None
    bar = None
    baz = None
    if maybe or (foo := (bar := (baz := [1])))[0]:
        reveal_type(foo)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
        reveal_type(bar)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
        reveal_type(baz)  # N: Revealed type is "Union[builtins.list[builtins.int], None]"
    else:
        reveal_type(foo)  # N: Revealed type is "builtins.list[builtins.int]"
        reveal_type(bar)  # N: Revealed type is "builtins.list[builtins.int]"
        reveal_type(baz)  # N: Revealed type is "builtins.list[builtins.int]"

[case testInferOptionalAgainstAny]
from typing import Any, Optional, TypeVar

a: Any
oa: Optional[Any]
T = TypeVar("T")
def f(x: Optional[T]) -> T: ...
reveal_type(f(a))  # N: Revealed type is "Any"
reveal_type(f(oa))  # N: Revealed type is "Any"

[case testNoCrashOnPartialTypeAsContext]
from typing import overload, TypeVar, Optional, Protocol

T = TypeVar("T")
class DbManager(Protocol):
    @overload
    def get(self, key: str) -> Optional[T]:
        pass

    @overload
    def get(self, key: str, default: T) -> T:
        pass

class Foo:
    def __init__(self, db: DbManager, bar: bool) -> None:
        if bar:
            self.qux = db.get("qux")
        else:
            self.qux = {}  # E: Need type annotation for "qux" (hint: "qux: dict[<type>, <type>] = ...")
[builtins fixtures/dict.pyi]

[case testConstraintSolvingFailureShowsCorrectArgument]
from typing import Callable, TypeVar

T1 = TypeVar('T1')
T2 = TypeVar('T2')
def foo(
    a: T1,
    b: T2,
    c: Callable[[T2], T2],
) -> tuple[T1, T2]: ...

def bar(y: float) -> float: ...

foo(1, None, bar)  # E: Cannot infer value of type parameter "T2" of "foo"
[builtins fixtures/tuple.pyi]