File: check-functions.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 (3710 lines) | stat: -rw-r--r-- 101,196 bytes parent folder | download | duplicates (4)
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
-- Test cases for the type checker related to functions, function types and
-- calls.

-- See also check-varargs.test.


-- Callable type basics
-- --------------------


[case testCallingVariableWithFunctionType]
from typing import Callable
f: Callable[[A], B]
a: A
b: B
if int():
    a = f(a)    # E: Incompatible types in assignment (expression has type "B", variable has type "A")
if int():
    b = f(b)    # E: Argument 1 has incompatible type "B"; expected "A"
if int():
    b = f()     # E: Too few arguments
if int():
    b = f(a, a) # E: Too many arguments
if int():
    b = f(a)

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

[case testKeywordOnlyArgumentOrderInsensitivity]
import typing

class A(object):
    def f(self, *, a: int, b: str) -> None: pass

class B(A):
    def f(self, *, b: str, a: int) -> None: pass

class C(A):
    def f(self, *, b: int, a: str) -> None: pass  # Fail
[out]
main:10: error: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "str"
main:10: note: This violates the Liskov substitution principle
main:10: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
main:10: error: Argument 2 of "f" is incompatible with supertype "A"; supertype defines the argument type as "int"

[case testPositionalOverridingArgumentNameInsensitivity]
import typing

class A(object):
    def f(self, a: int, b: str) -> None: pass

class B(A):
    def f(self, b: str, a: int) -> None: pass # E: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "int" \
                                              # N: This violates the Liskov substitution principle \
                                              # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides \
                                              # E: Argument 2 of "f" is incompatible with supertype "A"; supertype defines the argument type as "str"

class C(A):
    def f(self, foo: int, bar: str) -> None: pass


[case testPositionalOverridingArgumentNamesCheckedWhenMismatchingPos]
import typing

class A(object):
    def f(self, a: int, b: str) -> None: pass

class B(A):
    def f(self, b: int, a: str) -> None: pass  # Fail
[out]
main:7: error: Signature of "f" incompatible with supertype "A"
main:7: note:      Superclass:
main:7: note:          def f(self, a: int, b: str) -> None
main:7: note:      Subclass:
main:7: note:          def f(self, b: int, a: str) -> None

[case testSubtypingFunctionTypes]
from typing import Callable

class A: pass
class B(A): pass

f: Callable[[B], A]
g: Callable[[A], A]  # subtype of f
h: Callable[[B], B]  # subtype of f
if int():
    g = h  # E: Incompatible types in assignment (expression has type "Callable[[B], B]", variable has type "Callable[[A], A]")
if int():
    h = f  # E: Incompatible types in assignment (expression has type "Callable[[B], A]", variable has type "Callable[[B], B]")
if int():
    h = g  # E: Incompatible types in assignment (expression has type "Callable[[A], A]", variable has type "Callable[[B], B]")
if int():
    g = f  # E: Incompatible types in assignment (expression has type "Callable[[B], A]", variable has type "Callable[[A], A]")
if int():
    f = g
if int():
    f = h
if int():
    f = f
if int():
    g = g
if int():
    h = h

[case testSubtypingFunctionsDoubleCorrespondence]
def l(x) -> None: ...
def r(__x, *, x) -> None: ...
r = l  # E: Incompatible types in assignment (expression has type "Callable[[Any], None]", variable has type "def r(Any, /, *, x: Any) -> None")

[case testSubtypingFunctionsDoubleCorrespondenceNamedOptional]
def l(x) -> None: ...
def r(__x, *, x = 1) -> None: ...
r = l  # E: Incompatible types in assignment (expression has type "Callable[[Any], None]", variable has type "def r(Any, /, *, x: Any = ...) -> None")

[case testSubtypingFunctionsDoubleCorrespondenceBothNamedOptional]
def l(x = 1) -> None: ...
def r(__x, *, x = 1) -> None: ...
r = l  # E: Incompatible types in assignment (expression has type "Callable[[Any], None]", variable has type "def r(Any, /, *, x: Any = ...) -> None")

[case testSubtypingFunctionsTrivialSuffixRequired]
def l(__x) -> None: ...
def r(x, *args, **kwargs) -> None: ...

r = l  # E: Incompatible types in assignment (expression has type "Callable[[Any], None]", variable has type "def r(x: Any, *args: Any, **kwargs: Any) -> None")
[builtins fixtures/dict.pyi]

[case testSubtypingFunctionsTrivialSuffixOptional]
def l(__x = 1) -> None: ...
def r(x = 1, *args, **kwargs) -> None: ...

r = l  # E: Incompatible types in assignment (expression has type "def l(Any = ..., /) -> None", variable has type "def r(x: Any = ..., *args: Any, **kwargs: Any) -> None")
[builtins fixtures/dict.pyi]

[case testSubtypingFunctionsRequiredLeftArgNotPresent]
def l(x, y) -> None: ...
def r(x) -> None: ...
r = l  # E: Incompatible types in assignment (expression has type "Callable[[Any, Any], None]", variable has type "Callable[[Any], None]")

[case testSubtypingFunctionsImplicitNames]
from typing import Any

def f(a, b): pass
def g(c: Any, d: Any) -> Any: pass

ff = f
gg = g

gg = f
ff = g

[case testSubtypingFunctionsDefaultsNames]
from typing import Callable

def f(a: int, b: str) -> None: pass
f_nonames: Callable[[int, str], None]
def g(a: int, b: str = "") -> None: pass
def h(aa: int, b: str = "") -> None: pass

ff_nonames = f_nonames
ff = f
gg = g
hh = h

if int():
    ff = gg
if int():
    ff_nonames = ff
if int():
    ff_nonames = f_nonames # reset
if int():
    ff = ff_nonames # E: Incompatible types in assignment (expression has type "Callable[[int, str], None]", variable has type "def f(a: int, b: str) -> None")
if int():
    ff = f # reset
if int():
    gg = ff # E: Incompatible types in assignment (expression has type "def f(a: int, b: str) -> None", variable has type "def g(a: int, b: str = ...) -> None")
if int():
    gg = hh # E: Incompatible types in assignment (expression has type "def h(aa: int, b: str = ...) -> None", variable has type "def g(a: int, b: str = ...) -> None")

[case testSubtypingFunctionsArgsKwargs]
from typing import Any, Callable

def everything(*args: Any, **kwargs: Any) -> None: pass
everywhere: Callable[..., None]

def specific_1(a: int, b: str) -> None: pass
def specific_2(a: int, *, b: str) -> None: pass

ss_1 = specific_1
ss_2 = specific_2
ee_def = everything
ee_var = everywhere

if int():
    ss_1 = ee_def
if int():
    ss_1 = specific_1
if int():
    ss_2 = ee_def
if int():
    ss_2 = specific_2
if int():
    ee_def = everywhere
if int():
    ee_def = everything
if int():
    ee_var = everything
if int():
    ee_var = everywhere

if int():
    ee_var = specific_1
if int():
    ee_def = specific_1

[builtins fixtures/dict.pyi]

[case testSubtypingFunctionsDecorated]
from typing import Any

# untyped decorator
def deco(f): pass

class A:
    @deco
    def f(self) -> Any:
        pass

class B(A):
    @deco
    def f(self) -> Any:
        pass

[builtins fixtures/list.pyi]


[case testLackOfNames]
def f(__a: int, __b: str) -> None: pass
def g(a: int, b: str) -> None: pass

ff = f
gg = g

if int():
    ff = g
if int():
    gg = f # E: Incompatible types in assignment (expression has type "Callable[[int, str], None]", variable has type "def g(a: int, b: str) -> None")

[case testLackOfNamesFastparse]
def f(__a: int, __b: str) -> None: pass
def g(a: int, b: str) -> None: pass

ff = f
gg = g

if int():
    ff = g
if int():
    gg = f # E: Incompatible types in assignment (expression has type "Callable[[int, str], None]", variable has type "def g(a: int, b: str) -> None")

[case testFunctionTypeCompatibilityWithOtherTypes]
# flags: --no-strict-optional
from typing import Callable
f = None # type: Callable[[], None]
a, o = None, None # type: (A, object)
if int():
    a = f   # E: Incompatible types in assignment (expression has type "Callable[[], None]", variable has type "A")
if int():
    f = a   # E: Incompatible types in assignment (expression has type "A", variable has type "Callable[[], None]")
if int():
    f = o   # E: Incompatible types in assignment (expression has type "object", variable has type "Callable[[], None]")
if int():
    f = f() # E: Function does not return a value (it only ever returns None)

if int():
    f = f
if int():
    f = None
if int():
    o = f

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

[case testReturnEmptyTuple]
from typing import Tuple
def f(x): # type: (int) -> () # E: Syntax error in type annotation \
                              # N: Suggestion: Use Tuple[()] instead of () for an empty tuple, or None for a function without a return value
   pass

def g(x: int) -> Tuple[()]:
   pass
[builtins fixtures/tuple.pyi]

[case testFunctionSubtypingWithVoid]
from typing import Callable
f: Callable[[], None]
g: Callable[[], object]
if int():
    f = g  # E: Incompatible types in assignment (expression has type "Callable[[], object]", variable has type "Callable[[], None]")
if int():
    g = f  # OK

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

[case testFunctionSubtypingWithMultipleArgs]
from typing import Callable
f: Callable[[A, A], None]
g: Callable[[A, B], None]
h: Callable[[B, B], None]
if int():
    f = g  # E: Incompatible types in assignment (expression has type "Callable[[A, B], None]", variable has type "Callable[[A, A], None]")
if int():
    f = h  # E: Incompatible types in assignment (expression has type "Callable[[B, B], None]", variable has type "Callable[[A, A], None]")
if int():
    g = h  # E: Incompatible types in assignment (expression has type "Callable[[B, B], None]", variable has type "Callable[[A, B], None]")
if int():
    g = f
if int():
    h = f
if int():
    h = g
if int():
    f = f
if int():
    g = g
if int():
    h = h

class A: pass
class B(A): pass

[case testFunctionTypesWithDifferentArgumentCounts]
from typing import Callable
f: Callable[[], None]
g: Callable[[A], None]
h: Callable[[A, A], None]

if int():
    f = g   # E: Incompatible types in assignment (expression has type "Callable[[A], None]", variable has type "Callable[[], None]")
if int():
    f = h   # E: Incompatible types in assignment (expression has type "Callable[[A, A], None]", variable has type "Callable[[], None]")
if int():
    h = f   # E: Incompatible types in assignment (expression has type "Callable[[], None]", variable has type "Callable[[A, A], None]")
if int():
    h = g   # E: Incompatible types in assignment (expression has type "Callable[[A], None]", variable has type "Callable[[A, A], None]")

if int():
    f = f
if int():
    g = g
if int():
    h = h

class A: pass
[out]

[case testCompatibilityOfSimpleTypeObjectWithStdType]
class A:
    def __init__(self, a: 'A') -> None: pass

def f() -> None: pass

t: type
a: A

if int():
    a = A # E: Incompatible types in assignment (expression has type "type[A]", variable has type "A")
if int():
    t = f # E: Incompatible types in assignment (expression has type "Callable[[], None]", variable has type "type")
if int():
    t = A

[case testFunctionTypesWithOverloads]
from foo import *
[file foo.pyi]
from typing import Callable, overload
f: Callable[[AA], A]
g: Callable[[B], B]
h: Callable[[A], AA]

if int():
    h = i  # E: Incompatible types in assignment (expression has type overloaded function, variable has type "Callable[[A], AA]")
if int():
    f = j

if int():
    f = i
if int():
    g = i
if int():
    g = j

class A: pass
class AA(A): pass

class B: pass

@overload
def i(x: AA) -> A:
    pass
@overload
def i(x: B) -> B:
    pass

@overload
def j(x: B) -> B:
    pass
@overload
def j(x: A) -> AA:
    pass

[case testOverloadWithThreeItems]
from foo import *
[file foo.pyi]
from typing import Callable, overload
g1: Callable[[A], A]
g2: Callable[[B], B]
g3: Callable[[C], C]
g4: Callable[[A], B]
a: A
b: B
c: C

if int():
    b = f(a)  # E: Incompatible types in assignment (expression has type "A", variable has type "B")
if int():
    a = f(b)  # E: Incompatible types in assignment (expression has type "B", variable has type "A")
if int():
    b = f(c)  # E: Incompatible types in assignment (expression has type "C", variable has type "B")
if int():
    g4 = f    # E: Incompatible types in assignment (expression has type overloaded function, variable has type "Callable[[A], B]")

if int():
    g1 = f
if int():
    g2 = f
if int():
    g3 = f
if int():
    a = f(a)
if int():
    b = f(b)
if int():
    c = f(c)

class A: pass
class B: pass
class C: pass

@overload
def f(x: A) -> A: pass
@overload
def f(x: B) -> B: pass
@overload
def f(x: C) -> C: pass
[builtins fixtures/tuple.pyi]

[case testInferConstraintsUnequalLengths]
from typing import Any, Callable, List
def f(fields: List[Callable[[Any], Any]]): pass
class C: pass
f([C])  # E: List item 0 has incompatible type "type[C]"; expected "Callable[[Any], Any]"
class D:
    def __init__(self, a, b): pass
f([D])  # E: List item 0 has incompatible type "type[D]"; expected "Callable[[Any], Any]"
[builtins fixtures/list.pyi]

[case testSubtypingTypeTypeAsCallable]
from typing import Callable, Type
class A: pass
x: Callable[..., A]
y: Type[A]
x = y

[case testSubtypingCallableAsTypeType]
from typing import Callable, Type
class A: pass
x: Callable[..., A]
y: Type[A]
if int():
    y = x  # E: Incompatible types in assignment (expression has type "Callable[..., A]", variable has type "type[A]")

-- Default argument values
-- -----------------------


[case testCallingFunctionsWithDefaultArgumentValues]
# flags: --implicit-optional --no-strict-optional
class A: pass
class AA(A): pass
class B: pass

def f(x: 'A'  =  None) -> 'B': pass

a, b = None, None # type: (A, B)
if int():
    a = f()     # E: Incompatible types in assignment (expression has type "B", variable has type "A")
if int():
    b = f(b)    # E: Argument 1 to "f" has incompatible type "B"; expected "Optional[A]"
if int():
    b = f(a, a) # E: Too many arguments for "f"

if int():
    b = f()
if int():
    b = f(a)
if int():
    b = f(AA())

[builtins fixtures/tuple.pyi]

[case testDefaultArgumentExpressions]
import typing
class B: pass
class A: pass

def f(x: 'A' = A()) -> None:
    b = x # type: B # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    a = x # type: A
[out]

[case testDefaultArgumentExpressions2]
import typing
class B: pass
class A: pass

def f(x: 'A' = B()) -> None: # E: Incompatible default for argument "x" (default has type "B", argument has type "A")
    b = x # type: B      # E: Incompatible types in assignment (expression has type "A", variable has type "B")
    a = x # type: A
[case testDefaultArgumentExpressionsGeneric]
from typing import TypeVar
T = TypeVar('T', bound='A')

class B: pass
class A: pass

def f(x: T = B()) -> None: # E: Incompatible default for argument "x" (default has type "B", argument has type "T")
    b = x # type: B      # E: Incompatible types in assignment (expression has type "T", variable has type "B")
    a = x # type: A
[case testDefaultArgumentsWithSubtypes]
import typing
class A: pass
class B(A): pass

def f(x: 'B' = A()) -> None: # E: Incompatible default for argument "x" (default has type "A", argument has type "B")
    pass
def g(x: 'A' = B()) -> None:
    pass
[out]

[case testMultipleDefaultArgumentExpressions]
import typing
class A: pass
class B: pass

def f(x: 'A' = B(), y: 'B' = B()) -> None: # E: Incompatible default for argument "x" (default has type "B", argument has type "A")
    pass
def h(x: 'A' = A(), y: 'B' = B()) -> None:
    pass
[out]

[case testMultipleDefaultArgumentExpressions2]
import typing
class A: pass
class B: pass

def g(x: 'A' = A(), y: 'B' = A()) -> None: # E: Incompatible default for argument "y" (default has type "A", argument has type "B")
    pass
[out]

[case testDefaultArgumentsAndSignatureAsComment]
import typing
def f(x = 1): # type: (int) -> str
    pass
f()
f(1)
f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int"

[case testMethodDefaultArgumentsAndSignatureAsComment]
import typing
class A:
    def f(self, x = 1): # type: (int) -> str
        pass
A().f()
A().f(1)
A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"


-- Access to method defined as a data attribute
-- --------------------------------------------


[case testMethodAsDataAttribute]
from typing import Any, Callable, ClassVar
class B: pass
x: Any
class A:
    f = x # type: ClassVar[Callable[[A], None]]
    g = x # type: ClassVar[Callable[[A, B], None]]
a: A
a.f()
a.g(B())
a.f(a) # E: Too many arguments
a.g()  # E: Too few arguments

[case testMethodWithInvalidMethodAsDataAttribute]
from typing import Any, Callable, ClassVar
class B: pass
x: Any
class A:
    f = x # type: ClassVar[Callable[[], None]]
    g = x # type: ClassVar[Callable[[B], None]]
a: A
a.f() # E: Attribute function "f" with type "Callable[[], None]" does not accept self argument
a.g() # E: Invalid self argument "A" to attribute function "g" with type "Callable[[B], None]"

[case testMethodWithDynamicallyTypedMethodAsDataAttribute]
from typing import Any, Callable, ClassVar
class B: pass
x: Any
class A:
    f = x # type: ClassVar[Callable[[Any], Any]]
a: A
a.f()
a.f(a) # E: Too many arguments

[case testMethodWithInferredMethodAsDataAttribute]
from typing import Any
def m(self: "A") -> int: ...

class A:
    n = m

a = A()
reveal_type(a.n())  # N: Revealed type is "builtins.int"
reveal_type(A.n(a))  # N: Revealed type is "builtins.int"
A.n()  # E: Too few arguments

[case testOverloadedMethodAsDataAttribute]
from foo import *
[file foo.pyi]
from typing import overload
class B: pass
class A:
    @overload
    def f(self) -> None: pass
    @overload
    def f(self, b: B) -> None: pass
    g = f
a: A
a.g()
a.g(B())
a.g(a) # E: No overload variant matches argument type "A" \
       # N: Possible overload variants: \
       # N:     def f(self) -> None \
       # N:     def f(self, b: B) -> None

[case testMethodAsDataAttributeInferredFromDynamicallyTypedMethod]

class A:
    def f(self, x): pass
    g = f
a: A
a.g(object())
a.g(a, a) # E: Too many arguments
a.g()     # E: Too few arguments

[case testMethodAsDataAttributeInGenericClass]
from typing import TypeVar, Generic
t = TypeVar('t')
class B: pass
class A(Generic[t]):
    def f(self, x: t) -> None: pass
    g = f
a: A[B]
a.g(B())
a.g(a)   # E: Argument 1 has incompatible type "A[B]"; expected "B"

[case testInvalidMethodAsDataAttributeInGenericClass]
from typing import Any, TypeVar, Generic, Callable, ClassVar
t = TypeVar('t')
class B: pass
class C: pass
x: Any
class A(Generic[t]):
    f = x # type: ClassVar[Callable[[A[B]], None]]
ab: A[B]
ac: A[C]
ab.f()
ac.f()   # E: Invalid self argument "A[C]" to attribute function "f" with type "Callable[[A[B]], None]"

[case testPartiallyTypedSelfInMethodDataAttribute]
from typing import Any, TypeVar, Generic, Callable, ClassVar
t = TypeVar('t')
class B: pass
class C: pass
x: Any
class A(Generic[t]):
    f = x # type: ClassVar[Callable[[A], None]]
ab: A[B]
ac: A[C]
ab.f()
ac.f()

[case testCallableDataAttribute]
from typing import Callable, ClassVar
class A:
    g: ClassVar[Callable[[A], None]]
    def __init__(self, f: Callable[[], None]) -> None:
        self.f = f
a = A(lambda: None)
a.f()
a.g()
a.f(a) # E: Too many arguments
a.g(a) # E: Too many arguments


-- Nested functions
-- ----------------


[case testSimpleNestedFunction]
import typing
def f(a: 'A') -> None:
    def g(b: 'B') -> None:
        if int():
            b = a \
            # E: Incompatible types in assignment (expression has type "A", variable has type "B")
            aa = a # type: A # ok
            b = B()
    g(a) # E: Argument 1 to "g" has incompatible type "A"; expected "B"
    g(B())
class A: pass
class B: pass

[case testReturnAndNestedFunction]
import typing
def f() -> 'A':
    def g() -> 'B':
        return A() # fail
        return B()
    return B() # fail
    return A()
class A: pass
class B: pass
[out]
main:4: error: Incompatible return value type (got "A", expected "B")
main:6: error: Incompatible return value type (got "B", expected "A")

[case testDynamicallyTypedNestedFunction]
import typing
def f(x: object) -> None:
    def g(y):
        pass
    g() # E: Missing positional argument "y" in call to "g"
    g(x)
[out]

[case testNestedFunctionInMethod]
import typing
class A:
    def f(self) -> None:
        def g(x: int) -> None:
            y = x # type: int
            a = x # type: A # fail
        g(2)
        g(A()) # fail
[out]
main:6: error: Incompatible types in assignment (expression has type "int", variable has type "A")
main:8: error: Argument 1 to "g" has incompatible type "A"; expected "int"

[case testNestedFunctionInMethodWithTooFewArgumentsInTypeComment]
class A:
    def f(self):
        # type: () -> None
        def g(x):  # E: Type signature has too few arguments
            # type: () -> None
            pass

[case testDeepNestedFunctionWithTooFewArgumentsInTypeComment]
class A:
    def f(self):
        # type: () -> None
        class B:
            def g(self):
                # type: () -> None
                def h(x):  # E: Type signature has too few arguments
                    # type: () -> None
                    pass

[case testDeepNestedMethodInTypeComment]
class A:
    def f(self):
        # type: () -> None
        class B:
            class C:
                def g(self):
                    # type: () -> None
                    pass

[case testMutuallyRecursiveNestedFunctions]
def f() -> None:
    def g() -> None:
        h(1)
        h('') # E
    def h(x: int) -> None:
        g()
        g(1) # E
[out]
main:4: error: Argument 1 to "h" has incompatible type "str"; expected "int"
main:7: error: Too many arguments for "g"

[case testMutuallyRecursiveDecoratedFunctions]
from typing import Callable, Any
def dec(f) -> Callable[..., Any]: pass
def f() -> None:
    @dec
    def g() -> None:
        h()
        h.x # E
    @dec
    def h(x: int) -> None:
        g(1)
        g.x # E
[out]
main:7: error: "Callable[..., Any]" has no attribute "x"
main:11: error: "Callable[..., Any]" has no attribute "x"

[case testNestedGenericFunctions]
from typing import TypeVar
T = TypeVar('T')
U = TypeVar('U')

def outer(x: T) -> T:
    def inner(y: U) -> T: ...
    return inner(1)


-- Casts
-- -----


[case testCastsToAndFromFunctionTypes]
from typing import TypeVar, Callable, Any, cast
t = TypeVar('t')
def f(x: t,
      f1: Callable[[], None],
      f2: Callable[[Any], None], o: object) -> None:
    x = cast(t, f1)
    f1 = cast(Callable[[], None], x)
    f1 = cast(Callable[[], None], f2)
    f1 = cast(Callable[[], None], o)


-- Function decorators
-- -------------------


[case testTrivialStaticallyTypedFunctionDecorator]
from typing import TypeVar
t = TypeVar('t')
def dec(f: t) -> t:
    return f
@dec
def f(x: int) -> None: pass
f(1)
f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"

[case testTrivialStaticallyTypedMethodDecorator]
from typing import TypeVar
t = TypeVar('t')
def dec(f: t) -> t:
    return f
class A:
    @dec
    def f(self, x: int) -> None: pass
A().f(1)
A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
class B: pass

[case testTrivialDecoratedNestedFunction]
from typing import TypeVar
t = TypeVar('t')
def dec(f: t) -> t:
    return f
def g() -> None:
    @dec
    def f(x: int) -> None: pass
    f(1)
    f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
[out]

[case testCheckingDecoratedFunction]
import typing
def dec(f): pass
@dec
def f(x: 'A') -> None:
    a = x # type: A
    if int():
        x = object() # E: Incompatible types in assignment (expression has type "object", variable has type "A")
class A: pass
[out]

[case testDecoratorThatSwitchesType]
from typing import Callable
def dec(x) -> Callable[[], None]: pass
@dec
def f(y): pass
f()
f(None) # E: Too many arguments for "f"

[case testDecoratorThatSwitchesTypeWithMethod]
from typing import Any, Callable
def dec(x) -> Callable[[Any], None]: pass
class A:
    @dec
    def f(self, a, b, c): pass
a: A
a.f()
a.f(None) # E: Too many arguments for "f" of "A"

[case testNestedDecorators]
from typing import Any, Callable
def dec1(f: Callable[[Any], None]) -> Callable[[], None]: pass
def dec2(f: Callable[[Any, Any], None]) -> Callable[[Any], None]: pass
@dec1
@dec2
def f(x, y): pass
f()
f(None) # E: Too many arguments for "f"

[case testInvalidDecorator1]
from typing import Any, Callable
def dec1(f: Callable[[Any], None]) -> Callable[[], None]: pass
def dec2(f: Callable[[Any, Any], None]) -> Callable[[Any], None]: pass
@dec1
@dec2  # E: Argument 1 to "dec2" has incompatible type "Callable[[Any], Any]"; expected "Callable[[Any, Any], None]"
def f(x): pass

def faulty(c: Callable[[int], None]) -> Callable[[tuple[int, int]], None]:
    return lambda x: None

@faulty  # E: Argument 1 to "faulty" has incompatible type "Callable[[tuple[int, int]], None]"; expected "Callable[[int], None]"
@faulty  # E: Argument 1 to "faulty" has incompatible type "Callable[[str], None]"; expected "Callable[[int], None]"
def g(x: str) -> None:
    return None
[builtins fixtures/tuple.pyi]

[case testInvalidDecorator2]
from typing import Any, Callable
def dec1(f: Callable[[Any, Any], None]) -> Callable[[], None]: pass
def dec2(f: Callable[[Any, Any], None]) -> Callable[[Any], None]: pass
@dec1 # E: Argument 1 to "dec1" has incompatible type "Callable[[Any], None]"; expected "Callable[[Any, Any], None]"
@dec2
def f(x, y): pass

[case testNoTypeCheckDecoratorOnMethod1]
from typing import no_type_check

@no_type_check
def foo(x: 'bar', y: {'x': 4}) -> 42:
    1 + 'x'
[typing fixtures/typing-medium.pyi]

[case testNoTypeCheckDecoratorOnMethod2]
import typing

@typing.no_type_check
def foo(x: 's', y: {'x': 4}) -> 42:
    1 + 'x'

@typing.no_type_check
def bar() -> None:
    1 + 'x'
[typing fixtures/typing-medium.pyi]

[case testCallingNoTypeCheckFunction]
import typing

@typing.no_type_check
def foo(x: {1:2}) -> [1]:
    1 + 'x'

foo()
foo(1, 'b')
[typing fixtures/typing-medium.pyi]

[case testCallingNoTypeCheckFunction2]
import typing

def f() -> None:
    foo()

@typing.no_type_check
def foo(x: {1:2}) -> [1]:
    1 + 'x'
[typing fixtures/typing-medium.pyi]

[case testNoTypeCheckDecoratorSemanticError]
import typing

@typing.no_type_check
def foo(x: {1:2}) -> [1]:
    x = y
[typing fixtures/typing-medium.pyi]


-- Forward references to decorated functions
-- -----------------------------------------


[case testForwardReferenceToDynamicallyTypedDecorator]
def f(self) -> None:
    g()
    g(1)

def dec(f):
    return f

@dec
def g():
    pass

[case testForwardReferenceToDecoratorWithAnyReturn]
from typing import Any

def f(self) -> None:
    g()
    g(1)

def dec(f) -> Any:
    return f

@dec
def g():
    pass

[case testForwardReferenceToDecoratorWithIdentityMapping]
from typing import TypeVar

def f(self) -> None:
    g()
    g(1) # E: Too many arguments for "g"
    h(1).x # E: "str" has no attribute "x"
    h('') # E: Argument 1 to "h" has incompatible type "str"; expected "int"

T = TypeVar('T')
def dec(f: T) -> T:
    return f

@dec
def g(): pass
@dec
def h(x: int) -> str: pass
[out]

[case testForwardReferenceToDynamicallyTypedDecoratedMethod]
def f(self) -> None:
    A().f(1).y
    A().f()

class A:
    @dec
    def f(self, x): pass

def dec(f): return f
[builtins fixtures/staticmethod.pyi]

[case testForwardReferenceToStaticallyTypedDecoratedMethod]
from typing import TypeVar

def f(self) -> None:
    A().f(1).y # E: "str" has no attribute "y"
    A().f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"

class A:
    @dec
    def f(self, a: int) -> str: return ''

T = TypeVar('T')
def dec(f: T) -> T: return f
[builtins fixtures/staticmethod.pyi]
[out]

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

class A:
    @property
    def x(self): pass
[builtins fixtures/property.pyi]

[case testForwardReferenceToStaticallyTypedProperty]
def f(self) -> None:
    A().x.y # E: "int" has no attribute "y"

class A:
    @property
    def x(self) -> int: return 1
[builtins fixtures/property.pyi]
[out]

[case testForwardReferenceToDynamicallyTypedStaticMethod]
def f(self) -> None:
    A.x(1).y
    A.x() # E: Missing positional argument "x" in call to "x"

class A:
    @staticmethod
    def x(x): pass
[builtins fixtures/staticmethod.pyi]
[out]

[case testForwardReferenceToStaticallyTypedStaticMethod]
def f(self) -> None:
    A.x(1).y # E: "str" has no attribute "y"
    A.x('') # E: Argument 1 to "x" of "A" has incompatible type "str"; expected "int"

class A:
    @staticmethod
    def x(a: int) -> str: return ''
[builtins fixtures/staticmethod.pyi]
[out]

[case testForwardReferenceToDynamicallyTypedClassMethod]
def f(self) -> None:
    A.x(1).y
    A.x() # E: Missing positional argument "a" in call to "x"

class A:
    @classmethod
    def x(cls, a): pass
[builtins fixtures/classmethod.pyi]
[out]

[case testForwardReferenceToStaticallyTypedClassMethod]
def f(self) -> None:
    A.x(1).y # E: "str" has no attribute "y"
    A.x('') # E: Argument 1 to "x" of "A" has incompatible type "str"; expected "int"

class A:
    @classmethod
    def x(cls, x: int) -> str: return ''
[builtins fixtures/classmethod.pyi]
[out]

[case testForwardReferenceToDecoratedFunctionUsingMemberExpr]
import m

def f(self) -> None:
    g(1).x # E: "str" has no attribute "x"

@m.dec
def g(x: int) -> str: pass
[file m.py]
from typing import TypeVar
T = TypeVar('T')
def dec(f: T) -> T:
    return f
[out]

[case testForwardReferenceToFunctionWithMultipleDecorators]
# flags: --disable-error-code=used-before-def
def f(self) -> None:
    g()
    g(1)

def dec(f):
    return f

@dec
@dec2
def g():
    pass

def dec2(f):
    return f

[case testForwardReferenceToDynamicallyTypedDecoratedStaticMethod]
def f(self) -> None:
    A().f(1).y
    A().f()
    A().g(1).y
    A().g()

class A:
    @dec
    @staticmethod
    def f(self, x): pass
    @staticmethod
    @dec
    def g(self, x): pass

def dec(f): return f
[builtins fixtures/staticmethod.pyi]

[case testForwardRefereceToDecoratedFunctionWithCallExpressionDecorator]
# flags: --disable-error-code=used-before-def
def f(self) -> None:
    g()
    g(1)

@dec(1)
def g(): pass

def dec(f): pass


-- Decorator functions in import cycles
-- ------------------------------------


[case testDecoratorWithIdentityTypeInImportCycle]
import a

[file a.py]
import b
from d import dec
@dec
def f(x: int) -> None: pass
b.g(1) # E

[file b.py]
import a
from d import dec
@dec
def g(x: str) -> None: pass
a.f('')

[file d.py]
from typing import TypeVar
T = TypeVar('T')
def dec(f: T) -> T: return f

[out]
tmp/b.py:5: error: Argument 1 to "f" has incompatible type "str"; expected "int"
tmp/a.py:5: error: Argument 1 to "g" has incompatible type "int"; expected "str"

[case testDecoratorWithNoAnnotationInImportCycle]
import a

[file a.py]
import b
from d import dec
@dec
def f(x: int) -> None: pass
b.g(1, z=4)

[file b.py]
import a
from d import dec
@dec
def g(x: str) -> None: pass
a.f('', y=2)

[file d.py]
def dec(f): return f

[case testDecoratorWithFixedReturnTypeInImportCycle]
import a

[file a.py]
import b
from d import dec
@dec
def f(x: int) -> str: pass
b.g(1)()

[file b.py]
import a
from d import dec
@dec
def g(x: int) -> str: pass
a.f(1)()

[file d.py]
from typing import Callable
def dec(f: Callable[[int], str]) -> Callable[[int], str]: return f

[out]
tmp/b.py:5: error: "str" not callable
tmp/a.py:5: error: "str" not callable

[case testDecoratorWithCallAndFixedReturnTypeInImportCycle]
import a

[file a.py]
import b
from d import dec
@dec()
def f(x: int) -> str: pass
b.g(1)()

[file b.py]
import a
from d import dec
@dec()
def g(x: int) -> str: pass
a.f(1)()

[file d.py]
from typing import Callable
def dec() -> Callable[[Callable[[int], str]], Callable[[int], str]]: pass

[out]
tmp/b.py:5: error: "str" not callable
tmp/a.py:5: error: "str" not callable

[case testDecoratorWithCallAndFixedReturnTypeInImportCycleAndDecoratorArgs]
import a

[file a.py]
import b
from d import dec
@dec(1)
def f(x: int) -> str: pass
b.g(1)()

[file b.py]
import a
from d import dec
@dec(1)
def g(x: int) -> str: pass
a.f(1)()

[file d.py]
from typing import Callable
def dec(x: str) -> Callable[[Callable[[int], str]], Callable[[int], str]]: pass

[out]
tmp/b.py:3: error: Argument 1 to "dec" has incompatible type "int"; expected "str"
tmp/b.py:5: error: "str" not callable
tmp/a.py:3: error: Argument 1 to "dec" has incompatible type "int"; expected "str"
tmp/a.py:5: error: "str" not callable

[case testUndefinedDecoratorInImportCycle]
# cmd: mypy -m foo.base
[file foo/__init__.py]
import foo.base
class Derived(foo.base.Base):
    def method(self) -> None: pass
[file foo/base.py]
import foo
class Base:
    @decorator
    def method(self) -> None: pass
[out]
tmp/foo/base.py:3: error: Name "decorator" is not defined


-- Conditional function definition
-- -------------------------------


[case testTypeCheckBodyOfConditionalFunction]
from typing import Any
x = None # type: Any
if x:
    def f(x: int) -> None:
        if int():
            x = 1
            x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[out]

[case testCallConditionalFunction]
from typing import Any
x = None # type: Any
if x:
    def f(x: int) -> None:  pass
    f(1)
    f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
f(1)
f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"

[case testConditionalFunctionDefinitionWithIfElse]
from typing import Any
x = None # type: Any
if x:
    def f(x: int) -> None:
        'x' + x   # fail
        if int():
            x = 1
else:
    def f(x: int) -> None:
        x + 'x'   # fail
        if int():
            x = 1
f(1)
f('x') # fail
[builtins fixtures/primitives.pyi]
[out]
main:5: error: Unsupported operand types for + ("str" and "int")
main:10: error: Unsupported operand types for + ("int" and "str")
main:14: error: Argument 1 to "f" has incompatible type "str"; expected "int"

[case testNestedConditionalFunctionDefinitionWithIfElse]
from typing import Any
x = None # type: Any
def top() -> None:
    if x:
        def f(x: int) -> None:
            if int():
                x = 'x'  # E: Incompatible types in assignment \
                          (expression has type "str", variable has type "int")
                x = 1
    else:
        def f(x: int) -> None:
            x + 'x'   # E: Unsupported operand types for + ("int" and "str")
            x = 1
    f(1)
    f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"

[case testUnconditionalRedefinitionOfConditionalFunction]
from typing import Any
x = None # type: Any
if x:
    def f(): pass
def f(): pass # E: Name "f" already defined on line 4

[case testIncompatibleConditionalFunctionDefinition]
from typing import Any
x = None # type: Any
if x:
    def f(x: int) -> None: pass
else:
    def f(x): pass # E: All conditional function variants must have identical signatures \
                   # N: Original: \
                   # N:     def f(x: int) -> None \
                   # N: Redefinition: \
                   # N:     def f(x: Any) -> Any

[case testIncompatibleConditionalFunctionDefinition2]
from typing import Any
x = None # type: Any
if x:
    def f(x: int) -> None: pass
else:
    def f(y: int) -> None: pass # E: All conditional function variants must have identical signatures \
                                # N: Original: \
                                # N:     def f(x: int) -> None \
                                # N: Redefinition: \
                                # N:     def f(y: int) -> None

[case testIncompatibleConditionalFunctionDefinition3]
from typing import Any
x = None # type: Any
if x:
    def f(x: int) -> None: pass
else:
    def f(x: int = 0) -> None: pass # E: All conditional function variants must have identical signatures \
                                    # N: Original: \
                                    # N:     def f(x: int) -> None \
                                    # N: Redefinition: \
                                    # N:     def f(x: int = ...) -> None

[case testIncompatibleConditionalFunctionDefinition4]
from typing import Any, Union, TypeVar
T1 = TypeVar('T1')
T2 = TypeVar('T2', bound=Union[int, str])
x = None # type: Any
if x:
    def f(x: T1) -> T1: pass
else:
    def f(x: T2) -> T2: pass # E: All conditional function variants must have identical signatures \
                             # N: Original: \
                             # N:     def [T1] f(x: T1) -> T1 \
                             # N: Redefinition: \
                             # N:     def [T2: Union[int, str]] f(x: T2) -> T2

[case testConditionalFunctionDefinitionUsingDecorator1]
from typing import Callable

def dec(f) -> Callable[[int], None]: pass

x = int()
if x:
    @dec
    def f(): pass
else:
    def f(x: int) -> None: pass

[case testConditionalFunctionDefinitionUsingDecorator2]
from typing import Callable

def dec(f) -> Callable[[int], None]: pass

x = int()
if x:
    @dec
    def f(): pass
else:
    def f(x: str) -> None: pass # E: Incompatible redefinition (redefinition with type "Callable[[str], None]", original type "Callable[[int], None]")

[case testConditionalFunctionDefinitionUsingDecorator3]

from typing import Callable

def dec(f) -> Callable[[int], None]: pass

x = int()
if x:
    def f(x: int, /) -> None: pass
else:
    @dec
    def f(): pass

[case testConditionalFunctionDefinitionUsingDecorator4]

from typing import Callable

def dec(f) -> Callable[[int], None]: pass

x = int()
if x:
    def f(x: str) -> None: pass
else:
    @dec
    def f(): pass   # E: All conditional function variants must have identical signatures \
                    # N: Original: \
                    # N:     def f(x: str) -> None \
                    # N: Redefinition: \
                    # N:     def f(int, /) -> None

[case testConditionalFunctionDefinitionUnreachable]
def bar() -> None:
    if False:
        foo = 1
    else:
        def foo(obj): ...

def baz() -> None:
    if False:
        foo: int = 1
    else:
        def foo(obj): ...  # E: Incompatible redefinition (redefinition with type "Callable[[Any], Any]", original type "int")
[builtins fixtures/tuple.pyi]

[case testConditionalRedefinitionOfAnUnconditionalFunctionDefinition1]
from typing import Any
def f(x: str) -> None: pass
x = None # type: Any
if x:
    def f(x: int) -> None: pass # E: All conditional function variants must have identical signatures \
                                # N: Original: \
                                # N:     def f(x: str) -> None \
                                # N: Redefinition: \
                                # N:     def f(x: int) -> None

[case testConditionalRedefinitionOfAnUnconditionalFunctionDefinition2]
from typing import Any
def f(x: int) -> None: pass # N: "f" defined here
x = None # type: Any
if x:
    def f(y: int) -> None: pass # E: All conditional function variants must have identical signatures \
                                # N: Original: \
                                # N:     def f(x: int) -> None \
                                # N: Redefinition: \
                                # N:     def f(y: int) -> None
f(x=1) # The first definition takes precedence.
f(y=1) # E: Unexpected keyword argument "y" for "f"

[case testRedefineFunctionDefinedAsVariable]
def g(): pass
f = g
if g():
    def f(): pass
f()
f(1) # E: Too many arguments

[case testRedefineFunctionDefinedAsVariableInitializedToNone]
def g(): pass
f = None
if g():
    def f(): pass
f()
f(1) # E: Too many arguments for "f"

[case testRedefineNestedFunctionDefinedAsVariableInitializedToNone]
def g() -> None:
    f = None
    if object():
        def f(x: int) -> None: pass
    f() # E: Missing positional argument "x" in call to "f"
    f(1)
    f('') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
[out]

[case testRedefineFunctionDefinedAsVariableWithInvalidSignature]
def g(): pass
f = g
if g():
    def f(x): pass  # E: Incompatible redefinition (redefinition with type "Callable[[Any], Any]", original type "Callable[[], Any]")

[case testRedefineFunctionDefinedAsVariableWithVariance1]
class B: pass
class C(B): pass
def g(x: C) -> B: pass
f = g
if g(C()):
    def f(x: C) -> C: pass

[case testRedefineFunctionDefinedAsVariableWithVariance2]
class B: pass
class C(B): pass
def g(x: C) -> B: pass
f = g
if g(C()):
    def f(x: B) -> B: pass

[case testRedefineFunctionDefinedAsVariableInitializedToEmptyList]
f = [] # E: Need type annotation for "f" (hint: "f: list[<type>] = ...")
if object():
    def f(): pass # E: Incompatible redefinition
f()  # E: "list[Any]" not callable
f(1)  # E: "list[Any]" not callable
[builtins fixtures/list.pyi]

[case testDefineConditionallyAsImportedAndDecorated]
from typing import Callable

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

if int():
    from m import f
else:
    @dec
    def f():
        yield
[file m.py]
def f() -> None: pass

[case testDefineConditionallyAsImportedAndDecoratedWithInference]
if int():
    from m import f
else:
    from contextlib import contextmanager

    @contextmanager
    def f():
        yield
[file m.py]
from contextlib import contextmanager

@contextmanager
def f():
    yield
[typing fixtures/typing-medium.pyi]
[builtins fixtures/tuple.pyi]


-- Conditional method definition
-- -----------------------------


[case testTypeCheckBodyOfConditionalMethod]
from typing import Any
x = None # type: Any
class A:
    if x:
        def f(self, x: int) -> None:
            if int():
                x = 1
                x = '' # E: Incompatible types in assignment (expression has type "str", variable has type "int")
[out]

[case testCallConditionalMethodInClassBody]
from typing import Any
x = None # type: Any
class A:
    if x:
        def f(self, x: int) -> None:  pass
        f(x, 1)
        f(x, 'x') # E: Argument 2 to "f" of "A" has incompatible type "str"; expected "int"
    f(x, 1)
    f(x, 'x') # E: Argument 2 to "f" of "A" has incompatible type "str"; expected "int"
[out]

[case testCallConditionalMethodViaInstance]
from typing import Any
x = None # type: Any
class A:
    if x:
         def f(self, x: int) -> None: pass
A().f(1)
A().f('x') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"

[case testConditionalMethodDefinitionWithIfElse]
from typing import Any
x = None # type: Any
class A:
    if x:
        def f(self, x: int) -> None:
            'x' + x   # fail
            if int():
                x = 1
    else:
        def f(self, x: int) -> None:
            x + 'x'   # fail
            if int():
                x = 1
A().f(1)
A().f('x') # fail
[builtins fixtures/primitives.pyi]
[out]
main:6: error: Unsupported operand types for + ("str" and "int")
main:11: error: Unsupported operand types for + ("int" and "str")
main:15: error: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"

[case testUnconditionalRedefinitionOfConditionalMethod]
from typing import Any
x = None # type: Any
class A:
    if x:
        def f(self): pass
    def f(self): pass # E: Name "f" already defined on line 5

[case testIncompatibleConditionalMethodDefinition]
from typing import Any
x = None # type: Any
class A:
    if x:
        def f(self, x: int) -> None: pass
    else:
        def f(self, x): pass # E: All conditional function variants must have identical signatures \
                             # N: Original: \
                             # N:     def f(self: A, x: int) -> None \
                             # N: Redefinition: \
                             # N:     def f(self: A, x: Any) -> Any
[out]

[case testConditionalFunctionDefinitionInTry]
import typing
try:
    def f(x: int) -> None: pass
except:
    def g(x: str) -> None: pass
f(1)
f('x') # E: Argument 1 to "f" has incompatible type "str"; expected "int"
g('x')
g(1) # E: Argument 1 to "g" has incompatible type "int"; expected "str"

[case testConditionalMethodDefinitionUsingDecorator]
from typing import Callable

def dec(f) -> Callable[['A', int], None]: pass

class A:
    x = int()
    if x:
        @dec
        def f(self): pass
    else:
        def f(self, x: int) -> None: pass


-- Callable with specific arg list
-- -------------------------------


[case testCallableWithNamedArg]
from typing import Callable
from mypy_extensions import Arg

def a(f: Callable[[Arg(int, 'x')], int]):
    f(x=4)
    f(5)
    f(y=3) # E: Unexpected keyword argument "y"

[builtins fixtures/dict.pyi]

[case testCallableWithOptionalArg]
from typing import Callable
from mypy_extensions import DefaultArg

def a(f: Callable[[DefaultArg(int, 'x')], int]):
    f(x=4)
    f(2)
    f()
    f(y=3) # E: Unexpected keyword argument "y"
    f("foo") # E: Argument 1 has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]

[case testCallableWithNamedArgFromExpr]
from typing import Callable
from mypy_extensions import Arg

F = Callable[[Arg(int, 'x')], int]

def a(f: F):
    f(x=4)
    f(5)
    f(y=3) # E: Unexpected keyword argument "y"

[builtins fixtures/dict.pyi]

[case testCallableWithOptionalArgFromExpr]
from typing import Callable
from mypy_extensions import DefaultArg

F = Callable[[DefaultArg(int, 'x')], int]
def a(f: F):
    f(x=4)
    f(2)
    f()
    f(y=3) # E: Unexpected keyword argument "y"
    f("foo") # E: Argument 1 has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]

[case testCallableParsingInInheritance]

from collections import namedtuple
class C(namedtuple('t', 'x')):
    pass
[builtins fixtures/tuple.pyi]

[case testCallableParsingSameName]
from typing import Callable

def Arg(x, y): pass

F = Callable[[Arg(int, 'x')], int]  # E: Invalid argument constructor "__main__.Arg"

[case testCallableParsingFromExpr]
from typing import Callable, List
from mypy_extensions import Arg, VarArg, KwArg
import mypy_extensions
import types  # Needed for type checking

def WrongArg(x, y): return y
# Note that for this test, the 'Value of type "int" is not indexable' errors are silly,
# and a consequence of Callable being set to an int in the test stub.  We can't set it to
# something else sensible, because other tests require the stub not have anything
# that looks like a function call.
F = Callable[[WrongArg(int, 'x')], int] # E: Invalid argument constructor "__main__.WrongArg"
G = Callable[[Arg(1, 'x')], int] # E: Invalid type: try using Literal[1] instead?
H = Callable[[VarArg(int, 'x')], int] # E: VarArg arguments should not have names
I = Callable[[VarArg(int)], int] # ok
J = Callable[[VarArg(), KwArg()], int] # ok
K = Callable[[VarArg(), int], int] # E: Required positional args may not appear after default, named or var args
L = Callable[[Arg(name='x', type=int)], int] # ok
# I have commented out the following test because I don't know how to expect the "defined here" note part of the error.
# M = Callable[[Arg(gnome='x', type=int)], int]   E: Invalid type alias: expression is not a valid type   E: Unexpected keyword argument "gnome" for "Arg"
N = Callable[[Arg(name=None, type=int)], int] # ok
O = Callable[[List[Arg(int)]], int]  # E: Invalid type alias: expression is not a valid type \
                                     # E: Value of type "int" is not indexable \
                                     # E: Type expected within [...]
P = Callable[[mypy_extensions.VarArg(int)], int] # ok
Q = Callable[[Arg(int, type=int)], int]  # E: Invalid type alias: expression is not a valid type \
                                         # E: Value of type "int" is not indexable \
                                         # E: "Arg" gets multiple values for keyword argument "type"
R = Callable[[Arg(int, 'x', name='y')], int]  # E: Invalid type alias: expression is not a valid type \
                                              # E: Value of type "int" is not indexable \
                                              # E: "Arg" gets multiple values for keyword argument "name"
[builtins fixtures/dict.pyi]

[case testCallableParsing]
from typing import Callable
from mypy_extensions import Arg, VarArg, KwArg

def WrongArg(x, y): return y

def b(f: Callable[[Arg(1, 'x')], int]): pass # Invalid type. Try using Literal[1] instead?
def d(f: Callable[[VarArg(int)], int]): pass # ok
def e(f: Callable[[VarArg(), KwArg()], int]): pass # ok
def g(f: Callable[[Arg(name='x', type=int)], int]): pass # ok
def h(f: Callable[[Arg(gnome='x', type=int)], int]): pass  # E: Unexpected argument "gnome" for argument constructor
def i(f: Callable[[Arg(name=None, type=int)], int]): pass # ok
def j(f: Callable[[Arg(int, 'x', name='y')], int]): pass # E: "Arg" gets multiple values for keyword argument "name"
def k(f: Callable[[Arg(int, type=int)], int]): pass # E: "Arg" gets multiple values for keyword argument "type"

[builtins fixtures/dict.pyi]

[case testCallableTypeAnalysis]
from typing import Callable
from mypy_extensions import Arg, VarArg as VARG, KwArg
import mypy_extensions as ext

def WrongArg(x, y): return y
def a(f: Callable[[WrongArg(int, 'x')], int]): pass # E: Invalid argument constructor "__main__.WrongArg"
def b(f: Callable[[BadArg(int, 'x')], int]): pass # E: Name "BadArg" is not defined
def d(f: Callable[[ext.VarArg(int)], int]): pass # ok
def e(f: Callable[[VARG(), ext.KwArg()], int]): pass # ok
def g(f: Callable[[ext.Arg(name='x', type=int)], int]): pass # ok
def i(f: Callable[[Arg(name=None, type=int)], int]): pass # ok

def f1(*args) -> int: pass
def f2(*args, **kwargs) -> int: pass

d(f1)
e(f2)
d(f2)
e(f1)

[builtins fixtures/dict.pyi]

[case testCallableWrongTypeType]
from typing import Callable
from mypy_extensions import Arg
def b(f: Callable[[Arg(1, 'x')], int]): pass # E: Invalid type: try using Literal[1] instead?
[builtins fixtures/dict.pyi]

[case testCallableTooManyVarArg]
from typing import Callable
from mypy_extensions import VarArg
def c(f: Callable[[VarArg(int, 'x')], int]): pass # E: VarArg arguments should not have names
[builtins fixtures/dict.pyi]

[case testCallableFastParseGood]
from typing import Callable
from mypy_extensions import VarArg, Arg, KwArg
def d(f: Callable[[VarArg(int)], int]): pass # ok
def e(f: Callable[[VarArg(), KwArg()], int]): pass # ok
def g(f: Callable[[Arg(name='x', type=int)], int]): pass # ok
def i(f: Callable[[Arg(name=None, type=int)], int]): pass # ok
[builtins fixtures/dict.pyi]

[case testCallableFastParseBadArgArgName]
from typing import Callable
from mypy_extensions import Arg
def h(f: Callable[[Arg(gnome='x', type=int)], int]): pass # E: Unexpected argument "gnome" for argument constructor
[builtins fixtures/dict.pyi]

[case testCallableKindsOrdering]
from typing import Callable, Any
from mypy_extensions import Arg, VarArg, KwArg, DefaultArg, NamedArg

def f(f: Callable[[VarArg(), int], int]): pass # E: Required positional args may not appear after default, named or var args
def g(f: Callable[[VarArg(), VarArg()], int]): pass # E: Var args may not appear after named or var args
def h(f: Callable[[KwArg(), KwArg()], int]): pass # E: You may only have one **kwargs argument
def i(f: Callable[[DefaultArg(), int], int]): pass # E: Required positional args may not appear after default, named or var args
def j(f: Callable[[NamedArg(Any, 'x'), DefaultArg(int, 'y')], int]): pass # E: Positional default args may not appear after named or var args
def k(f: Callable[[KwArg(), NamedArg(Any, 'x')], int]): pass # E: A **kwargs argument must be the last argument
[builtins fixtures/dict.pyi]

[case testCallableDuplicateNames]
from typing import Callable
from mypy_extensions import Arg, VarArg, KwArg, DefaultArg

def f(f: Callable[[Arg(int, 'x'), int, Arg(int, 'x')], int]): pass # E: Duplicate argument "x" in Callable

[builtins fixtures/dict.pyi]


[case testCallableWithKeywordOnlyArg]
from typing import Callable
from mypy_extensions import NamedArg

def a(f: Callable[[NamedArg(int, 'x')], int]):
    f(x=4)
    f(2) # E: Too many positional arguments
    f() # E: Missing named argument "x"
    f(y=3) # E: Unexpected keyword argument "y"
    f(x="foo") # E: Argument "x" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]

[case testCallableWithKeywordOnlyOptionalArg]
from typing import Callable
from mypy_extensions import DefaultNamedArg

def a(f: Callable[[DefaultNamedArg(int, 'x')], int]):
    f(x=4)
    f(2) # E: Too many positional arguments
    f()
    f(y=3) # E: Unexpected keyword argument "y"
    f(x="foo") # E: Argument "x" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]

[case testCallableWithKwargs]
from typing import Callable
from mypy_extensions import KwArg

def a(f: Callable[[KwArg(int)], int]):
    f(x=4)
    f(2) # E: Too many arguments
    f()
    f(y=3)
    f(x=4, y=3, z=10)
    f(x="foo") # E: Argument "x" has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]


[case testCallableWithVarArg]
from typing import Callable
from mypy_extensions import VarArg

def a(f: Callable[[VarArg(int)], int]):
    f(x=4)  # E: Unexpected keyword argument "x"
    f(2)
    f()
    f(3, 4, 5)
    f("a")  # E: Argument 1 has incompatible type "str"; expected "int"
[builtins fixtures/dict.pyi]

[case testCallableArgKindSubtyping]
from typing import Callable
from mypy_extensions import Arg, DefaultArg

int_str_fun: Callable[[int, str], str]
int_opt_str_fun: Callable[[int, DefaultArg(str, None)], str]
int_named_str_fun: Callable[[int, Arg(str, 's')], str]

def isf(ii: int, ss: str) -> str:
    return ss

def iosf(i: int, s: str = "bar") -> str:
    return s

def isf_unnamed(__i: int, __s: str) -> str:
    return __s

int_str_fun = isf
int_str_fun = isf_unnamed
int_named_str_fun = isf_unnamed # E: Incompatible types in assignment (expression has type "Callable[[int, str], str]", variable has type "def (int, /, s: str) -> str")
int_opt_str_fun = iosf
int_str_fun = iosf
int_opt_str_fun = isf # E: Incompatible types in assignment (expression has type "def isf(ii: int, ss: str) -> str", variable has type "def (int, str = ..., /) -> str")

int_named_str_fun = isf # E: Incompatible types in assignment (expression has type "def isf(ii: int, ss: str) -> str", variable has type "def (int, /, s: str) -> str")
int_named_str_fun = iosf

[builtins fixtures/dict.pyi]

-- Callable[..., T]
-- ----------------


[case testCallableWithArbitraryArgs]
from typing import Callable
def f(x: Callable[..., int]) -> None:
    x()
    x(1)
    x(z=1)
    x() + '' # E: Unsupported operand types for + ("int" and "str")
[out]

[case testCallableWithArbitraryArgs2]
from typing import Callable
def f(x: Callable[..., int]) -> None:
    x(*[1], **{'x': 2})
[builtins fixtures/dict.pyi]

[case testCastWithCallableAndArbitraryArgs]
from typing import Callable, cast
f = cast(Callable[..., int], None)
f(x=4) + '' # E: Unsupported operand types for + ("int" and "str")

[case testCallableWithArbitraryArgsInErrorMessage]
from typing import Callable
def f(x: Callable[..., int]) -> None:
    if int():
        x = 1  # E: Incompatible types in assignment (expression has type "int", variable has type "Callable[..., int]")
[out]

[case testCallableWithArbitraryArgsInGenericFunction]
from typing import Callable, TypeVar
T = TypeVar('T')
def f(x: Callable[..., T]) -> T: pass
def g(*x: int) -> str: pass
x = f(g)
x + 1 # E: Unsupported left operand type for + ("str")
[builtins fixtures/list.pyi]

[case testCallableWithArbitraryArgsSubtyping]
from typing import Callable
def f(x: Callable[..., int]) -> None: pass
def g1(): pass
def g2(x, y) -> int: pass
def g3(*, y: str) -> int: pass
def g4(*, y: int) -> str: pass
f(g1)
f(g2)
f(g3)
f(g4) # E: Argument 1 to "f" has incompatible type "def g4(*, y: int) -> str"; expected "Callable[..., int]"

[case testCallableWithArbitraryArgsSubtypingWithGenericFunc]
from typing import Callable, TypeVar
T = TypeVar('T')
def f(x: Callable[..., int]) -> None: pass
def g1(x: T) -> int: pass
def g2(*x: T) -> int: pass
def g3(*x: T) -> T: pass
f(g1)
f(g2)
f(g3)
[builtins fixtures/tuple.pyi]

-- (...) -> T
-- ----------------

[case testEllipsisWithArbitraryArgsOnBareFunction]
def f(x, y, z): # type: (...) -> None
    pass
f(1, "hello", [])
f(x=1, y="hello", z=[])
[builtins fixtures/dict.pyi]

[case testEllipsisWithArbitraryArgsOnBareFunctionWithDefaults]
def f(x, y=1, z="hey"): # type: (...) -> None
    pass
f(1, "hello", [])
f(x=1, y="hello", z=[])
[builtins fixtures/dict.pyi]

[case testEllipsisWithArbitraryArgsOnBareFunctionWithKwargs]
from typing import Dict
def f(x, **kwargs): # type: (...) -> None
    success_dict_type = kwargs # type: Dict[str, str]
    failure_dict_type = kwargs # type: Dict[int, str] # E: Incompatible types in assignment (expression has type "dict[str, Any]", variable has type "dict[int, str]")
f(1, thing_in_kwargs=["hey"])
[builtins fixtures/dict.pyi]
[out]

[case testEllipsisWithArbitraryArgsOnBareFunctionWithVarargs]
from typing import Tuple, Any
def f(x, *args): # type: (...) -> None
    success_tuple_type = args # type: Tuple[Any, ...]
    fail_tuple_type = args # type: None # E: Incompatible types in assignment (expression has type "tuple[Any, ...]", variable has type "None")
f(1, "hello")
[builtins fixtures/tuple.pyi]
[out]

[case testEllipsisWithArbitraryArgsOnInstanceMethod]
class A:
    def f(self, x, y, z): # type: (...) -> None
        pass

[case testEllipsisWithArbitraryArgsOnClassMethod]
class A:
    @classmethod
    def f(cls, x, y, z): # type: (...) -> None
        pass
[builtins fixtures/classmethod.pyi]

[case testEllipsisWithArbitraryArgsOnStaticMethod]
class A:
    @staticmethod
    def f(x, y, z): # type: (...) -> None
        pass
[builtins fixtures/staticmethod.pyi]

[case testEllipsisWithSomethingAfterItFails]
def f(x, y, z): # type: (..., int) -> None
    pass
[out]
main:1: error: Ellipses cannot accompany other argument types in function type signature

[case testEllipsisWithSomethingBeforeItFails]
def f(x, y, z): # type: (int, ...) -> None
    pass
[out]
main:1: error: Ellipses cannot accompany other argument types in function type signature

[case testRejectCovariantArgument]
from typing import TypeVar, Generic

t = TypeVar('t', covariant=True)
class A(Generic[t]):
    def foo(self, x: t) -> None:
        return None
[builtins fixtures/bool.pyi]
[out]
main:5: error: Cannot use a covariant type variable as a parameter

[case testRejectCovariantArgumentSplitLine]
from typing import TypeVar, Generic

t = TypeVar('t', covariant=True)
class A(Generic[t]):
    def foo(self,
            x: t) -> None:
        return None
[builtins fixtures/bool.pyi]
[out]
main:6: error: Cannot use a covariant type variable as a parameter

[case testRejectCovariantArgumentInLambda]
from typing import TypeVar, Generic, Callable

t = TypeVar('t', covariant=True)
class Thing(Generic[t]):
    def chain(self, func: Callable[[t], None]) -> None: pass
    def end(self) -> None:
        return self.chain(  # Note that lambda args have no line numbers
            lambda _: None)
[builtins fixtures/bool.pyi]
[out]
main:8: error: Cannot use a covariant type variable as a parameter

[case testRejectCovariantArgumentInLambdaSplitLine]
from typing import TypeVar, Generic, Callable

[case testRejectContravariantReturnType]
# flags: --no-strict-optional
from typing import TypeVar, Generic

t = TypeVar('t', contravariant=True)
class A(Generic[t]):
    def foo(self) -> t:
        return None
[builtins fixtures/bool.pyi]
[out]
main:6: error: Cannot use a contravariant type variable as return type

[case testAcceptCovariantReturnType]
# flags: --no-strict-optional
from typing import TypeVar, Generic

t = TypeVar('t', covariant=True)
class A(Generic[t]):
    def foo(self) -> t:
        return None
[builtins fixtures/bool.pyi]

[case testAcceptContravariantArgument]
from typing import TypeVar, Generic

t = TypeVar('t', contravariant=True)
class A(Generic[t]):
    def foo(self, x: t) -> None:
        return None
[builtins fixtures/bool.pyi]


-- Redefining functions
-- --------------------


[case testRedefineFunction]
from typing import Any
def f(x) -> Any: pass
def g(x, y): pass
def h(x): pass
def j(y) -> Any: pass
f = h
f = j # E: Incompatible types in assignment (expression has type "def j(y: Any) -> Any", variable has type "def f(x: Any) -> Any")
f = g # E: Incompatible types in assignment (expression has type "Callable[[Any, Any], Any]", variable has type "Callable[[Any], Any]")

[case testRedefineFunction2]
def f() -> None: pass
def f() -> None: pass # E: Name "f" already defined on line 1


-- Special cases
-- -------------


[case testFunctionDefinitionWithForStatement]
for _ in [1]:
    def f(): pass
else:
    def g(): pass
f()
g()
[builtins fixtures/list.pyi]

[case testFunctionDefinitionWithWhileStatement]
while bool():
    def f(): pass
else:
    def g(): pass
f()
g()
[builtins fixtures/bool.pyi]

[case testBareCallable]
from typing import Callable, Any

def foo(f: Callable) -> bool:
    return f()

def f1() -> bool:
    return False

foo(f1)
[builtins fixtures/bool.pyi]

[case testFunctionNestedWithinWith]
from typing import Any
a = 1  # type: Any
with a:
    def f() -> None:
        pass
    f(1) # E: Too many arguments for "f"


[case testNameForDecoratorMethod]
from typing import Callable

class A:
    def f(self) -> None:
        # In particular, test that the error message contains "g" of "A".
        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], None]) -> Callable[[A, int], None]: pass
[out]

[case testUnknownFunctionNotCallable]
from typing import TypeVar

def f() -> None:
    pass
def g(x: int) -> None:
    pass
h = f if bool() else g
reveal_type(h) # N: Revealed type is "Union[def (), def (x: builtins.int)]"
h(7) # E: Too many arguments for "f"

T = TypeVar("T")
def join(x: T, y: T) -> T: ...

h2 = join(f, g)
reveal_type(h2)  # N: Revealed type is "builtins.function"
h2(7)  # E: Cannot call function of unknown type

h3 = join(g, f)
reveal_type(h3)  # N: Revealed type is "builtins.function"
h3(7)  # E: Cannot call function of unknown type
[builtins fixtures/bool.pyi]

[case testFunctionWithNameUnderscore]
def _(x: int) -> None: pass

_(1)
_('x')  # E: Argument 1 to "_" has incompatible type "str"; expected "int"

-- Positional-only arguments
-- -------------------------

[case testPositionalOnlyArg]
def f(__a: int) -> None: pass
def g(__a__: int) -> None: pass

f(1)
f(__a=1) # E: Unexpected keyword argument "__a" for "f"

g(1)
# Argument names that also end with __ are not positional-only.
g(__a__=1)

[builtins fixtures/bool.pyi]
[out]
main:1: note: "f" defined here

[case testMagicMethodPositionalOnlyArg]
class A(object):
    def __eq__(self, other) -> bool: return True # We are all equal.  # N: "__eq__" of "A" defined here

a = A()
a.__eq__(a)
a.__eq__(other=a) # E: Unexpected keyword argument "other" for "__eq__" of "A"

[builtins fixtures/bool.pyi]

[case testMagicMethodPositionalOnlyArgFastparse]


class A(object):
    def __eq__(self, other) -> bool: return True # We are all equal.  # N: "__eq__" of "A" defined here

a = A()
a.__eq__(a)
a.__eq__(other=a) # E: Unexpected keyword argument "other" for "__eq__" of "A"

[builtins fixtures/bool.pyi]

-- Type variable shenanigans
-- -------------------------

[case testGenericFunctionTypeDecl]
from typing import Callable, TypeVar

T = TypeVar('T')

f: Callable[[T], T]
reveal_type(f)  # N: Revealed type is "def [T] (T`-1) -> T`-1"
def g(__x: T) -> T: pass
f = g
reveal_type(f)  # N: Revealed type is "def [T] (T`-1) -> T`-1"
i = f(3)
reveal_type(i)  # N: Revealed type is "builtins.int"

[case testFunctionReturningGenericFunction]
from typing import Callable, TypeVar

T = TypeVar('T')
def deco() -> Callable[[T], T]: pass
reveal_type(deco)  # N: Revealed type is "def () -> def [T] (T`-1) -> T`-1"
f = deco()
reveal_type(f)  # N: Revealed type is "def [T] (T`1) -> T`1"
i = f(3)
reveal_type(i)  # N: Revealed type is "builtins.int"

[case testFunctionReturningGenericFunctionPartialBinding]
from typing import Callable, TypeVar

T = TypeVar('T')
U = TypeVar('U')

def deco(x: U) -> Callable[[T, U], T]: pass
reveal_type(deco)  # N: Revealed type is "def [U] (x: U`-1) -> def [T] (T`-2, U`-1) -> T`-2"
f = deco("foo")
reveal_type(f)  # N: Revealed type is "def [T] (T`1, builtins.str) -> T`1"
i = f(3, "eggs")
reveal_type(i)  # N: Revealed type is "builtins.int"

[case testFunctionReturningGenericFunctionTwoLevelBinding]
from typing import Callable, TypeVar

T = TypeVar('T')
R = TypeVar('R')
def deco() -> Callable[[T], Callable[[T, R], R]]: pass
f = deco()
reveal_type(f)  # N: Revealed type is "def [T] (T`2) -> def [R] (T`2, R`1) -> R`1"
g = f(3)
reveal_type(g)  # N: Revealed type is "def [R] (builtins.int, R`3) -> R`3"
s = g(4, "foo")
reveal_type(s)  # N: Revealed type is "builtins.str"

[case testGenericFunctionReturnAsDecorator]
from typing import Callable, TypeVar

T = TypeVar('T')
def deco(__i: int) -> Callable[[T], T]: pass

@deco(3)
def lol(x: int) -> str: ...

reveal_type(lol)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
s = lol(4)
reveal_type(s)  # N: Revealed type is "builtins.str"

[case testGenericFunctionOnReturnTypeOnly]
from typing import TypeVar, List

T = TypeVar('T')

def make_list() -> List[T]: pass

l: List[int] = make_list()

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

[case testAnonymousArgumentError]
def foo(__b: int, x: int, y: int) -> int: pass
foo(x=2, y=2)  # E: Too few arguments for "foo"
foo(y=2)  # E: Too few arguments for "foo"

[case testMissingArgumentError]
def f(a, b, c, d=None) -> None: pass
f(1, 2, d=3) # E: Missing positional argument "c" in call to "f"

[case testMissingArgumentErrorMoreThanOneOptional]
def f(a: int, b=None, c=None) -> None: pass
f(b=4) # E: Missing positional argument "a" in call to "f"

[case testMissingArgumentsError]
def f(a, b, c, d=None) -> None: pass
f(1, d=3) # E: Missing positional arguments "b", "c" in call to "f"

[case testReturnTypeLineNumberWithDecorator]
def dec(f): pass

@dec
def test(a: str) -> (str,): # E: Syntax error in type annotation # N: Suggestion: Is there a spurious trailing comma?
    return None

[case testReturnTypeLineNumberNewLine]
def fn(a: str
       ) -> badtype: # E: Name "badtype" is not defined
    pass

[case testArgumentTypeLineNumberWithDecorator]
def dec(f): pass

@dec
def some_method(self: badtype): pass # E: Name "badtype" is not defined

[case TestArgumentTypeLineNumberNewline]
def fn(
        a: badtype) -> None: # E: Name "badtype" is not defined
    pass

[case testInferredTypeSubTypeOfReturnType]
from typing import Union, Dict, List
def f() -> List[Union[str, int]]:
    x = ['a']
    return x # E: Incompatible return value type (got "list[str]", expected "list[Union[str, int]]") \
      # N: "list" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \
      # N: Consider using "Sequence" instead, which is covariant \
      # N: Perhaps you need a type annotation for "x"? Suggestion: "list[Union[str, int]]"

def g() -> Dict[str, Union[str, int]]:
    x = {'a': 'a'}
    return x # E: Incompatible return value type (got "dict[str, str]", expected "dict[str, Union[str, int]]") \
      # N: "dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \
      # N: Consider using "Mapping" instead, which is covariant in the value type \
      # N: Perhaps you need a type annotation for "x"? Suggestion: "dict[str, Union[str, int]]"

def h() -> Dict[Union[str, int], str]:
    x = {'a': 'a'}
    return x # E: Incompatible return value type (got "dict[str, str]", expected "dict[Union[str, int], str]") \
# N: Perhaps you need a type annotation for "x"? Suggestion: "dict[Union[str, int], str]"

def i() -> List[Union[int, float]]:
    x: List[int] = [1]
    return x # E: Incompatible return value type (got "list[int]", expected "list[Union[int, float]]") \
      # 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/dict.pyi]

[case testInferredTypeNotSubTypeOfReturnType]
from typing import Union, List
def f() -> List[Union[int, float]]:
    x = ['a']
    return x # E: Incompatible return value type (got "list[str]", expected "list[Union[int, float]]")

def g() -> List[Union[str, int]]:
    x = ('a', 2)
    return x # E: Incompatible return value type (got "tuple[str, int]", expected "list[Union[str, int]]")

[builtins fixtures/list.pyi]

[case testInferredTypeIsObjectMismatch]
from typing import Union, Dict, List
def f() -> Dict[str, Union[str, int]]:
    x = {'a': 'a', 'b': 2}
    return x # E: Incompatible return value type (got "dict[str, object]", expected "dict[str, Union[str, int]]")

def g() -> Dict[str, Union[str, int]]:
    x: Dict[str, Union[str, int]] = {'a': 'a', 'b': 2}
    return x

def h() -> List[Union[str, int]]:
    x = ['a', 2]
    return x # E: Incompatible return value type (got "list[object]", expected "list[Union[str, int]]")

def i() -> List[Union[str, int]]:
    x: List[Union[str, int]] = ['a', 2]
    return x

[builtins fixtures/dict.pyi]

[case testLambdaSemanal]
f = lambda: xyz
[out]
main:1: error: Name "xyz" is not defined

[case testLambdaTypeCheck]
f = lambda: 1 + '1'
[out]
main:1: error: Unsupported operand types for + ("int" and "str")

[case testLambdaTypeInference]
f = lambda: 5
reveal_type(f)
[out]
main:2: note: Revealed type is "def () -> builtins.int"

[case testRevealLocalsFunction]
a = 1.0

class A: pass

def f(a: int, b: int) -> int:
    reveal_locals()
    c = a + b
    class C: pass
    reveal_locals()
    return c

reveal_locals()
[out]
main:6: note: Revealed local types are:
main:6: note:     a: builtins.int
main:6: note:     b: builtins.int
main:9: note: Revealed local types are:
main:9: note:     a: builtins.int
main:9: note:     b: builtins.int
main:9: note:     c: builtins.int
main:12: note: Revealed local types are:
main:12: note:     a: builtins.float

[case testNoComplainOverloadNone]
# flags: --no-strict-optional
from typing import overload, Optional
@overload
def bar(x: None) -> None:
    ...
@overload
def bar(x: int) -> str:
    ...
def bar(x: Optional[int]) -> Optional[str]:
    if x is None:
        return None
    return "number"

reveal_type(bar(None))  # N: Revealed type is "None"
[builtins fixtures/isinstance.pyi]
[out]

[case testNoComplainOverloadNoneStrict]
from typing import overload, Optional
@overload
def bar(x: None) -> None:
    ...
@overload
def bar(x: int) -> str:
    ...
def bar(x: Optional[int]) -> Optional[str]:
    if x is None:
        return None
    return "number"

reveal_type(bar(None))  # N: Revealed type is "None"
[builtins fixtures/isinstance.pyi]
[out]

[case testNoComplainInferredNone]
# flags: --no-strict-optional
from typing import TypeVar, Optional
T = TypeVar('T')
def X(val: T) -> T: ...
x_in = None
def Y(x: Optional[str] = X(x_in)): ...

xx: Optional[int] = X(x_in)
[out]

[case testNoComplainInferredNoneStrict]
from typing import TypeVar, Optional
T = TypeVar('T')
def X(val: T) -> T: ...
x_in = None
def Y(x: Optional[str] = X(x_in)): ...

xx: Optional[int] = X(x_in)
[out]

[case testNoComplainNoneReturnFromUntyped]
def foo() -> None:
    pass

def lol():
    x = foo()

[case testConditionalImportFunction]
import p
[file p/__init__.py]

if int():
    from p.a import f
elif int():
    from p.b import f
else:
    from p.c import f

[file p/a.py]
def f() -> int: ...

[file p/b.py]
from p.d import f

[file p/c.py]
def f() -> int: ...

[file p/d.py]
import p
def f() -> int: ...

[case testLambdaDefaultTypeErrors]
lambda a=(1 + 'asdf'): a  # E: Unsupported operand types for + ("int" and "str")
lambda a=nonsense: a  # E: Name "nonsense" is not defined
def f(x: int = i):  # E: Name "i" is not defined
    i = 42

[case testRevealTypeOfCallExpressionReturningNoneWorks]
def foo() -> None:
    pass

reveal_type(foo()) # N: Revealed type is "None"

[case testAnyArgument]
def a(b: any): pass # E: Function "builtins.any" is not valid as a type \
                    # N: Perhaps you meant "typing.Any" instead of "any"?
[builtins fixtures/any.pyi]

[case testCallableArgument]
def a(b: callable): pass # E: Function "builtins.callable" is not valid as a type \
                         # N: Perhaps you meant "typing.Callable" instead of "callable"?
[builtins fixtures/callable.pyi]

[case testDecoratedProperty]
from typing import TypeVar, Callable, final

T = TypeVar("T")

def dec(f: Callable[[T], int]) -> Callable[[T], str]: ...
def dec2(f: T) -> T: ...

class A:
    @property
    @dec
    def f(self) -> int: pass
    @property
    @dec2
    def g(self) -> int: pass
reveal_type(A().f)  # N: Revealed type is "builtins.str"
reveal_type(A().g)  # N: Revealed type is "builtins.int"

class B:
    @final
    @property
    @dec
    def f(self) -> int: pass
reveal_type(B().f)  # N: Revealed type is "builtins.str"

class C:
    @property  # E: Only instance methods can be decorated with @property
    @classmethod
    def f(cls) -> int: pass
reveal_type(C().f)  # N: Revealed type is "builtins.int"
[builtins fixtures/property.pyi]
[out]

[case testDecoratedPropertySetter]
from typing import TypeVar, Callable, final

T = TypeVar("T")
def dec(f: T) -> T: ...

class A:
    @property
    @dec
    def f(self) -> int: pass
    @f.setter
    @dec
    def f(self, v: int) -> None: pass
reveal_type(A().f)  # N: Revealed type is "builtins.int"

class B:
    @property
    @dec
    def f(self) -> int: pass
    @dec # E: Only supported top decorators are "@f.setter" and "@f.deleter"
    @f.setter
    def f(self, v: int) -> None: pass

class C:
    @dec  # E: Decorators on top of @property are not supported
    @property
    def f(self) -> int: pass
    @f.setter
    @dec
    def f(self, v: int) -> None: pass
[builtins fixtures/property.pyi]

[case testInvalidArgCountForProperty]
from typing import Callable, TypeVar

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

class A:
    @property  # E: Too many arguments for property
    def f(self, x) -> int: pass
    @property  # E: Too many arguments for property
    @dec
    def e(self) -> int: pass
    @property
    def g() -> int: pass   # E: Method must have at least one argument. Did you forget the "self" argument?
    @property
    def h(self, *args, **kwargs) -> int: pass   # OK
[builtins fixtures/property.pyi]

[case testSubtypingUnionGenericBounds]
from typing import Callable, TypeVar, Union, Sequence

TI = TypeVar("TI", bound=int)
TS = TypeVar("TS", bound=str)

f: Callable[[Sequence[TI]], None]
g: Callable[[Union[Sequence[TI], Sequence[TS]]], None]
f = g

[case testOverrideDecoratedProperty]
class Base:
    @property
    def foo(self) -> int: ...

class decorator:
    def __init__(self, fn):
        self.fn = fn
    def __call__(self, decorated_self) -> int:
        return self.fn(decorated_self)

class Child(Base):
    @property
    @decorator
    def foo(self) -> int:
        return 42
reveal_type(Child().foo)  # N: Revealed type is "builtins.int"
Child().foo = 1  # E: Property "foo" defined in "Child" is read-only

reveal_type(Child().foo)  # N: Revealed type is "builtins.int"

class BadChild1(Base):
    @decorator
    def foo(self) -> int:  # E: Signature of "foo" incompatible with supertype "Base" \
                           # N:      Superclass: \
                           # N:          int \
                           # N:      Subclass: \
                           # N:          decorator
        return 42

class not_a_decorator:
    def __init__(self, fn): ...

class BadChild2(Base):
    # Override error not shown as accessing 'foo' on BadChild2 returns Any.
    @property
    @not_a_decorator
    def foo(self) -> int:
        return 42
reveal_type(BadChild2().foo)  # E: "not_a_decorator" not callable \
                              # N: Revealed type is "Any"
[builtins fixtures/property.pyi]

[case explicitOverride]
# flags: --python-version 3.12
from typing import override

class A:
    def f(self, x: int) -> str: pass
    @override
    def g(self, x: int) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class B(A):
    @override
    def f(self, x: int) -> str: pass
    @override
    def g(self, x: int) -> str: pass

class C(A):
    @override
    def f(self, x: str) -> str: pass  # E: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "int" \
                                      # N: This violates the Liskov substitution principle \
                                      # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
    def g(self, x: int) -> str: pass

class D(A): pass
class E(D): pass
class F(E):
    @override
    def f(self, x: int) -> str: pass
[typing fixtures/typing-override.pyi]

[case explicitOverrideStaticmethod]
# flags: --python-version 3.12
from typing import override

class A:
    @staticmethod
    def f(x: int) -> str: pass

class B(A):
    @staticmethod
    @override
    def f(x: int) -> str: pass
    @override
    @staticmethod
    def g(x: int) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class C(A):  # inverted order of decorators
    @override
    @staticmethod
    def f(x: int) -> str: pass
    @override
    @staticmethod
    def g(x: int) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class D(A):
    @staticmethod
    @override
    def f(x: str) -> str: pass  # E: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "int" \
                                # N: This violates the Liskov substitution principle \
                                # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
[typing fixtures/typing-override.pyi]
[builtins fixtures/staticmethod.pyi]

[case explicitOverrideClassmethod]
# flags: --python-version 3.12
from typing import override

class A:
    @classmethod
    def f(cls, x: int) -> str: pass

class B(A):
    @classmethod
    @override
    def f(cls, x: int) -> str: pass
    @override
    @classmethod
    def g(cls, x: int) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class C(A):  # inverted order of decorators
    @override
    @classmethod
    def f(cls, x: int) -> str: pass
    @override
    @classmethod
    def g(cls, x: int) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class D(A):
    @classmethod
    @override
    def f(cls, x: str) -> str: pass  # E: Argument 1 of "f" is incompatible with supertype "A"; supertype defines the argument type as "int" \
                                     # N: This violates the Liskov substitution principle \
                                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
[typing fixtures/typing-override.pyi]
[builtins fixtures/classmethod.pyi]

[case explicitOverrideProperty]
# flags: --python-version 3.12
from typing import override

class A:
    @property
    def f(self) -> str: pass

class B(A):
    @property
    @override
    def f(self) -> str: pass
    @override
    @property
    def g(self) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class C(A):  # inverted order of decorators
    @override
    @property
    def f(self) -> str: pass
    @override
    @property
    def g(self) -> str: pass  # E: Method "g" is marked as an override, but no base method was found with this name

class D(A):
    @property
    @override
    def f(self) -> int: pass  # E: Signature of "f" incompatible with supertype "A" \
                              # N:      Superclass: \
                              # N:          str \
                              # N:      Subclass: \
                              # N:          int
[typing fixtures/typing-override.pyi]
[builtins fixtures/property.pyi]

[case explicitOverrideSettableProperty]
# flags: --python-version 3.12
from typing import override

class A:
    @property
    def f(self) -> str: pass

    @f.setter
    def f(self, value: str) -> None: pass

class B(A):
    @property  # E: Read-only property cannot override read-write property
    @override
    def f(self) -> str: pass

class C(A):
    @override
    @property
    def f(self) -> str: pass

    @f.setter
    def f(self, value: str) -> None: pass

class D(A):
    @override  # E: Signature of "f" incompatible with supertype "A" \
               # N:      Superclass: \
               # N:          str \
               # N:      Subclass: \
               # N:          int
    @property
    def f(self) -> int: pass

    @f.setter
    def f(self, value: int) -> None: pass
[typing fixtures/typing-override.pyi]
[builtins fixtures/property.pyi]

[case invalidExplicitOverride]
# flags: --python-version 3.12
from typing import override

@override  # E: "override" used with a non-method
def f(x: int) -> str: pass

@override  # this should probably throw an error but the signature from typeshed should ensure this already
class A: pass

def g() -> None:
    @override  # E: "override" used with a non-method
    def h(b: bool) -> int: pass
[typing fixtures/typing-override.pyi]

[case explicitOverrideSpecialMethods]
# flags: --python-version 3.12
from typing import override

class A:
    def __init__(self, a: int) -> None: pass

class B(A):
    @override
    def __init__(self, b: str) -> None: pass

class C:
    @override
    def __init__(self, a: int) -> None: pass
[typing fixtures/typing-override.pyi]

[case explicitOverrideFromExtensions]
from typing_extensions import override

class A:
    def f(self, x: int) -> str: pass

class B(A):
    @override
    def f2(self, x: int) -> str: pass  # E: Method "f2" is marked as an override, but no base method was found with this name
[builtins fixtures/tuple.pyi]

[case explicitOverrideOverloads]
# flags: --python-version 3.12
from typing import overload, override

class A:
    def f(self, x: int) -> str: pass

class B(A):
    @overload  # E: Method "f2" is marked as an override, but no base method was found with this name
    def f2(self, x: int) -> str: pass
    @overload
    def f2(self, x: str) -> str: pass
    @override
    def f2(self, x: int | str) -> str: pass
[typing fixtures/typing-override.pyi]

[case explicitOverrideNotOnOverloadsImplementation]
# flags: --python-version 3.12
from typing import overload, override

class A:
    def f(self, x: int) -> str: pass

class B(A):
    @overload  # E: Method "f2" is marked as an override, but no base method was found with this name
    def f2(self, x: int) -> str: pass
    @override
    @overload
    def f2(self, x: str) -> str: pass
    def f2(self, x: int | str) -> str: pass

class C(A):
    @overload
    def f(self, y: int) -> str: pass
    @override
    @overload
    def f(self, y: str) -> str: pass
    def f(self, y: int | str) -> str: pass
[typing fixtures/typing-override.pyi]

[case explicitOverrideOnMultipleOverloads]
# flags: --python-version 3.12
from typing import overload, override

class A:
    def f(self, x: int) -> str: pass

class B(A):
    @override  # E: Method "f2" is marked as an override, but no base method was found with this name
    @overload
    def f2(self, x: int) -> str: pass
    @override
    @overload
    def f2(self, x: str) -> str: pass
    def f2(self, x: int | str) -> str: pass

class C(A):
    @overload
    def f(self, y: int) -> str: pass
    @override
    @overload
    def f(self, y: str) -> str: pass
    @override
    def f(self, y: int | str) -> str: pass
[typing fixtures/typing-override.pyi]

[case explicitOverrideCyclicDependency]
# flags: --python-version 3.12
import b
[file a.py]
from typing import override
import b
import c

class A(b.B):
    @override  # This is fine
    @c.deco
    def meth(self) -> int: ...
[file b.py]
import a
import c

class B:
    @c.deco
    def meth(self) -> int: ...
[file c.py]
from typing import TypeVar, Tuple, Callable
T = TypeVar('T')
def deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...
[builtins fixtures/tuple.pyi]
[typing fixtures/typing-override.pyi]

[case requireExplicitOverrideMethod]
# flags: --enable-error-code explicit-override --python-version 3.12
from typing import override

class A:
    def f(self, x: int) -> str: pass

class B(A):
    @override
    def f(self, y: int) -> str: pass

class C(A):
    def f(self, y: int) -> str: pass  # E: Method "f" is not using @override but is overriding a method in class "__main__.A"

class D(B):
    def f(self, y: int) -> str: pass  # E: Method "f" is not using @override but is overriding a method in class "__main__.B"
[typing fixtures/typing-override.pyi]

[case requireExplicitOverrideSpecialMethod]
# flags: --enable-error-code explicit-override --python-version 3.12
from typing import Callable, Self, TypeVar, override, overload

T = TypeVar('T')
def some_decorator(f: Callable[..., T]) -> Callable[..., T]: ...

# Don't require override decorator for __init__ and __new__
# See: https://github.com/python/typing/issues/1376
class A:
    def __init__(self) -> None: pass
    def __new__(cls) -> Self: pass

class B(A):
    def __init__(self) -> None: pass
    def __new__(cls) -> Self: pass

class C(A):
    @some_decorator
    def __init__(self) -> None: pass

    @some_decorator
    def __new__(cls) -> Self: pass

class D(A):
    @overload
    def __init__(self, x: int) -> None: ...
    @overload
    def __init__(self, x: str) -> None: ...
    def __init__(self, x): pass

    @overload
    def __new__(cls, x: int) -> Self: pass
    @overload
    def __new__(cls, x: str) -> Self: pass
    def __new__(cls, x): pass
[typing fixtures/typing-override.pyi]

[case requireExplicitOverrideProperty]
# flags: --enable-error-code explicit-override --python-version 3.12
from typing import override

class A:
    @property
    def prop(self) -> int: pass

class B(A):
    @override
    @property
    def prop(self) -> int: pass

class C(A):
    @property
    def prop(self) -> int: pass  # E: Method "prop" is not using @override but is overriding a method in class "__main__.A"
[typing fixtures/typing-override.pyi]
[builtins fixtures/property.pyi]

[case requireExplicitOverrideOverload]
# flags: --enable-error-code explicit-override --python-version 3.12
from typing import overload, override

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

class B(A):
    @overload
    def f(self, y: int) -> str: ...
    @overload
    def f(self, y: str) -> str: ...
    @override
    def f(self, y): pass

class C(A):
    @overload
    @override
    def f(self, y: int) -> str: ...
    @overload
    def f(self, y: str) -> str: ...
    def f(self, y): pass

class D(A):
    @overload
    def f(self, y: int) -> str: ...
    @overload
    def f(self, y: str) -> str: ...
    def f(self, y): pass  # E: Method "f" is not using @override but is overriding a method in class "__main__.A"
[typing fixtures/typing-override.pyi]

[case requireExplicitOverrideMultipleInheritance]
# flags: --enable-error-code explicit-override --python-version 3.12
from typing import override

class A:
    def f(self, x: int) -> str: pass
class B:
    def f(self, y: int) -> str: pass

class C(A, B):
    @override
    def f(self, z: int) -> str: pass

class D(A, B):
    def f(self, z: int) -> str: pass  # E: Method "f" is not using @override but is overriding a method in class "__main__.A"
[typing fixtures/typing-override.pyi]

[case testExplicitOverrideAllowedForPrivate]
# flags: --enable-error-code explicit-override --python-version 3.12

class B:
    def __f(self, y: int) -> str: pass

class C(B):
    def __f(self, y: int) -> str: pass  # OK
[typing fixtures/typing-override.pyi]

[case testOverrideUntypedDef]
# flags: --python-version 3.12
from typing import override

class Parent: pass

class Child(Parent):
    @override
    def foo(self, y): pass  # E: Method "foo" is marked as an override, but no base method was found with this name

[typing fixtures/typing-override.pyi]

[case testOverrideOnUnknownBaseClass]
# flags: --python-version 3.12
from typing import overload, override

from unknown import UnknownParent  # type: ignore[import-not-found]

class UnknownChild(UnknownParent):
    @override
    def foo(self, y): pass  # OK
    @override
    def bar(self, y: str) -> None: pass  # OK

    @override
    @overload
    def baz(self, y: str) -> None: ...
    @override
    @overload
    def baz(self, y: int) -> None: ...
    def baz(self, y: str | int) -> None: ...
[typing fixtures/typing-override.pyi]

[case testCallableProperty]
from typing import Callable

class something_callable:
    def __call__(self, fn) -> str: ...

def decorator(fn: Callable[..., int]) -> something_callable: ...

class A:
    @property
    @decorator
    def f(self) -> int: ...

reveal_type(A.f)  # N: Revealed type is "__main__.something_callable"
reveal_type(A().f)  # N: Revealed type is "builtins.str"
[builtins fixtures/property.pyi]

[case testFinalOverrideOnUntypedDef]
from typing import final

class Base:
    @final
    def foo(self):
        pass

class Derived(Base):
    def foo(self):  # E: Cannot override final attribute "foo" (previously declared in base class "Base")
        pass

[case testTypeVarIdClashPolymorphic]
from typing import Callable, Generic, TypeVar

A = TypeVar("A")
B = TypeVar("B")

class Gen(Generic[A]): ...

def id_(x: A) -> A: ...
def f(x: Gen[A], y: A) -> Gen[Gen[A]]: ...
def g(x: Gen[A], id_: Callable[[B], B], f: Callable[[A, B], Gen[A]]) -> A: ...

def test(x: Gen[Gen[A]]) -> Gen[A]:
    return g(x, id_, f)  # Technically OK

x: Gen[Gen[int]]
reveal_type(g(x, id_, f))  # N: Revealed type is "__main__.Gen[builtins.int]"

def h(x: A, y: A) -> A: ...
def gn(id_: Callable[[B], B], step: Callable[[A, B], A]) -> A: ...

def fn(x: A) -> A:
    return gn(id_, h)  # Technically OK

[case testTypeVarIdsNested]
from typing import Callable, TypeVar

A = TypeVar("A")
B = TypeVar("B")

def f(x: Callable[[A], A]) -> Callable[[B], B]:
    def g(x: B) -> B: ...
    return g

reveal_type(f(f))  # N: Revealed type is "def [B] (B`1) -> B`1"
reveal_type(f(f)(f))  # N: Revealed type is "def [A] (x: def (A`-1) -> A`-1) -> def [B] (B`-2) -> B`-2"

[case testGenericUnionFunctionJoin]
from typing import TypeVar, Union

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

def f(x: T, y: S) -> Union[T, S]: ...
def g(x: T, y: S) -> Union[T, S]: ...

x = [f, g]
reveal_type(x)  # N: Revealed type is "builtins.list[def [T, S] (x: T`4, y: S`5) -> Union[T`4, S`5]]"
[builtins fixtures/list.pyi]

[case testTypeVariableClashErrorMessage]
from typing import TypeVar

T = TypeVar("T")

class C:  # Note: Generic[T] missing
    def bad_idea(self, x: T) -> None:
        self.x = x

    def nope(self, x: T) -> None:
        self.x = x  # E: Incompatible types in assignment (expression has type "T@nope", variable has type "T@bad_idea")

[case testNoCrashOnBadCallablePropertyOverride]
from typing import Callable, Union

class C: ...
class D: ...

A = Callable[[C], None]
B = Callable[[D], None]

class Foo:
    @property
    def method(self) -> Callable[[int, Union[A, B]], None]:
        ...

class Bar(Foo):
    @property
    def method(self) -> Callable[[int, A], None]:  # E: Argument 2 of "method" is incompatible with supertype "Foo"; supertype defines the argument type as "Union[Callable[[C], None], Callable[[D], None]]" \
                                                   # N: This violates the Liskov substitution principle \
                                                   # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
        ...
[builtins fixtures/property.pyi]

[case testNoCrashOnUnpackOverride]
from typing import TypedDict, Unpack

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

class Other(TypedDict):
    x: int
    y: int

class B:
    def meth(self, **kwargs: Unpack[Params]) -> None:
        ...
class C(B):
    def meth(self, **kwargs: Unpack[Other]) -> None:  # E: Signature of "meth" incompatible with supertype "B" \
                                                      # N:      Superclass: \
                                                      # N:          def meth(*, x: int, y: str) -> None \
                                                      # N:      Subclass: \
                                                      # N:          def meth(*, x: int, y: int) -> None
        ...
[builtins fixtures/dict.pyi]
[typing fixtures/typing-full.pyi]

[case testOverrideErrorLocationNamed]
class B:
    def meth(
        self, *,
        x: int,
        y: str,
    ) -> None:
        ...
class C(B):
    def meth(
        self, *,
        y: int,  # E: Argument 1 of "meth" is incompatible with supertype "B"; supertype defines the argument type as "str" \
                 # N: This violates the Liskov substitution principle \
                 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
        x: int,
    ) -> None:
        ...
[builtins fixtures/tuple.pyi]

[case testLambdaAlwaysAllowed]
# flags: --disallow-untyped-calls
from typing import Callable, Optional

def func() -> Optional[str]: ...
var: Optional[str]

factory: Callable[[], Optional[str]]
for factory in (
    lambda: var,
    func,
):
    reveal_type(factory)  # N: Revealed type is "def () -> Union[builtins.str, None]"
    var = factory()
[builtins fixtures/tuple.pyi]

[case testLambdaInDeferredDecoratorNoCrash]
def foo(x):
    pass

class Bar:
    def baz(self, x):
        pass

class Qux(Bar):
    @foo(lambda x: None)
    def baz(self, x) -> None:
        pass
[builtins fixtures/tuple.pyi]

[case testGeneratorInDeferredDecoratorNoCrash]
from typing import Protocol, TypeVar

T = TypeVar("T", covariant=True)

class SupportsNext(Protocol[T]):
    def __next__(self) -> T: ...

def next(i: SupportsNext[T]) -> T: ...

def foo(x):
    pass

class Bar:
    def baz(self, x):
        pass

class Qux(Bar):
    @next(f for f in [foo])
    def baz(self, x) -> None:
        pass
[builtins fixtures/tuple.pyi]

[case testDistinctFormatting]
from typing import Awaitable, Callable, ParamSpec

P = ParamSpec("P")

class A: pass
class B(A): pass

def decorator(f: Callable[P, None]) -> Callable[[Callable[P, A]], None]:
    return lambda _: None

def key(x: int) -> None: ...
def fn_b(b: int) -> B: ...

decorator(key)(fn_b)  # E: Argument 1 has incompatible type "def fn_b(b: int) -> B"; expected "def (x: int) -> A"

def decorator2(f: Callable[P, None]) -> Callable[
    [Callable[P, Awaitable[None]]],
    Callable[P, Awaitable[None]],
]:
    return lambda f: f

def key2(x: int) -> None:
    ...

@decorator2(key2)  # E: Argument 1 has incompatible type "def foo2(y: int) -> Coroutine[Any, Any, None]"; expected "def (x: int) -> Awaitable[None]"
async def foo2(y: int) -> None:
    ...

class Parent:
    def method_without(self) -> "Parent": ...
    def method_with(self, param: str) -> "Parent": ...

class Child(Parent):
    method_without: Callable[[], "Child"]
    method_with: Callable[[str], "Child"]  # E: Incompatible types in assignment (expression has type "Callable[[str], Child]", base class "Parent" defined the type as "def method_with(self, param: str) -> Parent")
[builtins fixtures/tuple.pyi]

[case testDistinctFormattingUnion]
from typing import Callable, Union
from mypy_extensions import Arg

def f(x: Callable[[Arg(int, 'x')], None]) -> None: pass

y: Callable[[Union[int, str]], None]
f(y)  # E: Argument 1 to "f" has incompatible type "Callable[[Union[int, str]], None]"; expected "def (x: int) -> None"
[builtins fixtures/tuple.pyi]

[case testAbstractOverloadsWithoutImplementationAllowed]
from abc import abstractmethod
from typing import overload, Union

class Foo:
    @overload
    @abstractmethod
    def foo(self, value: int) -> int:
        ...
    @overload
    @abstractmethod
    def foo(self, value: str) -> str:
        ...

class Bar(Foo):
    @overload
    def foo(self, value: int) -> int:
        ...
    @overload
    def foo(self, value: str) -> str:
        ...

    def foo(self, value: Union[int, str]) -> Union[int, str]:
        return super().foo(value)  # E: Call to abstract method "foo" of "Foo" with trivial body via super() is unsafe

[case fullNamesOfImportedBaseClassesDisplayed]
from a import A

class B(A):
    def f(self, x: str) -> None:  # E: Argument 1 of "f" is incompatible with supertype "a.A"; supertype defines the argument type as "int" \
                                  # N: This violates the Liskov substitution principle \
                                  # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides
        ...
    def g(self, x: str) -> None:  # E: Signature of "g" incompatible with supertype "a.A" \
                                  # N:      Superclass: \
                                  # N:          def g(self) -> None \
                                  # N:      Subclass: \
                                  # N:          def g(self, x: str) -> None
        ...

[file a.py]
class A:
    def f(self, x: int) -> None:
        ...
    def g(self) -> None:
        ...

[case testBoundMethodsAssignedInClassBody]
from typing import Callable

class A:
    def f(self, x: int) -> str:
        pass
    @classmethod
    def g(cls, x: int) -> str:
        pass
    @staticmethod
    def h(x: int) -> str:
        pass
    attr: Callable[[int], str]

class C:
    x1 = A.f
    x2 = A.g
    x3 = A().f
    x4 = A().g
    x5 = A.h
    x6 = A().h
    x7 = A().attr

reveal_type(C.x1)  # N: Revealed type is "def (self: __main__.A, x: builtins.int) -> builtins.str"
reveal_type(C.x2)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C.x3)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C.x4)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C.x5)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C.x6)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C.x7)  # N: Revealed type is "def (builtins.int) -> builtins.str"

reveal_type(C().x1)  # E: Invalid self argument "C" to attribute function "x1" with type "Callable[[A, int], str]" \
                     # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C().x2)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C().x3)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C().x4)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C().x5)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C().x6)  # N: Revealed type is "def (x: builtins.int) -> builtins.str"
reveal_type(C().x7)  # E: Invalid self argument "C" to attribute function "x7" with type "Callable[[int], str]" \
                     # N: Revealed type is "def () -> builtins.str"
[builtins fixtures/classmethod.pyi]

[case testFunctionRedefinitionDeferred]
from typing import Callable, TypeVar

def outer() -> None:
    if bool():
        def inner() -> str: ...
    else:
        def inner() -> int: ...  # E: All conditional function variants must have identical signatures \
                                 # N: Original: \
                                 # N:     def inner() -> str \
                                 # N: Redefinition: \
                                 # N:     def inner() -> int
    x = defer()

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

@deco
def defer() -> int: ...
[builtins fixtures/list.pyi]

[case testCheckFunctionErrorContextDuplicateDeferred]
# flags: --show-error-context
from typing import Callable, TypeVar

def a() -> None:
    def b() -> None:
        1 + ""
        x = defer()

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

@deco
def defer() -> int: ...
[out]
main: note: In function "a":
main:6: error: Unsupported operand types for + ("int" and "str")

[case testNoExtraNoteForUnpacking]
from typing import Protocol

class P(Protocol):
    arg: int
    # Something that list and dict also have
    def __contains__(self, item: object) -> bool: ...

def foo(x: P, y: P) -> None: ...

args: list[object]
foo(*args)  # E: Argument 1 to "foo" has incompatible type "*list[object]"; expected "P"
kwargs: dict[str, object]
foo(**kwargs)  # E: Argument 1 to "foo" has incompatible type "**dict[str, object]"; expected "P"
[builtins fixtures/dict.pyi]