File size: 174,115 Bytes
a4edccc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 | diff --git a/Grammar/python.gram b/Grammar/python.gram
index 9698d6e2010..1212e8640a1 100644
--- a/Grammar/python.gram
+++ b/Grammar/python.gram
@@ -121,9 +121,9 @@ simple_stmts[asdl_stmt_seq*]:
simple_stmt[stmt_ty] (memo):
| assignment
| &"type" type_alias
+ | &('import' | 'from' | "lazy") import_stmt
| e=star_expressions { _PyAST_Expr(e, EXTRA) }
| &'return' return_stmt
- | &('import' | 'from') import_stmt
| &'raise' raise_stmt
| &'pass' pass_stmt
| &'del' del_stmt
@@ -216,7 +216,7 @@ assert_stmt[stmt_ty]:
| invalid_assert_stmt
| 'assert' a=expression b=[',' z=expression { z }] { _PyAST_Assert(a, b, EXTRA) }
-import_stmt[stmt_ty]:
+import_stmt[stmt_ty](memo):
| invalid_import
| import_name
| import_from
@@ -224,13 +224,15 @@ import_stmt[stmt_ty]:
# Import statements
# -----------------
-import_name[stmt_ty]: 'import' a=dotted_as_names { _PyAST_Import(a, EXTRA) }
+import_name[stmt_ty]:
+ | lazy="lazy"? 'import' a=dotted_as_names { _PyAST_Import(a, lazy ? 1 : 0, EXTRA) }
+
# note below: the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS
import_from[stmt_ty]:
- | 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets {
- _PyPegen_checked_future_import(p, b->v.Name.id, c, _PyPegen_seq_count_dots(a), EXTRA) }
- | 'from' a=('.' | '...')+ 'import' b=import_from_targets {
- _PyAST_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), EXTRA) }
+ | lazy="lazy"? 'from' a=('.' | '...')* b=dotted_name 'import' c=import_from_targets {
+ _PyPegen_checked_future_import(p, b->v.Name.id, c, _PyPegen_seq_count_dots(a), lazy, EXTRA) }
+ | lazy="lazy"? 'from' a=('.' | '...')+ 'import' b=import_from_targets {
+ _PyAST_ImportFrom(NULL, b, _PyPegen_seq_count_dots(a), lazy ? 1 : 0, EXTRA) }
import_from_targets[asdl_alias_seq*]:
| '(' a=import_from_as_names [','] ')' { a }
| import_from_as_names !','
diff --git a/Include/cpython/initconfig.h b/Include/cpython/initconfig.h
index 5606ebeb7c9..1ccc496c63a 100644
--- a/Include/cpython/initconfig.h
+++ b/Include/cpython/initconfig.h
@@ -191,6 +191,7 @@ typedef struct PyConfig {
int enable_gil;
int tlbc_enabled;
#endif
+ int lazy_imports;
/* --- Path configuration inputs ------------ */
int pathconfig_warnings;
diff --git a/Include/import.h b/Include/import.h
index d91ebe96ca8..cc7ad71f267 100644
--- a/Include/import.h
+++ b/Include/import.h
@@ -88,6 +88,20 @@ PyAPI_FUNC(int) PyImport_AppendInittab(
PyObject* (*initfunc)(void)
);
+typedef enum {
+ PyImport_LAZY_NORMAL,
+ PyImport_LAZY_ALL,
+ PyImport_LAZY_NONE,
+} PyImport_LazyImportsMode;
+
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(int) PyImport_SetLazyImportsMode(PyImport_LazyImportsMode mode);
+PyAPI_FUNC(int) PyImport_SetLazyImportsFilter(PyObject *filter);
+
+PyAPI_FUNC(PyImport_LazyImportsMode) PyImport_GetLazyImportsMode(void);
+PyAPI_FUNC(PyObject *) PyImport_GetLazyImportsFilter(void);
+#endif
+
#ifndef Py_LIMITED_API
# define Py_CPYTHON_IMPORT_H
# include "cpython/import.h"
diff --git a/Include/internal/pycore_ast.h b/Include/internal/pycore_ast.h
index 60367202bab..b47398669bb 100644
--- a/Include/internal/pycore_ast.h
+++ b/Include/internal/pycore_ast.h
@@ -329,12 +329,14 @@ struct _stmt {
struct {
asdl_alias_seq *names;
+ int is_lazy;
} Import;
struct {
identifier module;
asdl_alias_seq *names;
int level;
+ int is_lazy;
} ImportFrom;
struct {
@@ -764,11 +766,12 @@ stmt_ty _PyAST_TryStar(asdl_stmt_seq * body, asdl_excepthandler_seq * handlers,
end_col_offset, PyArena *arena);
stmt_ty _PyAST_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset,
int end_lineno, int end_col_offset, PyArena *arena);
-stmt_ty _PyAST_Import(asdl_alias_seq * names, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena);
+stmt_ty _PyAST_Import(asdl_alias_seq * names, int is_lazy, int lineno, int
+ col_offset, int end_lineno, int end_col_offset, PyArena
+ *arena);
stmt_ty _PyAST_ImportFrom(identifier module, asdl_alias_seq * names, int level,
- int lineno, int col_offset, int end_lineno, int
- end_col_offset, PyArena *arena);
+ int is_lazy, int lineno, int col_offset, int
+ end_lineno, int end_col_offset, PyArena *arena);
stmt_ty _PyAST_Global(asdl_identifier_seq * names, int lineno, int col_offset,
int end_lineno, int end_col_offset, PyArena *arena);
stmt_ty _PyAST_Nonlocal(asdl_identifier_seq * names, int lineno, int
diff --git a/Include/internal/pycore_ast_state.h b/Include/internal/pycore_ast_state.h
index d4ac419f51d..1caf200ee34 100644
--- a/Include/internal/pycore_ast_state.h
+++ b/Include/internal/pycore_ast_state.h
@@ -205,6 +205,7 @@ struct ast_state {
PyObject *id;
PyObject *ifs;
PyObject *is_async;
+ PyObject *is_lazy;
PyObject *items;
PyObject *iter;
PyObject *key;
diff --git a/Include/internal/pycore_ceval.h b/Include/internal/pycore_ceval.h
index e9f1f65e53c..1ee1f830827 100644
--- a/Include/internal/pycore_ceval.h
+++ b/Include/internal/pycore_ceval.h
@@ -310,7 +310,19 @@ PyAPI_FUNC(void) _PyEval_FormatExcCheckArg(PyThreadState *tstate, PyObject *exc,
PyAPI_FUNC(void) _PyEval_FormatExcUnbound(PyThreadState *tstate, PyCodeObject *co, int oparg);
PyAPI_FUNC(void) _PyEval_FormatKwargsError(PyThreadState *tstate, PyObject *func, PyObject *kwargs);
PyAPI_FUNC(PyObject *) _PyEval_ImportFrom(PyThreadState *, PyObject *, PyObject *);
-PyAPI_FUNC(PyObject *) _PyEval_ImportName(PyThreadState *, _PyInterpreterFrame *, PyObject *, PyObject *, PyObject *);
+
+PyAPI_FUNC(PyObject *) _PyEval_LazyImportName(
+ PyThreadState *tstate, PyObject *builtins, PyObject *globals,
+ PyObject *locals, PyObject *name, PyObject *fromlist, PyObject *level,
+ int lazy);
+PyAPI_FUNC(PyObject *) _PyEval_LazyImportFrom(
+ PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *v, PyObject *name);
+PyAPI_FUNC(PyObject *) _PyEval_ImportName(
+ PyThreadState *tstate, PyObject *builtins, PyObject *globals,
+ PyObject *locals, PyObject *name, PyObject *fromlist, PyObject *level);
+PyObject * _PyEval_ImportNameWithImport(
+ PyThreadState *tstate, PyObject *import_func, PyObject *globals,
+ PyObject *locals, PyObject *name, PyObject *fromlist, PyObject *level);
PyAPI_FUNC(PyObject *)_PyEval_MatchClass(PyThreadState *tstate, PyObject *subject, PyObject *type, Py_ssize_t nargs, PyObject *kwargs);
PyAPI_FUNC(PyObject *)_PyEval_MatchKeys(PyThreadState *tstate, PyObject *map, PyObject *keys);
PyAPI_FUNC(void) _PyEval_MonitorRaise(PyThreadState *tstate, _PyInterpreterFrame *frame, _Py_CODEUNIT *instr);
diff --git a/Include/internal/pycore_compile.h b/Include/internal/pycore_compile.h
index 527141b54d0..911cc1f10f1 100644
--- a/Include/internal/pycore_compile.h
+++ b/Include/internal/pycore_compile.h
@@ -131,6 +131,7 @@ int _PyCompile_PushFBlock(struct _PyCompiler *c, _Py_SourceLocation loc,
void _PyCompile_PopFBlock(struct _PyCompiler *c, enum _PyCompile_FBlockType t,
_PyJumpTargetLabel block_label);
_PyCompile_FBlockInfo *_PyCompile_TopFBlock(struct _PyCompiler *c);
+bool _PyCompile_InExceptionHandler(struct _PyCompiler *c);
int _PyCompile_EnterScope(struct _PyCompiler *c, identifier name, int scope_type,
void *key, int lineno, PyObject *private,
diff --git a/Include/internal/pycore_dict.h b/Include/internal/pycore_dict.h
index 950547cb002..379bf6a8178 100644
--- a/Include/internal/pycore_dict.h
+++ b/Include/internal/pycore_dict.h
@@ -36,6 +36,8 @@ extern int _PyDict_DelItem_KnownHash_LockHeld(PyObject *mp, PyObject *key,
extern int _PyDict_Contains_KnownHash(PyObject *, PyObject *, Py_hash_t);
+extern void _PyDict_ClearKeysVersionLockHeld(PyObject *mp);
+
extern int _PyDict_Next(
PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash);
@@ -264,6 +266,13 @@ static inline PyDictUnicodeEntry* DK_UNICODE_ENTRIES(PyDictKeysObject *dk) {
#define DICT_UNIQUE_ID_SHIFT (32)
#define DICT_UNIQUE_ID_MAX ((UINT64_C(1) << (64 - DICT_UNIQUE_ID_SHIFT)) - 1)
+/* The first three dict watcher IDs are reserved for CPython,
+ * so we don't need to check that they haven't been used */
+#define BUILTINS_WATCHER_ID 0
+#define GLOBALS_WATCHER_ID 1
+#define MODULE_WATCHER_ID 2
+#define FIRST_AVAILABLE_WATCHER 3
+
PyAPI_FUNC(void)
_PyDict_SendEvent(int watcher_bits,
diff --git a/Include/internal/pycore_global_objects_fini_generated.h b/Include/internal/pycore_global_objects_fini_generated.h
index 09b8762ee2d..64e3438f915 100644
--- a/Include/internal/pycore_global_objects_fini_generated.h
+++ b/Include/internal/pycore_global_objects_fini_generated.h
@@ -1446,6 +1446,8 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) {
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__iter__));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__itruediv__));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__ixor__));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__lazy_import__));
+ _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__lazy_modules__));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__le__));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__len__));
_PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(__length_hint__));
diff --git a/Include/internal/pycore_global_strings.h b/Include/internal/pycore_global_strings.h
index 040f79afeeb..78ed30dd7f6 100644
--- a/Include/internal/pycore_global_strings.h
+++ b/Include/internal/pycore_global_strings.h
@@ -169,6 +169,8 @@ struct _Py_global_strings {
STRUCT_FOR_ID(__iter__)
STRUCT_FOR_ID(__itruediv__)
STRUCT_FOR_ID(__ixor__)
+ STRUCT_FOR_ID(__lazy_import__)
+ STRUCT_FOR_ID(__lazy_modules__)
STRUCT_FOR_ID(__le__)
STRUCT_FOR_ID(__len__)
STRUCT_FOR_ID(__length_hint__)
diff --git a/Include/internal/pycore_import.h b/Include/internal/pycore_import.h
index 4c8b8c0ed86..32ed3a62b2b 100644
--- a/Include/internal/pycore_import.h
+++ b/Include/internal/pycore_import.h
@@ -32,6 +32,18 @@ extern int _PyImport_FixupBuiltin(
PyObject *modules
);
+extern PyObject * _PyImport_ResolveName(
+ PyThreadState *tstate, PyObject *name, PyObject *globals, int level);
+extern PyObject * _PyImport_GetAbsName(
+ PyThreadState *tstate, PyObject *name, PyObject *globals, int level);
+// Symbol is exported for the JIT on Windows builds.
+PyAPI_FUNC(PyObject *) _PyImport_LoadLazyImportTstate(
+ PyThreadState *tstate, PyObject *lazy_import);
+extern PyObject * _PyImport_LazyImportModuleLevelObject(
+ PyThreadState *tstate, PyObject *name, PyObject *builtins,
+ PyObject *globals, PyObject *locals, PyObject *fromlist, int level);
+
+
#ifdef HAVE_DLOPEN
# include <dlfcn.h> // RTLD_NOW, RTLD_LAZY
# if HAVE_DECL_RTLD_NOW
@@ -69,11 +81,19 @@ extern void _PyImport_ClearModules(PyInterpreterState *interp);
extern void _PyImport_ClearModulesByIndex(PyInterpreterState *interp);
+extern PyObject * _PyImport_InitLazyModules(
+ PyInterpreterState *interp);
+extern void _PyImport_ClearLazyModules(PyInterpreterState *interp);
+
extern int _PyImport_InitDefaultImportFunc(PyInterpreterState *interp);
extern int _PyImport_IsDefaultImportFunc(
PyInterpreterState *interp,
PyObject *func);
+extern int _PyImport_IsDefaultLazyImportFunc(
+ PyInterpreterState *interp,
+ PyObject *func);
+
extern PyObject * _PyImport_GetImportlibLoader(
PyInterpreterState *interp,
const char *loader_name);
diff --git a/Include/internal/pycore_interp_structs.h b/Include/internal/pycore_interp_structs.h
index 723657e4cef..3ebc8967c3d 100644
--- a/Include/internal/pycore_interp_structs.h
+++ b/Include/internal/pycore_interp_structs.h
@@ -324,6 +324,14 @@ struct _import_state {
int dlopenflags;
#endif
PyObject *import_func;
+ PyObject *lazy_import_func;
+ int lazy_imports_mode;
+ PyObject *lazy_imports_filter;
+ PyObject *lazy_importing_modules;
+ PyObject *lazy_modules;
+#ifdef Py_GIL_DISABLED
+ PyMutex lazy_mutex;
+#endif
/* The global import lock. */
_PyRecursiveMutex lock;
/* diagnostic info in PyImport_ImportModuleLevelObject() */
diff --git a/Include/internal/pycore_lazyimportobject.h b/Include/internal/pycore_lazyimportobject.h
new file mode 100644
index 00000000000..b81e4211b08
--- /dev/null
+++ b/Include/internal/pycore_lazyimportobject.h
@@ -0,0 +1,35 @@
+// Lazy object interface.
+
+#ifndef Py_INTERNAL_LAZYIMPORTOBJECT_H
+#define Py_INTERNAL_LAZYIMPORTOBJECT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef Py_BUILD_CORE
+# error "this header requires Py_BUILD_CORE define"
+#endif
+
+PyAPI_DATA(PyTypeObject) PyLazyImport_Type;
+#define PyLazyImport_CheckExact(op) Py_IS_TYPE((op), &PyLazyImport_Type)
+
+typedef struct {
+ PyObject_HEAD
+ PyObject *lz_builtins;
+ PyObject *lz_from;
+ PyObject *lz_attr;
+ // Frame information for the original import location.
+ PyCodeObject *lz_code; // Code object where the lazy import was created.
+ int lz_instr_offset; // Instruction offset where the lazy import was created.
+} PyLazyImportObject;
+
+
+PyAPI_FUNC(PyObject *) _PyLazyImport_GetName(PyObject *lazy_import);
+PyAPI_FUNC(PyObject *) _PyLazyImport_New(
+ struct _PyInterpreterFrame *frame, PyObject *import_func, PyObject *from, PyObject *attr);
+
+#ifdef __cplusplus
+}
+#endif
+#endif // !Py_INTERNAL_LAZYIMPORTOBJECT_H
diff --git a/Include/internal/pycore_magic_number.h b/Include/internal/pycore_magic_number.h
index 919a2ec0d1a..3fcf650426d 100644
--- a/Include/internal/pycore_magic_number.h
+++ b/Include/internal/pycore_magic_number.h
@@ -286,11 +286,12 @@ Known values:
Python 3.15a1 3653 (Fix handling of opcodes that may leave operands on the stack when optimizing LOAD_FAST)
Python 3.15a1 3654 (Fix missing exception handlers in logical expression)
Python 3.15a1 3655 (Fix miscompilation of some module-level annotations)
- Python 3.15a2 3656 (Add TRACE_RECORD instruction, for platforms with switch based interpreter)
+ Python 3.15a1 3656 (Add TRACE_RECORD instruction, for platforms with switch based interpreter)
Python 3.15a4 3657 (Add BINARY_OP_SUBSCR_USTR_INT)
Python 3.15a4 3658 (Optimize bytecode for list/set called on genexp)
Python 3.15a4 3659 (Add CALL_FUNCTION_EX specialization)
Python 3.15a4 3660 (Change generator preamble code)
+ Python 3.15a4 3661 (Lazy imports IMPORT_NAME opcode changes)
Python 3.16 will start with 3700
@@ -304,7 +305,7 @@ PC/launcher.c must also be updated.
*/
-#define PYC_MAGIC_NUMBER 3660
+#define PYC_MAGIC_NUMBER 3661
/* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes
(little-endian) and then appending b'\r\n'. */
#define PYC_MAGIC_NUMBER_TOKEN \
diff --git a/Include/internal/pycore_moduleobject.h b/Include/internal/pycore_moduleobject.h
index 9a62daf6621..7882ce03323 100644
--- a/Include/internal/pycore_moduleobject.h
+++ b/Include/internal/pycore_moduleobject.h
@@ -19,6 +19,8 @@ extern int _PyModule_IsPossiblyShadowing(PyObject *);
extern int _PyModule_IsExtension(PyObject *obj);
+extern int _PyModule_InitModuleDictWatcher(PyInterpreterState *interp);
+
typedef int (*_Py_modexecfunc)(PyObject *);
typedef struct {
diff --git a/Include/internal/pycore_runtime_init_generated.h b/Include/internal/pycore_runtime_init_generated.h
index f4ea7b7954b..d4b7b090f93 100644
--- a/Include/internal/pycore_runtime_init_generated.h
+++ b/Include/internal/pycore_runtime_init_generated.h
@@ -1444,6 +1444,8 @@ extern "C" {
INIT_ID(__iter__), \
INIT_ID(__itruediv__), \
INIT_ID(__ixor__), \
+ INIT_ID(__lazy_import__), \
+ INIT_ID(__lazy_modules__), \
INIT_ID(__le__), \
INIT_ID(__len__), \
INIT_ID(__length_hint__), \
diff --git a/Include/internal/pycore_symtable.h b/Include/internal/pycore_symtable.h
index c0164507ea0..e1176c65c5c 100644
--- a/Include/internal/pycore_symtable.h
+++ b/Include/internal/pycore_symtable.h
@@ -126,6 +126,7 @@ typedef struct _symtable_entry {
unsigned ste_method : 1; /* true if block is a function block defined in class scope */
unsigned ste_has_conditional_annotations : 1; /* true if block has conditionally executed annotations */
unsigned ste_in_conditional_block : 1; /* set while we are inside a conditionally executed block */
+ unsigned ste_in_try_block : 1; /* set while we are inside a try/except block */
unsigned ste_in_unevaluated_annotation : 1; /* set while we are processing an annotation that will not be evaluated */
int ste_comp_iter_expr; /* non-zero if visiting a comprehension range expression */
_Py_SourceLocation ste_loc; /* source location of block */
diff --git a/Include/internal/pycore_unicodeobject_generated.h b/Include/internal/pycore_unicodeobject_generated.h
index f9677d01228..d843674f180 100644
--- a/Include/internal/pycore_unicodeobject_generated.h
+++ b/Include/internal/pycore_unicodeobject_generated.h
@@ -456,6 +456,14 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) {
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_ID(__lazy_import__);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
+ string = &_Py_ID(__lazy_modules__);
+ _PyUnicode_InternStatic(interp, &string);
+ assert(_PyUnicode_CheckConsistency(string, 1));
+ assert(PyUnicode_GET_LENGTH(string) != 1);
string = &_Py_ID(__le__);
_PyUnicode_InternStatic(interp, &string);
assert(_PyUnicode_CheckConsistency(string, 1));
diff --git a/Include/pyerrors.h b/Include/pyerrors.h
index 5d0028c116e..cfabbc5fe8d 100644
--- a/Include/pyerrors.h
+++ b/Include/pyerrors.h
@@ -91,6 +91,9 @@ PyAPI_DATA(PyObject *) PyExc_EOFError;
PyAPI_DATA(PyObject *) PyExc_FloatingPointError;
PyAPI_DATA(PyObject *) PyExc_OSError;
PyAPI_DATA(PyObject *) PyExc_ImportError;
+#if !defined(Py_LIMITED_API)
+PyAPI_DATA(PyObject *) PyExc_ImportCycleError;
+#endif
#if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03060000
PyAPI_DATA(PyObject *) PyExc_ModuleNotFoundError;
#endif
diff --git a/Lib/_compat_pickle.py b/Lib/_compat_pickle.py
index a9813264324..928db663b44 100644
--- a/Lib/_compat_pickle.py
+++ b/Lib/_compat_pickle.py
@@ -240,6 +240,7 @@
REVERSE_NAME_MAPPING[('builtins', excname)] = ('exceptions', 'OSError')
PYTHON3_IMPORTERROR_EXCEPTIONS = (
+ 'ImportCycleError',
'ModuleNotFoundError',
)
diff --git a/Lib/_pyrepl/utils.py b/Lib/_pyrepl/utils.py
index 06cddef851b..25d7ac1bd0b 100644
--- a/Lib/_pyrepl/utils.py
+++ b/Lib/_pyrepl/utils.py
@@ -276,6 +276,12 @@ def is_soft_keyword_used(*tokens: TI | None) -> bool:
TI(T.NAME, string=s)
):
return not keyword.iskeyword(s)
+ case (
+ None | TI(T.NEWLINE) | TI(T.INDENT) | TI(T.DEDENT) | TI(string=":" | ";"),
+ TI(string="lazy"),
+ TI(string="import") | TI(string="from")
+ ):
+ return True
case _:
return False
diff --git a/Lib/dis.py b/Lib/dis.py
index 8c257d118fb..58c7f641903 100644
--- a/Lib/dis.py
+++ b/Lib/dis.py
@@ -35,6 +35,7 @@
FUNCTION_ATTR_FLAGS = ('defaults', 'kwdefaults', 'annotations', 'closure', 'annotate')
ENTER_EXECUTOR = opmap['ENTER_EXECUTOR']
+IMPORT_NAME = opmap['IMPORT_NAME']
LOAD_GLOBAL = opmap['LOAD_GLOBAL']
LOAD_SMALL_INT = opmap['LOAD_SMALL_INT']
BINARY_OP = opmap['BINARY_OP']
@@ -600,6 +601,12 @@ def get_argval_argrepr(self, op, arg, offset):
argval, argrepr = _get_name_info(arg//4, get_name)
if (arg & 1) and argrepr:
argrepr = f"{argrepr} + NULL|self"
+ elif deop == IMPORT_NAME:
+ argval, argrepr = _get_name_info(arg//4, get_name)
+ if (arg & 1) and argrepr:
+ argrepr = f"{argrepr} + lazy"
+ elif (arg & 2) and argrepr:
+ argrepr = f"{argrepr} + eager"
else:
argval, argrepr = _get_name_info(arg, get_name)
elif deop in hasjump or deop in hasexc:
@@ -1012,7 +1019,9 @@ def _find_imports(co):
(level_op[0] in hasconst or level_op[0] == LOAD_SMALL_INT)):
level = _get_const_value(level_op[0], level_op[1], consts)
fromlist = _get_const_value(from_op[0], from_op[1], consts)
- yield (names[oparg], level, fromlist)
+ # IMPORT_NAME encodes lazy/eager flags in bits 0-1,
+ # name index in bits 2+.
+ yield (names[oparg >> 2], level, fromlist)
def _find_store_names(co):
"""Find names of variables which are written in the code
diff --git a/Lib/idlelib/colorizer.py b/Lib/idlelib/colorizer.py
index bffa2ddd3cd..6db38de3aa6 100644
--- a/Lib/idlelib/colorizer.py
+++ b/Lib/idlelib/colorizer.py
@@ -42,6 +42,11 @@ def make_pat():
]) +
r"))"
)
+ lazy_softkw = (
+ r"^[ \t]*" + # at beginning of line + possible indentation
+ r"(?P<LAZY_SOFTKW>lazy)" +
+ r"(?=[ \t]+(?:import|from)\b)" # followed by 'import' or 'from'
+ )
builtinlist = [str(name) for name in dir(builtins)
if not name.startswith('_') and
name not in keyword.kwlist]
@@ -56,7 +61,7 @@ def make_pat():
prog = re.compile("|".join([
builtin, comment, string, kw,
match_softkw, case_default,
- case_softkw_and_pattern,
+ case_softkw_and_pattern, lazy_softkw,
any("SYNC", [r"\n"]),
]),
re.DOTALL | re.MULTILINE)
@@ -70,6 +75,7 @@ def make_pat():
"CASE_SOFTKW": "KEYWORD",
"CASE_DEFAULT_UNDERSCORE": "KEYWORD",
"CASE_SOFTKW2": "KEYWORD",
+ "LAZY_SOFTKW": "KEYWORD",
}
diff --git a/Lib/importlib/_bootstrap.py b/Lib/importlib/_bootstrap.py
index cfcebb73098..45beb51659f 100644
--- a/Lib/importlib/_bootstrap.py
+++ b/Lib/importlib/_bootstrap.py
@@ -1256,6 +1256,12 @@ def _find_and_load_unlocked(name, import_):
except AttributeError:
msg = f"Cannot set an attribute on {parent!r} for child module {child!r}"
_warnings.warn(msg, ImportWarning)
+ # Set attributes to lazy submodules on the module.
+ try:
+ _imp._set_lazy_attributes(module, name)
+ except Exception as e:
+ msg = f"Cannot set lazy attributes on {name!r}: {e!r}"
+ _warnings.warn(msg, ImportWarning)
return module
diff --git a/Lib/keyword.py b/Lib/keyword.py
index e22c837835e..98ffe2de28b 100644
--- a/Lib/keyword.py
+++ b/Lib/keyword.py
@@ -56,6 +56,7 @@ kwlist = [
softkwlist = [
'_',
'case',
+ 'lazy',
'match',
'type'
]
diff --git a/Lib/rlcompleter.py b/Lib/rlcompleter.py
index 23eb0020f42..e8cef29d004 100644
--- a/Lib/rlcompleter.py
+++ b/Lib/rlcompleter.py
@@ -36,6 +36,7 @@
import re
import __main__
import warnings
+import types
__all__ = ["Completer"]
@@ -188,7 +189,17 @@ def attr_matches(self, text):
# property method, which is not desirable.
matches.append(match)
continue
- if (value := getattr(thisobject, word, None)) is not None:
+
+ if (isinstance(thisobject, types.ModuleType)
+ and
+ isinstance(thisobject.__dict__.get(word),
+ types.LazyImportType)
+ ):
+ value = thisobject.__dict__.get(word)
+ else:
+ value = getattr(thisobject, word, None)
+
+ if value is not None:
matches.append(self._callable_postfix(value, match))
else:
matches.append(match)
diff --git a/Lib/traceback.py b/Lib/traceback.py
index 97d83f3ddd3..b121733c27f 100644
--- a/Lib/traceback.py
+++ b/Lib/traceback.py
@@ -5,6 +5,7 @@
import linecache
import sys
import textwrap
+import types
import warnings
import codeop
import keyword
@@ -1629,12 +1630,29 @@ def _substitution_cost(ch_a, ch_b):
return _MOVE_COST
+def _is_lazy_import(obj, attr_name):
+ """Check if attr_name in obj's __dict__ is a lazy import.
+
+ Returns True if obj is a module and the attribute is a LazyImportType,
+ False otherwise. This avoids triggering module loading when computing
+ suggestions for AttributeError.
+ """
+ if not isinstance(obj, types.ModuleType):
+ return False
+ obj_dict = getattr(obj, '__dict__', None)
+ if obj_dict is None:
+ return False
+ attr_value = obj_dict.get(attr_name)
+ return isinstance(attr_value, types.LazyImportType)
+
+
def _check_for_nested_attribute(obj, wrong_name, attrs):
"""Check if any attribute of obj has the wrong_name as a nested attribute.
Returns the first nested attribute suggestion found, or None.
Limited to checking 20 attributes.
Only considers non-descriptor attributes to avoid executing arbitrary code.
+ Skips lazy imports to avoid triggering module loading.
"""
# Check for nested attributes (only one level deep)
attrs_to_check = [x for x in attrs if not x.startswith('_')][:20] # Limit number of attributes to check
@@ -1645,6 +1663,10 @@ def _check_for_nested_attribute(obj, wrong_name, attrs):
if attr_from_class is not None and hasattr(attr_from_class, '__get__'):
continue # Skip descriptors to avoid executing arbitrary code
+ # Skip lazy imports to avoid triggering module loading
+ if _is_lazy_import(obj, attr_name):
+ continue
+
# Safe to get the attribute since it's not a descriptor
attr_obj = getattr(obj, attr_name)
@@ -1675,6 +1697,8 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
except TypeError: # Attributes are unsortable, e.g. int and str
d = list(obj.__class__.__dict__.keys()) + list(obj.__dict__.keys())
d = sorted([x for x in d if isinstance(x, str)])
+ # Filter out lazy imports to avoid triggering module loading
+ d = [x for x in d if not _is_lazy_import(obj, x)]
hide_underscored = (wrong_name[:1] != '_')
if hide_underscored and tb is not None:
while tb.tb_next is not None:
@@ -1694,6 +1718,8 @@ def _compute_suggestion_error(exc_value, tb, wrong_name):
except TypeError: # Attributes are unsortable, e.g. int and str
d = list(mod.__dict__.keys())
d = sorted([x for x in d if isinstance(x, str)])
+ # Filter out lazy imports to avoid triggering module loading
+ d = [x for x in d if not _is_lazy_import(mod, x)]
if wrong_name[:1] != '_':
d = [x for x in d if x[:1] != '_']
except Exception:
diff --git a/Lib/types.py b/Lib/types.py
index 99f23c3f442..b4f9a5c5140 100644
--- a/Lib/types.py
+++ b/Lib/types.py
@@ -76,6 +76,9 @@ def _m(self): pass
# CapsuleType cannot be accessed from pure Python,
# so there is no fallback definition.
+ # LazyImportType in pure Python cannot be guaranteed
+ # without overriding the filter, so there is no fallback.
+
del sys, _f, _g, _C, _c, _ag, _cell_factory # Not for export
diff --git a/Makefile.pre.in b/Makefile.pre.in
index d27e3301666..f4119abf324 100644
--- a/Makefile.pre.in
+++ b/Makefile.pre.in
@@ -539,6 +539,7 @@ OBJECT_OBJS= \
Objects/funcobject.o \
Objects/interpolationobject.o \
Objects/iterobject.o \
+ Objects/lazyimportobject.o \
Objects/listobject.o \
Objects/longobject.o \
Objects/dictobject.o \
@@ -1372,6 +1373,7 @@ PYTHON_HEADERS= \
$(srcdir)/Include/internal/pycore_interpolation.h \
$(srcdir)/Include/internal/pycore_intrinsics.h \
$(srcdir)/Include/internal/pycore_jit.h \
+ $(srcdir)/Include/internal/pycore_lazyimportobject.h \
$(srcdir)/Include/internal/pycore_list.h \
$(srcdir)/Include/internal/pycore_llist.h \
$(srcdir)/Include/internal/pycore_lock.h \
@@ -2676,6 +2678,8 @@ TESTSUBDIRS= idlelib/idle_test \
test/test_import/data/package3 \
test/test_import/data/package4 \
test/test_import/data/unwritable \
+ test/test_import/data/lazy_imports \
+ test/test_import/data/lazy_imports/pkg \
test/test_importlib \
test/test_importlib/builtin \
test/test_importlib/extension \
diff --git a/Modules/_testcapi/import.c b/Modules/_testcapi/import.c
index 27d37498f3c..ebb1032fdd1 100644
--- a/Modules/_testcapi/import.c
+++ b/Modules/_testcapi/import.c
@@ -30,9 +30,75 @@ pyimport_importmoduleattrstring(PyObject *self, PyObject *args)
}
+static PyObject *
+pyimport_setlazyimportsmode(PyObject *self, PyObject *args)
+{
+ PyObject *mode;
+ if (!PyArg_ParseTuple(args, "U", &mode)) {
+ return NULL;
+ }
+ if (strcmp(PyUnicode_AsUTF8(mode), "normal") == 0) {
+ PyImport_SetLazyImportsMode(PyImport_LAZY_NORMAL);
+ } else if (strcmp(PyUnicode_AsUTF8(mode), "all") == 0) {
+ PyImport_SetLazyImportsMode(PyImport_LAZY_ALL);
+ } else if (strcmp(PyUnicode_AsUTF8(mode), "none") == 0) {
+ PyImport_SetLazyImportsMode(PyImport_LAZY_NONE);
+ } else {
+ PyErr_SetString(PyExc_ValueError, "invalid mode");
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+pyimport_getlazyimportsmode(PyObject *self, PyObject *args)
+{
+ switch (PyImport_GetLazyImportsMode()) {
+ case PyImport_LAZY_NORMAL:
+ return PyUnicode_FromString("normal");
+ case PyImport_LAZY_ALL:
+ return PyUnicode_FromString("all");
+ case PyImport_LAZY_NONE:
+ return PyUnicode_FromString("none");
+ default:
+ PyErr_SetString(PyExc_ValueError, "unknown mode");
+ return NULL;
+ }
+}
+
+static PyObject *
+pyimport_setlazyimportsfilter(PyObject *self, PyObject *args)
+{
+ PyObject *filter;
+ if (!PyArg_ParseTuple(args, "O", &filter)) {
+ return NULL;
+ }
+
+ if (PyImport_SetLazyImportsFilter(filter) < 0) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+static PyObject *
+pyimport_getlazyimportsfilter(PyObject *self, PyObject *args)
+{
+ PyObject *res = PyImport_GetLazyImportsFilter();
+ if (res == NULL) {
+ Py_RETURN_NONE;
+ }
+ return res;
+}
+
static PyMethodDef test_methods[] = {
{"PyImport_ImportModuleAttr", pyimport_importmoduleattr, METH_VARARGS},
{"PyImport_ImportModuleAttrString", pyimport_importmoduleattrstring, METH_VARARGS},
+ {"PyImport_SetLazyImportsMode", pyimport_setlazyimportsmode, METH_VARARGS},
+ {"PyImport_GetLazyImportsMode", pyimport_getlazyimportsmode, METH_NOARGS},
+ {"PyImport_SetLazyImportsFilter", pyimport_setlazyimportsfilter, METH_VARARGS},
+ {"PyImport_GetLazyImportsFilter", pyimport_getlazyimportsfilter, METH_NOARGS},
{NULL},
};
@@ -41,4 +107,3 @@ _PyTestCapi_Init_Import(PyObject *m)
{
return PyModule_AddFunctions(m, test_methods);
}
-
diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h
index 35b1bc4e17c..ddd8fcdc231 100644
--- a/Modules/_testinternalcapi/test_cases.c.h
+++ b/Modules/_testinternalcapi/test_cases.c.h
@@ -6371,9 +6371,19 @@
_PyStackRef res;
from = stack_pointer[-1];
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
- _PyFrame_SetStackPointer(frame, stack_pointer);
- PyObject *res_o = _PyEval_ImportFrom(tstate, PyStackRef_AsPyObjectBorrow(from), name);
- stack_pointer = _PyFrame_GetStackPointer(frame);
+ PyObject *res_o;
+ if (PyLazyImport_CheckExact(PyStackRef_AsPyObjectBorrow(from))) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_LazyImportFrom(
+ tstate, frame, PyStackRef_AsPyObjectBorrow(from), name);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
+ else {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_ImportFrom(
+ tstate, PyStackRef_AsPyObjectBorrow(from), name);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
if (res_o == NULL) {
JUMP_TO_LABEL(error);
}
@@ -6397,11 +6407,26 @@
_PyStackRef res;
fromlist = stack_pointer[-1];
level = stack_pointer[-2];
- PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
+ PyObject *name = GETITEM(FRAME_CO_NAMES, oparg >> 2);
+ PyObject *res_o;
+ if (!(oparg & 0x02)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_LazyImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level),
+ oparg & 0x01);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
+ else {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_ImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level));
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
_PyFrame_SetStackPointer(frame, stack_pointer);
- PyObject *res_o = _PyEval_ImportName(tstate, frame, name,
- PyStackRef_AsPyObjectBorrow(fromlist),
- PyStackRef_AsPyObjectBorrow(level));
_PyStackRef tmp = fromlist;
fromlist = PyStackRef_NULL;
stack_pointer[-1] = fromlist;
@@ -9156,6 +9181,15 @@
}
JUMP_TO_LABEL(error);
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (v_o == NULL) {
+ JUMP_TO_LABEL(error);
+ }
+ }
}
else {
_PyFrame_SetStackPointer(frame, stack_pointer);
@@ -9180,6 +9214,15 @@
JUMP_TO_LABEL(error);
}
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (v_o == NULL) {
+ JUMP_TO_LABEL(error);
+ }
+ }
}
}
v = PyStackRef_FromPyObjectSteal(v_o);
@@ -9432,6 +9475,30 @@
if (v_o == NULL) {
JUMP_TO_LABEL(error);
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (l_v == NULL) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_DECREF(v_o);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ JUMP_TO_LABEL(error);
+ }
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ int err = PyDict_SetItem(GLOBALS(), name, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (err < 0) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_DECREF(v_o);
+ Py_DECREF(l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ JUMP_TO_LABEL(error);
+ }
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
v = PyStackRef_FromPyObjectSteal(v_o);
stack_pointer[0] = v;
stack_pointer += 1;
diff --git a/Modules/_typesmodule.c b/Modules/_typesmodule.c
index df6b4c93cb8..6c9e7a0a3ba 100644
--- a/Modules/_typesmodule.c
+++ b/Modules/_typesmodule.c
@@ -2,6 +2,7 @@
#include "Python.h"
#include "pycore_descrobject.h" // _PyMethodWrapper_Type
+#include "pycore_lazyimportobject.h" // PyLazyImport_Type
#include "pycore_namespace.h" // _PyNamespace_Type
#include "pycore_object.h" // _PyNone_Type, _PyNotImplemented_Type
#include "pycore_unionobject.h" // _PyUnion_Type
@@ -35,6 +36,7 @@ _types_exec(PyObject *m)
EXPORT_STATIC_TYPE("GetSetDescriptorType", PyGetSetDescr_Type);
// LambdaType is the same as FunctionType
EXPORT_STATIC_TYPE("LambdaType", PyFunction_Type);
+ EXPORT_STATIC_TYPE("LazyImportType", PyLazyImport_Type);
EXPORT_STATIC_TYPE("MappingProxyType", PyDictProxy_Type);
EXPORT_STATIC_TYPE("MemberDescriptorType", PyMemberDescr_Type);
EXPORT_STATIC_TYPE("MethodDescriptorType", PyMethodDescr_Type);
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index c1584be3f0e..ae7bf61767d 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -4693,6 +4693,14 @@ _PyDict_SizeOf_LockHeld(PyDictObject *mp)
return (Py_ssize_t)res;
}
+void
+_PyDict_ClearKeysVersionLockHeld(PyObject *mp)
+{
+ ASSERT_DICT_LOCKED(mp);
+
+ FT_ATOMIC_STORE_UINT32_RELAXED(((PyDictObject *)mp)->ma_keys->dk_version, 0);
+}
+
Py_ssize_t
_PyDict_SizeOf(PyDictObject *mp)
{
@@ -7655,8 +7663,8 @@ PyDict_AddWatcher(PyDict_WatchCallback callback)
{
PyInterpreterState *interp = _PyInterpreterState_GET();
- /* Start at 2, as 0 and 1 are reserved for CPython */
- for (int i = 2; i < DICT_MAX_WATCHERS; i++) {
+ /* Some watchers are reserved for CPython, start at the first available one */
+ for (int i = FIRST_AVAILABLE_WATCHER; i < DICT_MAX_WATCHERS; i++) {
if (!interp->dict_state.watchers[i]) {
interp->dict_state.watchers[i] = callback;
return i;
diff --git a/Objects/exceptions.c b/Objects/exceptions.c
index ca6f323ac11..499fb2b34b3 100644
--- a/Objects/exceptions.c
+++ b/Objects/exceptions.c
@@ -2014,6 +2014,12 @@ static PyTypeObject _PyExc_ImportError = {
};
PyObject *PyExc_ImportError = (PyObject *)&_PyExc_ImportError;
+/*
+ * ImportCycleError extends ImportError
+ */
+
+MiddlingExtendsException(PyExc_ImportError, ImportCycleError, ImportError,
+ "Import produces a cycle.");
/*
* ModuleNotFoundError extends ImportError
*/
@@ -4454,6 +4460,7 @@ static struct static_exception static_exceptions[] = {
{&_PyExc_IncompleteInputError, "_IncompleteInputError"}, // base: SyntaxError(Exception)
ITEM(IndexError), // base: LookupError(Exception)
ITEM(KeyError), // base: LookupError(Exception)
+ ITEM(ImportCycleError), // base: ImportError(Exception)
ITEM(ModuleNotFoundError), // base: ImportError(Exception)
ITEM(NotImplementedError), // base: RuntimeError(Exception)
ITEM(PythonFinalizationError), // base: RuntimeError(Exception)
@@ -4643,4 +4650,3 @@ _PyException_AddNote(PyObject *exc, PyObject *note)
Py_XDECREF(r);
return res;
}
-
diff --git a/Objects/lazyimportobject.c b/Objects/lazyimportobject.c
new file mode 100644
index 00000000000..451f335e033
--- /dev/null
+++ b/Objects/lazyimportobject.c
@@ -0,0 +1,157 @@
+// Lazy object implementation.
+
+#include "Python.h"
+#include "pycore_ceval.h"
+#include "pycore_frame.h"
+#include "pycore_import.h"
+#include "pycore_interpframe.h"
+#include "pycore_lazyimportobject.h"
+#include "pycore_modsupport.h"
+
+#define PyLazyImportObject_CAST(op) ((PyLazyImportObject *)(op))
+
+PyObject *
+_PyLazyImport_New(_PyInterpreterFrame *frame, PyObject *builtins, PyObject *name, PyObject *fromlist)
+{
+ PyLazyImportObject *m;
+ if (!name || !PyUnicode_Check(name)) {
+ PyErr_SetString(PyExc_TypeError, "expected str for name");
+ return NULL;
+ }
+ if (fromlist == Py_None || fromlist == NULL) {
+ fromlist = NULL;
+ }
+ else if (!PyUnicode_Check(fromlist) && !PyTuple_Check(fromlist)) {
+ PyErr_SetString(PyExc_TypeError,
+ "lazy_import: fromlist must be None, a string, or a tuple");
+ return NULL;
+ }
+ m = PyObject_GC_New(PyLazyImportObject, &PyLazyImport_Type);
+ if (m == NULL) {
+ return NULL;
+ }
+ m->lz_builtins = Py_XNewRef(builtins);
+ m->lz_from = Py_NewRef(name);
+ m->lz_attr = Py_XNewRef(fromlist);
+
+ // Capture frame information for the original import location.
+ m->lz_code = NULL;
+ m->lz_instr_offset = -1;
+
+ if (frame != NULL) {
+ PyCodeObject *code = _PyFrame_GetCode(frame);
+ if (code != NULL) {
+ m->lz_code = (PyCodeObject *)Py_NewRef(code);
+ // Calculate the instruction offset from the current frame.
+ m->lz_instr_offset = _PyInterpreterFrame_LASTI(frame);
+ }
+ }
+
+ _PyObject_GC_TRACK(m);
+ return (PyObject *)m;
+}
+
+static int
+lazy_import_traverse(PyObject *op, visitproc visit, void *arg)
+{
+ PyLazyImportObject *m = PyLazyImportObject_CAST(op);
+ Py_VISIT(m->lz_builtins);
+ Py_VISIT(m->lz_from);
+ Py_VISIT(m->lz_attr);
+ Py_VISIT(m->lz_code);
+ return 0;
+}
+
+static int
+lazy_import_clear(PyObject *op)
+{
+ PyLazyImportObject *m = PyLazyImportObject_CAST(op);
+ Py_CLEAR(m->lz_builtins);
+ Py_CLEAR(m->lz_from);
+ Py_CLEAR(m->lz_attr);
+ Py_CLEAR(m->lz_code);
+ return 0;
+}
+
+static void
+lazy_import_dealloc(PyObject *op)
+{
+ _PyObject_GC_UNTRACK(op);
+ (void)lazy_import_clear(op);
+ Py_TYPE(op)->tp_free(op);
+}
+
+static PyObject *
+lazy_import_name(PyLazyImportObject *m)
+{
+ if (m->lz_attr != NULL) {
+ if (PyUnicode_Check(m->lz_attr)) {
+ return PyUnicode_FromFormat("%U.%U", m->lz_from, m->lz_attr);
+ }
+ else {
+ return PyUnicode_FromFormat("%U...", m->lz_from);
+ }
+ }
+ return Py_NewRef(m->lz_from);
+}
+
+static PyObject *
+lazy_import_repr(PyObject *op)
+{
+ PyLazyImportObject *m = PyLazyImportObject_CAST(op);
+ PyObject *name = lazy_import_name(m);
+ if (name == NULL) {
+ return NULL;
+ }
+ PyObject *res = PyUnicode_FromFormat("<%T '%U'>", op, name);
+ Py_DECREF(name);
+ return res;
+}
+
+PyObject *
+_PyLazyImport_GetName(PyObject *op)
+{
+ PyLazyImportObject *lazy_import = PyLazyImportObject_CAST(op);
+ assert(PyLazyImport_CheckExact(lazy_import));
+ return lazy_import_name(lazy_import);
+}
+
+static PyObject *
+lazy_import_resolve(PyObject *self, PyObject *args)
+{
+ return _PyImport_LoadLazyImportTstate(PyThreadState_GET(), self);
+}
+
+static PyMethodDef lazy_import_methods[] = {
+ {
+ "resolve", lazy_import_resolve, METH_NOARGS,
+ PyDoc_STR("resolves the lazy import and returns the actual object")
+ },
+ {NULL, NULL}
+};
+
+
+PyDoc_STRVAR(lazy_import_doc,
+"lazy_import(builtins, name, fromlist=None, /)\n"
+"--\n"
+"\n"
+"Represents a deferred import that will be resolved on first use.\n"
+"\n"
+"Instances of this object accessed from the global scope will be\n"
+"automatically imported based upon their name and then replaced with\n"
+"the imported value.");
+
+PyTypeObject PyLazyImport_Type = {
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ .tp_name = "lazy_import",
+ .tp_basicsize = sizeof(PyLazyImportObject),
+ .tp_dealloc = lazy_import_dealloc,
+ .tp_repr = lazy_import_repr,
+ .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
+ .tp_doc = lazy_import_doc,
+ .tp_traverse = lazy_import_traverse,
+ .tp_clear = lazy_import_clear,
+ .tp_methods = lazy_import_methods,
+ .tp_alloc = PyType_GenericAlloc,
+ .tp_free = PyObject_GC_Del,
+};
diff --git a/Objects/moduleobject.c b/Objects/moduleobject.c
index b7270077028..e3868097c0b 100644
--- a/Objects/moduleobject.c
+++ b/Objects/moduleobject.c
@@ -7,6 +7,7 @@
#include "pycore_fileutils.h" // _Py_wgetcwd
#include "pycore_import.h" // _PyImport_GetNextModuleIndex()
#include "pycore_interp.h" // PyInterpreterState.importlib
+#include "pycore_lazyimportobject.h" // _PyLazyImportObject_Check()
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_modsupport.h" // _PyModule_CreateInitialized()
#include "pycore_moduleobject.h" // _PyModule_GetDefOrNull()
@@ -18,7 +19,6 @@
#include "osdefs.h" // MAXPATHLEN
-
#define _PyModule_CAST(op) \
(assert(PyModule_Check(op)), _Py_CAST(PyModuleObject*, (op)))
@@ -195,11 +195,40 @@ new_module_notrack(PyTypeObject *mt)
return m;
}
+/* Module dict watcher callback.
+ * When a module dictionary is modified, we need to clear the keys version
+ * to invalidate any cached lookups that depend on the dictionary structure.
+ */
+static int
+module_dict_watcher(PyDict_WatchEvent event, PyObject *dict,
+ PyObject *key, PyObject *new_value)
+{
+ assert(PyDict_Check(dict));
+ // Only if a new lazy object shows up do we need to clear the dictionary. If
+ // this is adding a new key then the version will be reset anyway.
+ if (event == PyDict_EVENT_MODIFIED &&
+ new_value != NULL &&
+ PyLazyImport_CheckExact(new_value)) {
+ _PyDict_ClearKeysVersionLockHeld(dict);
+ }
+ return 0;
+}
+
+int
+_PyModule_InitModuleDictWatcher(PyInterpreterState *interp)
+{
+ // This is a reserved watcher for CPython so there's no need to check for non-NULL.
+ assert(interp->dict_state.watchers[MODULE_WATCHER_ID] == NULL);
+ interp->dict_state.watchers[MODULE_WATCHER_ID] = &module_dict_watcher;
+ return 0;
+}
+
static void
track_module(PyModuleObject *m)
{
_PyDict_EnablePerThreadRefcounting(m->md_dict);
_PyObject_SetDeferredRefcount((PyObject *)m);
+ PyDict_Watch(MODULE_WATCHER_ID, m->md_dict);
PyObject_GC_Track(m);
}
@@ -1308,6 +1337,28 @@ _Py_module_getattro_impl(PyModuleObject *m, PyObject *name, int suppress)
PyObject *attr, *mod_name, *getattr;
attr = _PyObject_GenericGetAttrWithDict((PyObject *)m, name, NULL, suppress);
if (attr) {
+ if (PyLazyImport_CheckExact(attr)) {
+ PyObject *new_value = _PyImport_LoadLazyImportTstate(
+ PyThreadState_GET(), attr);
+ if (new_value == NULL) {
+ if (suppress &&
+ PyErr_ExceptionMatches(PyExc_ImportCycleError)) {
+ // ImportCycleError is raised when a lazy object tries
+ // to import itself. In this case, the error should not
+ // propagate to the caller and instead treated as if the
+ // attribute doesn't exist.
+ PyErr_Clear();
+ }
+ Py_DECREF(attr);
+ return NULL;
+ }
+
+ if (PyDict_SetItem(m->md_dict, name, new_value) < 0) {
+ Py_CLEAR(new_value);
+ }
+ Py_DECREF(attr);
+ return new_value;
+ }
return attr;
}
if (suppress == 1) {
@@ -1506,7 +1557,12 @@ static PyObject *
module_dir(PyObject *self, PyObject *args)
{
PyObject *result = NULL;
- PyObject *dict = PyObject_GetAttr(self, &_Py_ID(__dict__));
+ PyObject *dict;
+ if (PyModule_CheckExact(self)) {
+ dict = Py_NewRef(((PyModuleObject *)self)->md_dict);
+ } else {
+ dict = PyObject_GetAttr(self, &_Py_ID(__dict__));
+ }
if (dict != NULL) {
if (PyDict_Check(dict)) {
@@ -1534,7 +1590,7 @@ static PyMethodDef module_methods[] = {
};
static PyObject *
-module_get_dict(PyModuleObject *m)
+module_load_dict(PyModuleObject *m)
{
PyObject *dict = PyObject_GetAttr((PyObject *)m, &_Py_ID(__dict__));
if (dict == NULL) {
@@ -1553,7 +1609,7 @@ module_get_annotate(PyObject *self, void *Py_UNUSED(ignored))
{
PyModuleObject *m = _PyModule_CAST(self);
- PyObject *dict = module_get_dict(m);
+ PyObject *dict = module_load_dict(m);
if (dict == NULL) {
return NULL;
}
@@ -1578,7 +1634,7 @@ module_set_annotate(PyObject *self, PyObject *value, void *Py_UNUSED(ignored))
return -1;
}
- PyObject *dict = module_get_dict(m);
+ PyObject *dict = module_load_dict(m);
if (dict == NULL) {
return -1;
}
@@ -1608,7 +1664,7 @@ module_get_annotations(PyObject *self, void *Py_UNUSED(ignored))
{
PyModuleObject *m = _PyModule_CAST(self);
- PyObject *dict = module_get_dict(m);
+ PyObject *dict = module_load_dict(m);
if (dict == NULL) {
return NULL;
}
@@ -1680,7 +1736,7 @@ module_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)
{
PyModuleObject *m = _PyModule_CAST(self);
- PyObject *dict = module_get_dict(m);
+ PyObject *dict = module_load_dict(m);
if (dict == NULL) {
return -1;
}
@@ -1709,7 +1765,6 @@ module_set_annotations(PyObject *self, PyObject *value, void *Py_UNUSED(ignored)
return ret;
}
-
static PyGetSetDef module_getsets[] = {
{"__annotations__", module_get_annotations, module_set_annotations},
{"__annotate__", module_get_annotate, module_set_annotate},
diff --git a/Parser/Python.asdl b/Parser/Python.asdl
index dbe226f8372..2f0b123858f 100644
--- a/Parser/Python.asdl
+++ b/Parser/Python.asdl
@@ -45,8 +45,8 @@ module Python
| TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)
| Assert(expr test, expr? msg)
- | Import(alias* names)
- | ImportFrom(identifier? module, alias* names, int? level)
+ | Import(alias* names, int? is_lazy)
+ | ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)
| Global(identifier* names)
| Nonlocal(identifier* names)
diff --git a/Parser/action_helpers.c b/Parser/action_helpers.c
index 50856686335..1f5b6220ba1 100644
--- a/Parser/action_helpers.c
+++ b/Parser/action_helpers.c
@@ -1971,10 +1971,16 @@ _PyPegen_concatenate_strings(Parser *p, asdl_expr_seq *strings,
}
stmt_ty
-_PyPegen_checked_future_import(Parser *p, identifier module, asdl_alias_seq * names, int level,
- int lineno, int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena) {
+_PyPegen_checked_future_import(Parser *p, identifier module, asdl_alias_seq * names,
+ int level, expr_ty lazy_token, int lineno,
+ int col_offset, int end_lineno, int end_col_offset,
+ PyArena *arena) {
if (level == 0 && PyUnicode_CompareWithASCIIString(module, "__future__") == 0) {
+ if (lazy_token) {
+ RAISE_SYNTAX_ERROR_KNOWN_LOCATION(lazy_token,
+ "lazy from __future__ import is not allowed");
+ return NULL;
+ }
for (Py_ssize_t i = 0; i < asdl_seq_LEN(names); i++) {
alias_ty alias = asdl_seq_GET(names, i);
if (PyUnicode_CompareWithASCIIString(alias->name, "barry_as_FLUFL") == 0) {
@@ -1982,7 +1988,8 @@ _PyPegen_checked_future_import(Parser *p, identifier module, asdl_alias_seq * na
}
}
}
- return _PyAST_ImportFrom(module, names, level, lineno, col_offset, end_lineno, end_col_offset, arena);
+ return _PyAST_ImportFrom(module, names, level, lazy_token ? 1 : 0, lineno,
+ col_offset, end_lineno, end_col_offset, arena);
}
asdl_stmt_seq*
diff --git a/Parser/parser.c b/Parser/parser.c
index b9848a865b6..37c19c4c902 100644
--- a/Parser/parser.c
+++ b/Parser/parser.c
@@ -60,8 +60,8 @@ static KeywordToken *reserved_keywords[] = {
{NULL, -1},
},
(KeywordToken[]) {
- {"return", 522},
{"import", 647},
+ {"return", 522},
{"assert", 638},
{"global", 530},
{"except", 690},
@@ -81,6 +81,7 @@ static KeywordToken *reserved_keywords[] = {
static char *soft_keywords[] = {
"_",
"case",
+ "lazy",
"match",
"type",
NULL,
@@ -1565,9 +1566,9 @@ simple_stmts_rule(Parser *p)
// simple_stmt:
// | assignment
// | &"type" type_alias
+// | &('import' | 'from' | "lazy") import_stmt
// | star_expressions
// | &'return' return_stmt
-// | &('import' | 'from') import_stmt
// | &'raise' raise_stmt
// | &'pass' pass_stmt
// | &'del' del_stmt
@@ -1642,6 +1643,27 @@ simple_stmt_rule(Parser *p)
D(fprintf(stderr, "%*c%s simple_stmt[%d-%d]: %s failed!\n", p->level, ' ',
p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "&\"type\" type_alias"));
}
+ { // &('import' | 'from' | "lazy") import_stmt
+ if (p->error_indicator) {
+ p->level--;
+ return NULL;
+ }
+ D(fprintf(stderr, "%*c> simple_stmt[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&('import' | 'from' | \"lazy\") import_stmt"));
+ stmt_ty import_stmt_var;
+ if (
+ _PyPegen_lookahead(1, _tmp_5_rule, p)
+ &&
+ (import_stmt_var = import_stmt_rule(p)) // import_stmt
+ )
+ {
+ D(fprintf(stderr, "%*c+ simple_stmt[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "&('import' | 'from' | \"lazy\") import_stmt"));
+ _res = import_stmt_var;
+ goto done;
+ }
+ p->mark = _mark;
+ D(fprintf(stderr, "%*c%s simple_stmt[%d-%d]: %s failed!\n", p->level, ' ',
+ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "&('import' | 'from' | \"lazy\") import_stmt"));
+ }
{ // star_expressions
if (p->error_indicator) {
p->level--;
@@ -1696,27 +1718,6 @@ simple_stmt_rule(Parser *p)
D(fprintf(stderr, "%*c%s simple_stmt[%d-%d]: %s failed!\n", p->level, ' ',
p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "&'return' return_stmt"));
}
- { // &('import' | 'from') import_stmt
- if (p->error_indicator) {
- p->level--;
- return NULL;
- }
- D(fprintf(stderr, "%*c> simple_stmt[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "&('import' | 'from') import_stmt"));
- stmt_ty import_stmt_var;
- if (
- _PyPegen_lookahead(1, _tmp_5_rule, p)
- &&
- (import_stmt_var = import_stmt_rule(p)) // import_stmt
- )
- {
- D(fprintf(stderr, "%*c+ simple_stmt[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "&('import' | 'from') import_stmt"));
- _res = import_stmt_var;
- goto done;
- }
- p->mark = _mark;
- D(fprintf(stderr, "%*c%s simple_stmt[%d-%d]: %s failed!\n", p->level, ' ',
- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "&('import' | 'from') import_stmt"));
- }
{ // &'raise' raise_stmt
if (p->error_indicator) {
p->level--;
@@ -3511,6 +3512,10 @@ import_stmt_rule(Parser *p)
return NULL;
}
stmt_ty _res = NULL;
+ if (_PyPegen_is_memoized(p, import_stmt_type, &_res)) {
+ p->level--;
+ return _res;
+ }
int _mark = p->mark;
if (p->call_invalid_rules) { // invalid_import
if (p->error_indicator) {
@@ -3571,11 +3576,12 @@ import_stmt_rule(Parser *p)
}
_res = NULL;
done:
+ _PyPegen_insert_memo(p, _mark, import_stmt_type, _res);
p->level--;
return _res;
}
-// import_name: 'import' dotted_as_names
+// import_name: "lazy"? 'import' dotted_as_names
static stmt_ty
import_name_rule(Parser *p)
{
@@ -3597,21 +3603,24 @@ import_name_rule(Parser *p)
UNUSED(_start_lineno); // Only used by EXTRA macro
int _start_col_offset = p->tokens[_mark]->col_offset;
UNUSED(_start_col_offset); // Only used by EXTRA macro
- { // 'import' dotted_as_names
+ { // "lazy"? 'import' dotted_as_names
if (p->error_indicator) {
p->level--;
return NULL;
}
- D(fprintf(stderr, "%*c> import_name[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'import' dotted_as_names"));
+ D(fprintf(stderr, "%*c> import_name[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "\"lazy\"? 'import' dotted_as_names"));
Token * _keyword;
asdl_alias_seq* a;
+ void *lazy;
if (
+ (lazy = _PyPegen_expect_soft_keyword(p, "lazy"), !p->error_indicator) // "lazy"?
+ &&
(_keyword = _PyPegen_expect_token(p, 647)) // token='import'
&&
(a = dotted_as_names_rule(p)) // dotted_as_names
)
{
- D(fprintf(stderr, "%*c+ import_name[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'import' dotted_as_names"));
+ D(fprintf(stderr, "%*c+ import_name[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "\"lazy\"? 'import' dotted_as_names"));
Token *_token = _PyPegen_get_last_nonnwhitespace_token(p);
if (_token == NULL) {
p->level--;
@@ -3621,7 +3630,7 @@ import_name_rule(Parser *p)
UNUSED(_end_lineno); // Only used by EXTRA macro
int _end_col_offset = _token->end_col_offset;
UNUSED(_end_col_offset); // Only used by EXTRA macro
- _res = _PyAST_Import ( a , EXTRA );
+ _res = _PyAST_Import ( a , lazy ? 1 : 0 , EXTRA );
if (_res == NULL && PyErr_Occurred()) {
p->error_indicator = 1;
p->level--;
@@ -3631,7 +3640,7 @@ import_name_rule(Parser *p)
}
p->mark = _mark;
D(fprintf(stderr, "%*c%s import_name[%d-%d]: %s failed!\n", p->level, ' ',
- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'import' dotted_as_names"));
+ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "\"lazy\"? 'import' dotted_as_names"));
}
_res = NULL;
done:
@@ -3640,8 +3649,8 @@ import_name_rule(Parser *p)
}
// import_from:
-// | 'from' (('.' | '...'))* dotted_name 'import' import_from_targets
-// | 'from' (('.' | '...'))+ 'import' import_from_targets
+// | "lazy"? 'from' (('.' | '...'))* dotted_name 'import' import_from_targets
+// | "lazy"? 'from' (('.' | '...'))+ 'import' import_from_targets
static stmt_ty
import_from_rule(Parser *p)
{
@@ -3663,18 +3672,21 @@ import_from_rule(Parser *p)
UNUSED(_start_lineno); // Only used by EXTRA macro
int _start_col_offset = p->tokens[_mark]->col_offset;
UNUSED(_start_col_offset); // Only used by EXTRA macro
- { // 'from' (('.' | '...'))* dotted_name 'import' import_from_targets
+ { // "lazy"? 'from' (('.' | '...'))* dotted_name 'import' import_from_targets
if (p->error_indicator) {
p->level--;
return NULL;
}
- D(fprintf(stderr, "%*c> import_from[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'from' (('.' | '...'))* dotted_name 'import' import_from_targets"));
+ D(fprintf(stderr, "%*c> import_from[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "\"lazy\"? 'from' (('.' | '...'))* dotted_name 'import' import_from_targets"));
Token * _keyword;
Token * _keyword_1;
asdl_seq * a;
expr_ty b;
asdl_alias_seq* c;
+ void *lazy;
if (
+ (lazy = _PyPegen_expect_soft_keyword(p, "lazy"), !p->error_indicator) // "lazy"?
+ &&
(_keyword = _PyPegen_expect_token(p, 646)) // token='from'
&&
(a = _loop0_17_rule(p)) // (('.' | '...'))*
@@ -3686,7 +3698,7 @@ import_from_rule(Parser *p)
(c = import_from_targets_rule(p)) // import_from_targets
)
{
- D(fprintf(stderr, "%*c+ import_from[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'from' (('.' | '...'))* dotted_name 'import' import_from_targets"));
+ D(fprintf(stderr, "%*c+ import_from[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "\"lazy\"? 'from' (('.' | '...'))* dotted_name 'import' import_from_targets"));
Token *_token = _PyPegen_get_last_nonnwhitespace_token(p);
if (_token == NULL) {
p->level--;
@@ -3696,7 +3708,7 @@ import_from_rule(Parser *p)
UNUSED(_end_lineno); // Only used by EXTRA macro
int _end_col_offset = _token->end_col_offset;
UNUSED(_end_col_offset); // Only used by EXTRA macro
- _res = _PyPegen_checked_future_import ( p , b -> v . Name . id , c , _PyPegen_seq_count_dots ( a ) , EXTRA );
+ _res = _PyPegen_checked_future_import ( p , b -> v . Name . id , c , _PyPegen_seq_count_dots ( a ) , lazy , EXTRA );
if (_res == NULL && PyErr_Occurred()) {
p->error_indicator = 1;
p->level--;
@@ -3706,19 +3718,22 @@ import_from_rule(Parser *p)
}
p->mark = _mark;
D(fprintf(stderr, "%*c%s import_from[%d-%d]: %s failed!\n", p->level, ' ',
- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'from' (('.' | '...'))* dotted_name 'import' import_from_targets"));
+ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "\"lazy\"? 'from' (('.' | '...'))* dotted_name 'import' import_from_targets"));
}
- { // 'from' (('.' | '...'))+ 'import' import_from_targets
+ { // "lazy"? 'from' (('.' | '...'))+ 'import' import_from_targets
if (p->error_indicator) {
p->level--;
return NULL;
}
- D(fprintf(stderr, "%*c> import_from[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "'from' (('.' | '...'))+ 'import' import_from_targets"));
+ D(fprintf(stderr, "%*c> import_from[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "\"lazy\"? 'from' (('.' | '...'))+ 'import' import_from_targets"));
Token * _keyword;
Token * _keyword_1;
asdl_seq * a;
asdl_alias_seq* b;
+ void *lazy;
if (
+ (lazy = _PyPegen_expect_soft_keyword(p, "lazy"), !p->error_indicator) // "lazy"?
+ &&
(_keyword = _PyPegen_expect_token(p, 646)) // token='from'
&&
(a = _loop1_18_rule(p)) // (('.' | '...'))+
@@ -3728,7 +3743,7 @@ import_from_rule(Parser *p)
(b = import_from_targets_rule(p)) // import_from_targets
)
{
- D(fprintf(stderr, "%*c+ import_from[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "'from' (('.' | '...'))+ 'import' import_from_targets"));
+ D(fprintf(stderr, "%*c+ import_from[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "\"lazy\"? 'from' (('.' | '...'))+ 'import' import_from_targets"));
Token *_token = _PyPegen_get_last_nonnwhitespace_token(p);
if (_token == NULL) {
p->level--;
@@ -3738,7 +3753,7 @@ import_from_rule(Parser *p)
UNUSED(_end_lineno); // Only used by EXTRA macro
int _end_col_offset = _token->end_col_offset;
UNUSED(_end_col_offset); // Only used by EXTRA macro
- _res = _PyAST_ImportFrom ( NULL , b , _PyPegen_seq_count_dots ( a ) , EXTRA );
+ _res = _PyAST_ImportFrom ( NULL , b , _PyPegen_seq_count_dots ( a ) , lazy ? 1 : 0 , EXTRA );
if (_res == NULL && PyErr_Occurred()) {
p->error_indicator = 1;
p->level--;
@@ -3748,7 +3763,7 @@ import_from_rule(Parser *p)
}
p->mark = _mark;
D(fprintf(stderr, "%*c%s import_from[%d-%d]: %s failed!\n", p->level, ' ',
- p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'from' (('.' | '...'))+ 'import' import_from_targets"));
+ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "\"lazy\"? 'from' (('.' | '...'))+ 'import' import_from_targets"));
}
_res = NULL;
done:
@@ -28556,7 +28571,7 @@ _gather_4_rule(Parser *p)
return _res;
}
-// _tmp_5: 'import' | 'from'
+// _tmp_5: 'import' | 'from' | "lazy"
static void *
_tmp_5_rule(Parser *p)
{
@@ -28607,6 +28622,25 @@ _tmp_5_rule(Parser *p)
D(fprintf(stderr, "%*c%s _tmp_5[%d-%d]: %s failed!\n", p->level, ' ',
p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "'from'"));
}
+ { // "lazy"
+ if (p->error_indicator) {
+ p->level--;
+ return NULL;
+ }
+ D(fprintf(stderr, "%*c> _tmp_5[%d-%d]: %s\n", p->level, ' ', _mark, p->mark, "\"lazy\""));
+ expr_ty _keyword;
+ if (
+ (_keyword = _PyPegen_expect_soft_keyword(p, "lazy")) // soft_keyword='"lazy"'
+ )
+ {
+ D(fprintf(stderr, "%*c+ _tmp_5[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "\"lazy\""));
+ _res = _keyword;
+ goto done;
+ }
+ p->mark = _mark;
+ D(fprintf(stderr, "%*c%s _tmp_5[%d-%d]: %s failed!\n", p->level, ' ',
+ p->error_indicator ? "ERROR!" : "-", _mark, p->mark, "\"lazy\""));
+ }
_res = NULL;
done:
p->level--;
diff --git a/Parser/pegen.h b/Parser/pegen.h
index be5333eb268..85c9ada765d 100644
--- a/Parser/pegen.h
+++ b/Parser/pegen.h
@@ -367,7 +367,7 @@ void *_PyPegen_arguments_parsing_error(Parser *, expr_ty);
expr_ty _PyPegen_get_last_comprehension_item(comprehension_ty comprehension);
void *_PyPegen_nonparen_genexp_in_call(Parser *p, expr_ty args, asdl_comprehension_seq *comprehensions);
stmt_ty _PyPegen_checked_future_import(Parser *p, identifier module, asdl_alias_seq *,
- int , int, int , int , int , PyArena *);
+ int, expr_ty, int, int, int, int, PyArena *);
asdl_stmt_seq* _PyPegen_register_stmts(Parser *p, asdl_stmt_seq* stmts);
stmt_ty _PyPegen_register_stmt(Parser *p, stmt_ty s);
diff --git a/Programs/test_frozenmain.h b/Programs/test_frozenmain.h
index dbeedb7ffe0..f808544045e 100644
--- a/Programs/test_frozenmain.h
+++ b/Programs/test_frozenmain.h
@@ -2,7 +2,7 @@
unsigned char M_test_frozenmain[] = {
227,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,
0,0,0,0,0,243,184,0,0,0,128,0,94,0,82,1,
- 73,0,116,0,94,0,82,1,73,1,116,1,93,2,33,0,
+ 73,0,116,0,94,0,82,1,73,4,116,1,93,2,33,0,
82,2,52,1,0,0,0,0,0,0,31,0,93,2,33,0,
82,3,93,0,80,6,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,52,2,0,0,0,0,0,0,
diff --git a/Python/Python-ast.c b/Python/Python-ast.c
index 577adb825b0..5d319992dcd 100644
--- a/Python/Python-ast.c
+++ b/Python/Python-ast.c
@@ -222,6 +222,7 @@ void _PyAST_Fini(PyInterpreterState *interp)
Py_CLEAR(state->id);
Py_CLEAR(state->ifs);
Py_CLEAR(state->is_async);
+ Py_CLEAR(state->is_lazy);
Py_CLEAR(state->items);
Py_CLEAR(state->iter);
Py_CLEAR(state->key);
@@ -327,6 +328,7 @@ static int init_identifiers(struct ast_state *state)
if ((state->id = PyUnicode_InternFromString("id")) == NULL) return -1;
if ((state->ifs = PyUnicode_InternFromString("ifs")) == NULL) return -1;
if ((state->is_async = PyUnicode_InternFromString("is_async")) == NULL) return -1;
+ if ((state->is_lazy = PyUnicode_InternFromString("is_lazy")) == NULL) return -1;
if ((state->items = PyUnicode_InternFromString("items")) == NULL) return -1;
if ((state->iter = PyUnicode_InternFromString("iter")) == NULL) return -1;
if ((state->key = PyUnicode_InternFromString("key")) == NULL) return -1;
@@ -527,11 +529,13 @@ static const char * const Assert_fields[]={
};
static const char * const Import_fields[]={
"names",
+ "is_lazy",
};
static const char * const ImportFrom_fields[]={
"module",
"names",
"level",
+ "is_lazy",
};
static const char * const Global_fields[]={
"names",
@@ -2254,6 +2258,21 @@ add_ast_annotations(struct ast_state *state)
return 0;
}
}
+ {
+ PyObject *type = (PyObject *)&PyLong_Type;
+ type = _Py_union_type_or(type, Py_None);
+ cond = type != NULL;
+ if (!cond) {
+ Py_DECREF(Import_annotations);
+ return 0;
+ }
+ cond = PyDict_SetItemString(Import_annotations, "is_lazy", type) == 0;
+ Py_DECREF(type);
+ if (!cond) {
+ Py_DECREF(Import_annotations);
+ return 0;
+ }
+ }
cond = PyObject_SetAttrString(state->Import_type, "_field_types",
Import_annotations) == 0;
if (!cond) {
@@ -2315,6 +2334,22 @@ add_ast_annotations(struct ast_state *state)
return 0;
}
}
+ {
+ PyObject *type = (PyObject *)&PyLong_Type;
+ type = _Py_union_type_or(type, Py_None);
+ cond = type != NULL;
+ if (!cond) {
+ Py_DECREF(ImportFrom_annotations);
+ return 0;
+ }
+ cond = PyDict_SetItemString(ImportFrom_annotations, "is_lazy", type) ==
+ 0;
+ Py_DECREF(type);
+ if (!cond) {
+ Py_DECREF(ImportFrom_annotations);
+ return 0;
+ }
+ }
cond = PyObject_SetAttrString(state->ImportFrom_type, "_field_types",
ImportFrom_annotations) == 0;
if (!cond) {
@@ -6223,8 +6258,8 @@ init_types(void *arg)
" | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\n"
" | TryStar(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\n"
" | Assert(expr test, expr? msg)\n"
- " | Import(alias* names)\n"
- " | ImportFrom(identifier? module, alias* names, int? level)\n"
+ " | Import(alias* names, int? is_lazy)\n"
+ " | ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)\n"
" | Global(identifier* names)\n"
" | Nonlocal(identifier* names)\n"
" | Expr(expr value)\n"
@@ -6353,17 +6388,21 @@ init_types(void *arg)
if (PyObject_SetAttr(state->Assert_type, state->msg, Py_None) == -1)
return -1;
state->Import_type = make_type(state, "Import", state->stmt_type,
- Import_fields, 1,
- "Import(alias* names)");
+ Import_fields, 2,
+ "Import(alias* names, int? is_lazy)");
if (!state->Import_type) return -1;
+ if (PyObject_SetAttr(state->Import_type, state->is_lazy, Py_None) == -1)
+ return -1;
state->ImportFrom_type = make_type(state, "ImportFrom", state->stmt_type,
- ImportFrom_fields, 3,
- "ImportFrom(identifier? module, alias* names, int? level)");
+ ImportFrom_fields, 4,
+ "ImportFrom(identifier? module, alias* names, int? level, int? is_lazy)");
if (!state->ImportFrom_type) return -1;
if (PyObject_SetAttr(state->ImportFrom_type, state->module, Py_None) == -1)
return -1;
if (PyObject_SetAttr(state->ImportFrom_type, state->level, Py_None) == -1)
return -1;
+ if (PyObject_SetAttr(state->ImportFrom_type, state->is_lazy, Py_None) == -1)
+ return -1;
state->Global_type = make_type(state, "Global", state->stmt_type,
Global_fields, 1,
"Global(identifier* names)");
@@ -7605,8 +7644,8 @@ _PyAST_Assert(expr_ty test, expr_ty msg, int lineno, int col_offset, int
}
stmt_ty
-_PyAST_Import(asdl_alias_seq * names, int lineno, int col_offset, int
- end_lineno, int end_col_offset, PyArena *arena)
+_PyAST_Import(asdl_alias_seq * names, int is_lazy, int lineno, int col_offset,
+ int end_lineno, int end_col_offset, PyArena *arena)
{
stmt_ty p;
p = (stmt_ty)_PyArena_Malloc(arena, sizeof(*p));
@@ -7614,6 +7653,7 @@ _PyAST_Import(asdl_alias_seq * names, int lineno, int col_offset, int
return NULL;
p->kind = Import_kind;
p->v.Import.names = names;
+ p->v.Import.is_lazy = is_lazy;
p->lineno = lineno;
p->col_offset = col_offset;
p->end_lineno = end_lineno;
@@ -7623,8 +7663,8 @@ _PyAST_Import(asdl_alias_seq * names, int lineno, int col_offset, int
stmt_ty
_PyAST_ImportFrom(identifier module, asdl_alias_seq * names, int level, int
- lineno, int col_offset, int end_lineno, int end_col_offset,
- PyArena *arena)
+ is_lazy, int lineno, int col_offset, int end_lineno, int
+ end_col_offset, PyArena *arena)
{
stmt_ty p;
p = (stmt_ty)_PyArena_Malloc(arena, sizeof(*p));
@@ -7634,6 +7674,7 @@ _PyAST_ImportFrom(identifier module, asdl_alias_seq * names, int level, int
p->v.ImportFrom.module = module;
p->v.ImportFrom.names = names;
p->v.ImportFrom.level = level;
+ p->v.ImportFrom.is_lazy = is_lazy;
p->lineno = lineno;
p->col_offset = col_offset;
p->end_lineno = end_lineno;
@@ -9467,6 +9508,11 @@ ast2obj_stmt(struct ast_state *state, void* _o)
if (PyObject_SetAttr(result, state->names, value) == -1)
goto failed;
Py_DECREF(value);
+ value = ast2obj_int(state, o->v.Import.is_lazy);
+ if (!value) goto failed;
+ if (PyObject_SetAttr(result, state->is_lazy, value) == -1)
+ goto failed;
+ Py_DECREF(value);
break;
case ImportFrom_kind:
tp = (PyTypeObject *)state->ImportFrom_type;
@@ -9488,6 +9534,11 @@ ast2obj_stmt(struct ast_state *state, void* _o)
if (PyObject_SetAttr(result, state->level, value) == -1)
goto failed;
Py_DECREF(value);
+ value = ast2obj_int(state, o->v.ImportFrom.is_lazy);
+ if (!value) goto failed;
+ if (PyObject_SetAttr(result, state->is_lazy, value) == -1)
+ goto failed;
+ Py_DECREF(value);
break;
case Global_kind:
tp = (PyTypeObject *)state->Global_type;
@@ -13483,6 +13534,7 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena*
}
if (isinstance) {
asdl_alias_seq* names;
+ int is_lazy;
if (PyObject_GetOptionalAttr(obj, state->names, &tmp) < 0) {
return -1;
@@ -13522,7 +13574,24 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena*
}
Py_CLEAR(tmp);
}
- *out = _PyAST_Import(names, lineno, col_offset, end_lineno,
+ if (PyObject_GetOptionalAttr(obj, state->is_lazy, &tmp) < 0) {
+ return -1;
+ }
+ if (tmp == NULL || tmp == Py_None) {
+ Py_CLEAR(tmp);
+ is_lazy = 0;
+ }
+ else {
+ int res;
+ if (_Py_EnterRecursiveCall(" while traversing 'Import' node")) {
+ goto failed;
+ }
+ res = obj2ast_int(state, tmp, &is_lazy, arena);
+ _Py_LeaveRecursiveCall();
+ if (res != 0) goto failed;
+ Py_CLEAR(tmp);
+ }
+ *out = _PyAST_Import(names, is_lazy, lineno, col_offset, end_lineno,
end_col_offset, arena);
if (*out == NULL) goto failed;
return 0;
@@ -13536,6 +13605,7 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena*
identifier module;
asdl_alias_seq* names;
int level;
+ int is_lazy;
if (PyObject_GetOptionalAttr(obj, state->module, &tmp) < 0) {
return -1;
@@ -13609,8 +13679,25 @@ obj2ast_stmt(struct ast_state *state, PyObject* obj, stmt_ty* out, PyArena*
if (res != 0) goto failed;
Py_CLEAR(tmp);
}
- *out = _PyAST_ImportFrom(module, names, level, lineno, col_offset,
- end_lineno, end_col_offset, arena);
+ if (PyObject_GetOptionalAttr(obj, state->is_lazy, &tmp) < 0) {
+ return -1;
+ }
+ if (tmp == NULL || tmp == Py_None) {
+ Py_CLEAR(tmp);
+ is_lazy = 0;
+ }
+ else {
+ int res;
+ if (_Py_EnterRecursiveCall(" while traversing 'ImportFrom' node")) {
+ goto failed;
+ }
+ res = obj2ast_int(state, tmp, &is_lazy, arena);
+ _Py_LeaveRecursiveCall();
+ if (res != 0) goto failed;
+ Py_CLEAR(tmp);
+ }
+ *out = _PyAST_ImportFrom(module, names, level, is_lazy, lineno,
+ col_offset, end_lineno, end_col_offset, arena);
if (*out == NULL) goto failed;
return 0;
}
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c
index c2d780ac9b9..9144793ae73 100644
--- a/Python/bltinmodule.c
+++ b/Python/bltinmodule.c
@@ -9,6 +9,7 @@
#include "pycore_fileutils.h" // _PyFile_Flush
#include "pycore_floatobject.h" // _PyFloat_ExactDealloc()
#include "pycore_interp.h" // _PyInterpreterState_GetConfig()
+#include "pycore_import.h" // _PyImport_LazyImportModuleLevelObject ()
#include "pycore_long.h" // _PyLong_CompactValue
#include "pycore_modsupport.h" // _PyArg_NoKwnames()
#include "pycore_object.h" // _Py_AddToAllObjects()
@@ -287,6 +288,61 @@ builtin___import___impl(PyObject *module, PyObject *name, PyObject *globals,
}
+/*[clinic input]
+__lazy_import__ as builtin___lazy_import__
+
+ name: object
+ globals: object(c_default="NULL") = None
+ locals: object(c_default="NULL") = None
+ fromlist: object(c_default="NULL") = ()
+ level: int = 0
+
+Lazily imports a module.
+
+Returns either the module to be imported or a imp.lazy_module object which
+indicates the module to be lazily imported.
+[clinic start generated code]*/
+
+static PyObject *
+builtin___lazy_import___impl(PyObject *module, PyObject *name,
+ PyObject *globals, PyObject *locals,
+ PyObject *fromlist, int level)
+/*[clinic end generated code: output=300f1771094b9e8c input=9394874f340b2948]*/
+{
+ PyObject *builtins;
+ PyThreadState *tstate = PyThreadState_GET();
+ if (globals == NULL) {
+ globals = PyEval_GetGlobals();
+ }
+ if (locals == NULL) {
+ locals = globals;
+ }
+
+ if (PyDict_GetItemRef(globals, &_Py_ID(__builtins__), &builtins) < 0) {
+ return NULL;
+ }
+ if (builtins == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "unable to get builtins for lazy import");
+ return NULL;
+ }
+ if (PyModule_Check(builtins)) {
+ PyObject *builtins_dict = Py_XNewRef(PyModule_GetDict(builtins));
+ if (builtins_dict == NULL) {
+ Py_DECREF(builtins);
+ PyErr_SetString(PyExc_AttributeError,
+ "builtins module has no dict");
+ return NULL;
+ }
+ Py_SETREF(builtins, builtins_dict);
+ }
+
+ PyObject *res = _PyImport_LazyImportModuleLevelObject(
+ tstate, name, builtins, globals, locals, fromlist, level);
+ Py_DECREF(builtins);
+ return res;
+}
+
/*[clinic input]
abs as builtin_abs
@@ -3362,6 +3418,7 @@ static PyMethodDef builtin_methods[] = {
{"__build_class__", _PyCFunction_CAST(builtin___build_class__),
METH_FASTCALL | METH_KEYWORDS, build_class_doc},
BUILTIN___IMPORT___METHODDEF
+ BUILTIN___LAZY_IMPORT___METHODDEF
BUILTIN_ABS_METHODDEF
BUILTIN_ALL_METHODDEF
BUILTIN_ANY_METHODDEF
diff --git a/Python/bytecodes.c b/Python/bytecodes.c
index e1884ac38c0..b461f9b5bea 100644
--- a/Python/bytecodes.c
+++ b/Python/bytecodes.c
@@ -11,12 +11,15 @@
#include "pycore_audit.h" // _PySys_Audit()
#include "pycore_backoff.h"
#include "pycore_cell.h" // PyCell_GetRef()
+#include "pycore_ceval.h" // _PyEval_LazyImportName(), _PyEval_LazyImportFrom()
#include "pycore_code.h"
#include "pycore_emscripten_signal.h" // _Py_CHECK_EMSCRIPTEN_SIGNALS
#include "pycore_function.h"
+#include "pycore_import.h" // _PyImport_LoadLazyImportTstate()
#include "pycore_instruments.h"
#include "pycore_interpolation.h" // _PyInterpolation_Build()
#include "pycore_intrinsics.h"
+#include "pycore_lazyimportobject.h" // PyLazyImport_CheckExact()
#include "pycore_long.h" // _PyLong_ExactDealloc(), _PyLong_GetZero()
#include "pycore_moduleobject.h" // PyModuleObject
#include "pycore_object.h" // _PyObject_GC_TRACK()
@@ -1795,6 +1798,12 @@ dummy_func(
}
ERROR_NO_POP();
}
+
+ if (PyLazyImport_CheckExact(v_o)) {
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ Py_SETREF(v_o, l_v);
+ ERROR_IF(v_o == NULL);
+ }
}
else {
/* Slow-path if globals or builtins is not a dict */
@@ -1812,6 +1821,11 @@ dummy_func(
ERROR_IF(true);
}
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ Py_SETREF(v_o, l_v);
+ ERROR_IF(v_o == NULL);
+ }
}
}
v = PyStackRef_FromPyObjectSteal(v_o);
@@ -1821,6 +1835,22 @@ dummy_func(
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
PyObject *v_o = _PyEval_LoadName(tstate, frame, name);
ERROR_IF(v_o == NULL);
+ if (PyLazyImport_CheckExact(v_o)) {
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ // cannot early-decref v_o as it may cause a side-effect on l_v
+ if (l_v == NULL) {
+ Py_DECREF(v_o);
+ ERROR_IF(true);
+ }
+ int err = PyDict_SetItem(GLOBALS(), name, l_v);
+ if (err < 0) {
+ Py_DECREF(v_o);
+ Py_DECREF(l_v);
+ ERROR_IF(true);
+ }
+ Py_SETREF(v_o, l_v);
+ }
+
v = PyStackRef_FromPyObjectSteal(v_o);
}
@@ -1846,6 +1876,7 @@ dummy_func(
op(_LOAD_GLOBAL, ( -- res[1])) {
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg>>1);
_PyEval_LoadGlobalStackRef(GLOBALS(), BUILTINS(), name, res);
+
ERROR_IF(PyStackRef_IsNull(*res));
}
@@ -2962,11 +2993,23 @@ dummy_func(
b = res ? PyStackRef_True : PyStackRef_False;
}
- inst(IMPORT_NAME, (level, fromlist -- res)) {
- PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
- PyObject *res_o = _PyEval_ImportName(tstate, frame, name,
- PyStackRef_AsPyObjectBorrow(fromlist),
- PyStackRef_AsPyObjectBorrow(level));
+ inst(IMPORT_NAME, (level, fromlist -- res)) {
+ PyObject *name = GETITEM(FRAME_CO_NAMES, oparg >> 2);
+ PyObject *res_o;
+ if (!(oparg & 0x02)) {
+ res_o = _PyEval_LazyImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level),
+ oparg & 0x01);
+
+ }
+ else {
+ res_o = _PyEval_ImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level));
+ }
DECREF_INPUTS();
ERROR_IF(res_o == NULL);
res = PyStackRef_FromPyObjectSteal(res_o);
@@ -2974,7 +3017,16 @@ dummy_func(
inst(IMPORT_FROM, (from -- from, res)) {
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
- PyObject *res_o = _PyEval_ImportFrom(tstate, PyStackRef_AsPyObjectBorrow(from), name);
+ PyObject *res_o;
+ if (PyLazyImport_CheckExact(PyStackRef_AsPyObjectBorrow(from))) {
+ res_o = _PyEval_LazyImportFrom(
+ tstate, frame, PyStackRef_AsPyObjectBorrow(from), name);
+ }
+ else {
+ res_o = _PyEval_ImportFrom(
+ tstate, PyStackRef_AsPyObjectBorrow(from), name);
+ }
+
ERROR_IF(res_o == NULL);
res = PyStackRef_FromPyObjectSteal(res_o);
}
diff --git a/Python/ceval.c b/Python/ceval.c
index 61644d35b5e..758b142d7a7 100644
--- a/Python/ceval.c
+++ b/Python/ceval.c
@@ -2916,11 +2916,13 @@ _PyEval_SliceIndexNotNone(PyObject *v, Py_ssize_t *pi)
}
PyObject *
-_PyEval_ImportName(PyThreadState *tstate, _PyInterpreterFrame *frame,
- PyObject *name, PyObject *fromlist, PyObject *level)
+_PyEval_ImportName(PyThreadState *tstate, PyObject *builtins,
+ PyObject *globals, PyObject *locals, PyObject *name,
+ PyObject *fromlist, PyObject *level)
{
PyObject *import_func;
- if (PyMapping_GetOptionalItem(frame->f_builtins, &_Py_ID(__import__), &import_func) < 0) {
+ if (PyMapping_GetOptionalItem(builtins, &_Py_ID(__import__),
+ &import_func) < 0) {
return NULL;
}
if (import_func == NULL) {
@@ -2928,29 +2930,143 @@ _PyEval_ImportName(PyThreadState *tstate, _PyInterpreterFrame *frame,
return NULL;
}
- PyObject *locals = frame->f_locals;
+ PyObject *res = _PyEval_ImportNameWithImport(
+ tstate, import_func, globals, locals, name, fromlist, level);
+ Py_DECREF(import_func);
+ return res;
+}
+
+PyObject *
+_PyEval_ImportNameWithImport(PyThreadState *tstate, PyObject *import_func,
+ PyObject *globals, PyObject *locals,
+ PyObject *name, PyObject *fromlist, PyObject *level)
+{
if (locals == NULL) {
locals = Py_None;
}
/* Fast path for not overloaded __import__. */
if (_PyImport_IsDefaultImportFunc(tstate->interp, import_func)) {
- Py_DECREF(import_func);
int ilevel = PyLong_AsInt(level);
if (ilevel == -1 && _PyErr_Occurred(tstate)) {
return NULL;
}
return PyImport_ImportModuleLevelObject(
name,
- frame->f_globals,
+ globals,
locals,
fromlist,
ilevel);
}
- PyObject* args[5] = {name, frame->f_globals, locals, fromlist, level};
+ PyObject *args[5] = {name, globals, locals, fromlist, level};
PyObject *res = PyObject_Vectorcall(import_func, args, 5, NULL);
- Py_DECREF(import_func);
+ return res;
+}
+
+static int
+check_lazy_import_compatibility(PyThreadState *tstate, PyObject *globals,
+ PyObject *name, PyObject *level)
+{
+ // Check if this module should be imported lazily due to
+ // the compatibility mode support via __lazy_modules__.
+ PyObject *lazy_modules = NULL;
+ PyObject *abs_name = NULL;
+ int res = -1;
+
+ if (globals != NULL &&
+ PyMapping_GetOptionalItem(globals, &_Py_ID(__lazy_modules__),
+ &lazy_modules) < 0)
+ {
+ return -1;
+ }
+ if (lazy_modules == NULL) {
+ assert(!PyErr_Occurred());
+ return 0;
+ }
+
+ int ilevel = PyLong_AsInt(level);
+ if (ilevel == -1 && _PyErr_Occurred(tstate)) {
+ goto error;
+ }
+
+ abs_name = _PyImport_GetAbsName(tstate, name, globals, ilevel);
+ if (abs_name == NULL) {
+ goto error;
+ }
+
+ res = PySequence_Contains(lazy_modules, abs_name);
+error:
+ Py_XDECREF(abs_name);
+ Py_XDECREF(lazy_modules);
+ return res;
+}
+
+PyObject *
+_PyEval_LazyImportName(PyThreadState *tstate, PyObject *builtins,
+ PyObject *globals, PyObject *locals, PyObject *name,
+ PyObject *fromlist, PyObject *level, int lazy)
+{
+ PyObject *res = NULL;
+ // Check if global policy overrides the local syntax
+ switch (PyImport_GetLazyImportsMode()) {
+ case PyImport_LAZY_NONE:
+ lazy = 0;
+ break;
+ case PyImport_LAZY_ALL:
+ lazy = 1;
+ break;
+ case PyImport_LAZY_NORMAL:
+ break;
+ }
+
+ if (!lazy) {
+ // See if __lazy_modules__ forces this to be lazy.
+ lazy = check_lazy_import_compatibility(tstate, globals, name, level);
+ if (lazy < 0) {
+ return NULL;
+ }
+ }
+
+ if (!lazy) {
+ // Not a lazy import or lazy imports are disabled, fallback to the
+ // regular import.
+ return _PyEval_ImportName(tstate, builtins, globals, locals,
+ name, fromlist, level);
+ }
+
+ PyObject *lazy_import_func;
+ if (PyMapping_GetOptionalItem(builtins, &_Py_ID(__lazy_import__),
+ &lazy_import_func) < 0) {
+ goto error;
+ }
+ if (lazy_import_func == NULL) {
+ assert(!PyErr_Occurred());
+ _PyErr_SetString(tstate, PyExc_ImportError,
+ "__lazy_import__ not found");
+ goto error;
+ }
+
+ if (locals == NULL) {
+ locals = Py_None;
+ }
+
+ if (_PyImport_IsDefaultLazyImportFunc(tstate->interp, lazy_import_func)) {
+ int ilevel = PyLong_AsInt(level);
+ if (ilevel == -1 && PyErr_Occurred()) {
+ goto error;
+ }
+
+ res = _PyImport_LazyImportModuleLevelObject(
+ tstate, name, builtins, globals, locals, fromlist, ilevel
+ );
+ goto error;
+ }
+
+ PyObject *args[6] = {name, globals, locals, fromlist, level, builtins};
+ res = PyObject_Vectorcall(lazy_import_func, args, 6, NULL);
+error:
+ Py_XDECREF(lazy_import_func);
return res;
}
@@ -3122,6 +3238,64 @@ _PyEval_ImportFrom(PyThreadState *tstate, PyObject *v, PyObject *name)
return NULL;
}
+PyObject *
+_PyEval_LazyImportFrom(PyThreadState *tstate, _PyInterpreterFrame *frame, PyObject *v, PyObject *name)
+{
+ assert(PyLazyImport_CheckExact(v));
+ assert(name);
+ assert(PyUnicode_Check(name));
+ PyObject *ret;
+ PyLazyImportObject *d = (PyLazyImportObject *)v;
+ PyObject *mod = PyImport_GetModule(d->lz_from);
+ if (mod != NULL) {
+ // Check if the module already has the attribute, if so, resolve it
+ // eagerly.
+ if (PyModule_Check(mod)) {
+ PyObject *mod_dict = PyModule_GetDict(mod);
+ if (mod_dict != NULL) {
+ if (PyDict_GetItemRef(mod_dict, name, &ret) < 0) {
+ Py_DECREF(mod);
+ return NULL;
+ }
+ if (ret != NULL) {
+ Py_DECREF(mod);
+ return ret;
+ }
+ }
+ }
+ Py_DECREF(mod);
+ }
+
+ if (d->lz_attr != NULL) {
+ if (PyUnicode_Check(d->lz_attr)) {
+ PyObject *from = PyUnicode_FromFormat(
+ "%U.%U", d->lz_from, d->lz_attr);
+ if (from == NULL) {
+ return NULL;
+ }
+ ret = _PyLazyImport_New(frame, d->lz_builtins, from, name);
+ Py_DECREF(from);
+ return ret;
+ }
+ }
+ else {
+ Py_ssize_t dot = PyUnicode_FindChar(
+ d->lz_from, '.', 0, PyUnicode_GET_LENGTH(d->lz_from), 1
+ );
+ if (dot >= 0) {
+ PyObject *from = PyUnicode_Substring(d->lz_from, 0, dot);
+ if (from == NULL) {
+ return NULL;
+ }
+ ret = _PyLazyImport_New(frame, d->lz_builtins, from, name);
+ Py_DECREF(from);
+ return ret;
+ }
+ }
+ ret = _PyLazyImport_New(frame, d->lz_builtins, d->lz_from, name);
+ return ret;
+}
+
#define CANNOT_CATCH_MSG "catching classes that do not inherit from "\
"BaseException is not allowed"
@@ -3410,6 +3584,24 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name
}
*writeto = PyStackRef_FromPyObjectSteal(res);
}
+
+ PyObject *res_o = PyStackRef_AsPyObjectBorrow(*writeto);
+ if (res_o != NULL && PyLazyImport_CheckExact(res_o)) {
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(PyThreadState_GET(), res_o);
+ PyStackRef_CLOSE(writeto[0]);
+ if (l_v == NULL) {
+ assert(PyErr_Occurred());
+ *writeto = PyStackRef_NULL;
+ return;
+ }
+ int err = PyDict_SetItem(globals, name, l_v);
+ if (err < 0) {
+ Py_DECREF(l_v);
+ *writeto = PyStackRef_NULL;
+ return;
+ }
+ *writeto = PyStackRef_FromPyObjectSteal(l_v);
+ }
}
PyObject *
diff --git a/Python/ceval.h b/Python/ceval.h
index b170643e236..bb5f7ddb857 100644
--- a/Python/ceval.h
+++ b/Python/ceval.h
@@ -20,6 +20,7 @@
#include "pycore_interpolation.h" // _PyInterpolation_Build()
#include "pycore_intrinsics.h"
#include "pycore_jit.h"
+#include "pycore_lazyimportobject.h"
#include "pycore_list.h" // _PyList_GetItemRef()
#include "pycore_long.h" // _PyLong_GetZero()
#include "pycore_moduleobject.h" // PyModuleObject
diff --git a/Python/clinic/bltinmodule.c.h b/Python/clinic/bltinmodule.c.h
index f08e5847abe..c8c141f863d 100644
--- a/Python/clinic/bltinmodule.c.h
+++ b/Python/clinic/bltinmodule.c.h
@@ -113,6 +113,101 @@ exit:
return return_value;
}
+PyDoc_STRVAR(builtin___lazy_import____doc__,
+"__lazy_import__($module, /, name, globals=None, locals=None,\n"
+" fromlist=(), level=0)\n"
+"--\n"
+"\n"
+"Lazily imports a module.\n"
+"\n"
+"Returns either the module to be imported or a imp.lazy_module object which\n"
+"indicates the module to be lazily imported.");
+
+#define BUILTIN___LAZY_IMPORT___METHODDEF \
+ {"__lazy_import__", _PyCFunction_CAST(builtin___lazy_import__), METH_FASTCALL|METH_KEYWORDS, builtin___lazy_import____doc__},
+
+static PyObject *
+builtin___lazy_import___impl(PyObject *module, PyObject *name,
+ PyObject *globals, PyObject *locals,
+ PyObject *fromlist, int level);
+
+static PyObject *
+builtin___lazy_import__(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+
+ #define NUM_KEYWORDS 5
+ static struct {
+ PyGC_Head _this_is_not_used;
+ PyObject_VAR_HEAD
+ Py_hash_t ob_hash;
+ PyObject *ob_item[NUM_KEYWORDS];
+ } _kwtuple = {
+ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+ .ob_hash = -1,
+ .ob_item = { &_Py_ID(name), &_Py_ID(globals), &_Py_ID(locals), &_Py_ID(fromlist), &_Py_ID(level), },
+ };
+ #undef NUM_KEYWORDS
+ #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+ #else // !Py_BUILD_CORE
+ # define KWTUPLE NULL
+ #endif // !Py_BUILD_CORE
+
+ static const char * const _keywords[] = {"name", "globals", "locals", "fromlist", "level", NULL};
+ static _PyArg_Parser _parser = {
+ .keywords = _keywords,
+ .fname = "__lazy_import__",
+ .kwtuple = KWTUPLE,
+ };
+ #undef KWTUPLE
+ PyObject *argsbuf[5];
+ Py_ssize_t noptargs = nargs + (kwnames ? PyTuple_GET_SIZE(kwnames) : 0) - 1;
+ PyObject *name;
+ PyObject *globals = NULL;
+ PyObject *locals = NULL;
+ PyObject *fromlist = NULL;
+ int level = 0;
+
+ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
+ /*minpos*/ 1, /*maxpos*/ 5, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+ if (!args) {
+ goto exit;
+ }
+ name = args[0];
+ if (!noptargs) {
+ goto skip_optional_pos;
+ }
+ if (args[1]) {
+ globals = args[1];
+ if (!--noptargs) {
+ goto skip_optional_pos;
+ }
+ }
+ if (args[2]) {
+ locals = args[2];
+ if (!--noptargs) {
+ goto skip_optional_pos;
+ }
+ }
+ if (args[3]) {
+ fromlist = args[3];
+ if (!--noptargs) {
+ goto skip_optional_pos;
+ }
+ }
+ level = PyLong_AsInt(args[4]);
+ if (level == -1 && PyErr_Occurred()) {
+ goto exit;
+ }
+skip_optional_pos:
+ return_value = builtin___lazy_import___impl(module, name, globals, locals, fromlist, level);
+
+exit:
+ return return_value;
+}
+
PyDoc_STRVAR(builtin_abs__doc__,
"abs($module, number, /)\n"
"--\n"
@@ -1285,4 +1380,4 @@ builtin_issubclass(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
exit:
return return_value;
}
-/*[clinic end generated code: output=06500bcc9a341e68 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=1c3327da8885bb8e input=a9049054013a1b77]*/
diff --git a/Python/clinic/import.c.h b/Python/clinic/import.c.h
index 9bbb13f7566..de62714ebdd 100644
--- a/Python/clinic/import.c.h
+++ b/Python/clinic/import.c.h
@@ -622,6 +622,41 @@ exit:
return return_value;
}
+PyDoc_STRVAR(_imp__set_lazy_attributes__doc__,
+"_set_lazy_attributes($module, modobj, name, /)\n"
+"--\n"
+"\n"
+"Sets attributes to lazy submodules on the module, as side effects.");
+
+#define _IMP__SET_LAZY_ATTRIBUTES_METHODDEF \
+ {"_set_lazy_attributes", _PyCFunction_CAST(_imp__set_lazy_attributes), METH_FASTCALL, _imp__set_lazy_attributes__doc__},
+
+static PyObject *
+_imp__set_lazy_attributes_impl(PyObject *module, PyObject *modobj,
+ PyObject *name);
+
+static PyObject *
+_imp__set_lazy_attributes(PyObject *module, PyObject *const *args, Py_ssize_t nargs)
+{
+ PyObject *return_value = NULL;
+ PyObject *modobj;
+ PyObject *name;
+
+ if (!_PyArg_CheckPositional("_set_lazy_attributes", nargs, 2, 2)) {
+ goto exit;
+ }
+ modobj = args[0];
+ if (!PyUnicode_Check(args[1])) {
+ _PyArg_BadArgument("_set_lazy_attributes", "argument 2", "str", args[1]);
+ goto exit;
+ }
+ name = args[1];
+ return_value = _imp__set_lazy_attributes_impl(module, modobj, name);
+
+exit:
+ return return_value;
+}
+
#ifndef _IMP_CREATE_DYNAMIC_METHODDEF
#define _IMP_CREATE_DYNAMIC_METHODDEF
#endif /* !defined(_IMP_CREATE_DYNAMIC_METHODDEF) */
@@ -629,4 +664,4 @@ exit:
#ifndef _IMP_EXEC_DYNAMIC_METHODDEF
#define _IMP_EXEC_DYNAMIC_METHODDEF
#endif /* !defined(_IMP_EXEC_DYNAMIC_METHODDEF) */
-/*[clinic end generated code: output=24f597d6b0f3feed input=a9049054013a1b77]*/
+/*[clinic end generated code: output=5fa42f580441b3fa input=a9049054013a1b77]*/
diff --git a/Python/clinic/sysmodule.c.h b/Python/clinic/sysmodule.c.h
index 4c4a86de2f9..f8ae7f18acc 100644
--- a/Python/clinic/sysmodule.c.h
+++ b/Python/clinic/sysmodule.c.h
@@ -1820,6 +1820,180 @@ exit:
return return_value;
}
+PyDoc_STRVAR(sys_set_lazy_imports_filter__doc__,
+"set_lazy_imports_filter($module, /, filter)\n"
+"--\n"
+"\n"
+"Set the lazy imports filter callback.\n"
+"\n"
+"The filter is a callable which disables lazy imports when they\n"
+"would otherwise be enabled. Returns True if the import is still enabled\n"
+"or False to disable it. The callable is called with:\n"
+"\n"
+"(importing_module_name, imported_module_name, [fromlist])\n"
+"\n"
+"Pass None to clear the filter.");
+
+#define SYS_SET_LAZY_IMPORTS_FILTER_METHODDEF \
+ {"set_lazy_imports_filter", _PyCFunction_CAST(sys_set_lazy_imports_filter), METH_FASTCALL|METH_KEYWORDS, sys_set_lazy_imports_filter__doc__},
+
+static PyObject *
+sys_set_lazy_imports_filter_impl(PyObject *module, PyObject *filter);
+
+static PyObject *
+sys_set_lazy_imports_filter(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+
+ #define NUM_KEYWORDS 1
+ static struct {
+ PyGC_Head _this_is_not_used;
+ PyObject_VAR_HEAD
+ Py_hash_t ob_hash;
+ PyObject *ob_item[NUM_KEYWORDS];
+ } _kwtuple = {
+ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+ .ob_hash = -1,
+ .ob_item = { &_Py_ID(filter), },
+ };
+ #undef NUM_KEYWORDS
+ #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+ #else // !Py_BUILD_CORE
+ # define KWTUPLE NULL
+ #endif // !Py_BUILD_CORE
+
+ static const char * const _keywords[] = {"filter", NULL};
+ static _PyArg_Parser _parser = {
+ .keywords = _keywords,
+ .fname = "set_lazy_imports_filter",
+ .kwtuple = KWTUPLE,
+ };
+ #undef KWTUPLE
+ PyObject *argsbuf[1];
+ PyObject *filter;
+
+ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
+ /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+ if (!args) {
+ goto exit;
+ }
+ filter = args[0];
+ return_value = sys_set_lazy_imports_filter_impl(module, filter);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(sys_get_lazy_imports_filter__doc__,
+"get_lazy_imports_filter($module, /)\n"
+"--\n"
+"\n"
+"Get the current lazy imports filter callback.\n"
+"\n"
+"Returns the filter callable or None if no filter is set.");
+
+#define SYS_GET_LAZY_IMPORTS_FILTER_METHODDEF \
+ {"get_lazy_imports_filter", (PyCFunction)sys_get_lazy_imports_filter, METH_NOARGS, sys_get_lazy_imports_filter__doc__},
+
+static PyObject *
+sys_get_lazy_imports_filter_impl(PyObject *module);
+
+static PyObject *
+sys_get_lazy_imports_filter(PyObject *module, PyObject *Py_UNUSED(ignored))
+{
+ return sys_get_lazy_imports_filter_impl(module);
+}
+
+PyDoc_STRVAR(sys_set_lazy_imports__doc__,
+"set_lazy_imports($module, /, mode)\n"
+"--\n"
+"\n"
+"Sets the global lazy imports mode.\n"
+"\n"
+"The mode parameter must be one of the following strings:\n"
+"- \"all\": All top-level imports become potentially lazy\n"
+"- \"none\": All lazy imports are suppressed (even explicitly marked ones)\n"
+"- \"normal\": Only explicitly marked imports (with \'lazy\' keyword) are lazy\n"
+"\n"
+"In addition to the mode, lazy imports can be controlled via the filter\n"
+"provided to sys.set_lazy_imports_filter");
+
+#define SYS_SET_LAZY_IMPORTS_METHODDEF \
+ {"set_lazy_imports", _PyCFunction_CAST(sys_set_lazy_imports), METH_FASTCALL|METH_KEYWORDS, sys_set_lazy_imports__doc__},
+
+static PyObject *
+sys_set_lazy_imports_impl(PyObject *module, PyObject *mode);
+
+static PyObject *
+sys_set_lazy_imports(PyObject *module, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
+{
+ PyObject *return_value = NULL;
+ #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+
+ #define NUM_KEYWORDS 1
+ static struct {
+ PyGC_Head _this_is_not_used;
+ PyObject_VAR_HEAD
+ Py_hash_t ob_hash;
+ PyObject *ob_item[NUM_KEYWORDS];
+ } _kwtuple = {
+ .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+ .ob_hash = -1,
+ .ob_item = { &_Py_ID(mode), },
+ };
+ #undef NUM_KEYWORDS
+ #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+ #else // !Py_BUILD_CORE
+ # define KWTUPLE NULL
+ #endif // !Py_BUILD_CORE
+
+ static const char * const _keywords[] = {"mode", NULL};
+ static _PyArg_Parser _parser = {
+ .keywords = _keywords,
+ .fname = "set_lazy_imports",
+ .kwtuple = KWTUPLE,
+ };
+ #undef KWTUPLE
+ PyObject *argsbuf[1];
+ PyObject *mode;
+
+ args = _PyArg_UnpackKeywords(args, nargs, NULL, kwnames, &_parser,
+ /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+ if (!args) {
+ goto exit;
+ }
+ mode = args[0];
+ return_value = sys_set_lazy_imports_impl(module, mode);
+
+exit:
+ return return_value;
+}
+
+PyDoc_STRVAR(sys_get_lazy_imports__doc__,
+"get_lazy_imports($module, /)\n"
+"--\n"
+"\n"
+"Gets the global lazy imports mode.\n"
+"\n"
+"Returns \"all\" if all top level imports are potentially lazy.\n"
+"Returns \"none\" if all explicitly marked lazy imports are suppressed.\n"
+"Returns \"normal\" if only explicitly marked imports are lazy.");
+
+#define SYS_GET_LAZY_IMPORTS_METHODDEF \
+ {"get_lazy_imports", (PyCFunction)sys_get_lazy_imports, METH_NOARGS, sys_get_lazy_imports__doc__},
+
+static PyObject *
+sys_get_lazy_imports_impl(PyObject *module);
+
+static PyObject *
+sys_get_lazy_imports(PyObject *module, PyObject *Py_UNUSED(ignored))
+{
+ return sys_get_lazy_imports_impl(module);
+}
+
PyDoc_STRVAR(_jit_is_available__doc__,
"is_available($module, /)\n"
"--\n"
@@ -1947,4 +2121,4 @@ exit:
#ifndef SYS_GETANDROIDAPILEVEL_METHODDEF
#define SYS_GETANDROIDAPILEVEL_METHODDEF
#endif /* !defined(SYS_GETANDROIDAPILEVEL_METHODDEF) */
-/*[clinic end generated code: output=5f7d84c5bf00d557 input=a9049054013a1b77]*/
+/*[clinic end generated code: output=adbadb629b98eabf input=a9049054013a1b77]*/
diff --git a/Python/codegen.c b/Python/codegen.c
index 5227312b4f7..32a03e7212e 100644
--- a/Python/codegen.c
+++ b/Python/codegen.c
@@ -357,8 +357,8 @@ codegen_addop_o(compiler *c, location loc,
#define LOAD_ZERO_SUPER_METHOD -4
static int
-codegen_addop_name(compiler *c, location loc,
- int opcode, PyObject *dict, PyObject *o)
+codegen_addop_name_custom(compiler *c, location loc, int opcode,
+ PyObject *dict, PyObject *o, int shift, int low)
{
PyObject *mangled = _PyCompile_MaybeMangle(c, o);
if (!mangled) {
@@ -369,40 +369,51 @@ codegen_addop_name(compiler *c, location loc,
if (arg < 0) {
return ERROR;
}
+ ADDOP_I(c, loc, opcode, (arg << shift) | low);
+ return SUCCESS;
+}
+
+static int
+codegen_addop_name(compiler *c, location loc,
+ int opcode, PyObject *dict, PyObject *o)
+{
+ int shift = 0, low = 0;
if (opcode == LOAD_ATTR) {
- arg <<= 1;
+ shift = 1;
}
if (opcode == LOAD_METHOD) {
opcode = LOAD_ATTR;
- arg <<= 1;
- arg |= 1;
+ shift = 1;
+ low = 1;
}
if (opcode == LOAD_SUPER_ATTR) {
- arg <<= 2;
- arg |= 2;
+ shift = 2;
+ low = 2;
}
if (opcode == LOAD_SUPER_METHOD) {
opcode = LOAD_SUPER_ATTR;
- arg <<= 2;
- arg |= 3;
+ shift = 2;
+ low = 3;
}
if (opcode == LOAD_ZERO_SUPER_ATTR) {
opcode = LOAD_SUPER_ATTR;
- arg <<= 2;
+ shift = 2;
}
if (opcode == LOAD_ZERO_SUPER_METHOD) {
opcode = LOAD_SUPER_ATTR;
- arg <<= 2;
- arg |= 1;
+ shift = 2;
+ low = 1;
}
- ADDOP_I(c, loc, opcode, arg);
- return SUCCESS;
+ return codegen_addop_name_custom(c, loc, opcode, dict, o, shift, low);
}
#define ADDOP_NAME(C, LOC, OP, O, TYPE) \
RETURN_IF_ERROR(codegen_addop_name((C), (LOC), (OP), METADATA(C)->u_ ## TYPE, (O)))
-static int
+#define ADDOP_NAME_CUSTOM(C, LOC, OP, O, TYPE, SHIFT, LOW) \
+ RETURN_IF_ERROR(codegen_addop_name_custom((C), (LOC), (OP), METADATA(C)->u_ ## TYPE, (O), SHIFT, LOW))
+
+ static int
codegen_addop_j(instr_sequence *seq, location loc,
int opcode, jump_target_label target)
{
@@ -2864,6 +2875,17 @@ codegen_import_as(compiler *c, location loc,
return codegen_nameop(c, loc, asname, Store);
}
+static int
+codegen_validate_lazy_import(compiler *c, location loc)
+{
+ if (_PyCompile_ScopeType(c) != COMPILE_SCOPE_MODULE) {
+ return _PyCompile_Error(
+ c, loc, "lazy imports only allowed in module scope");
+ }
+
+ return SUCCESS;
+}
+
static int
codegen_import(compiler *c, stmt_ty s)
{
@@ -2884,7 +2906,18 @@ codegen_import(compiler *c, stmt_ty s)
ADDOP_LOAD_CONST(c, loc, zero);
ADDOP_LOAD_CONST(c, loc, Py_None);
- ADDOP_NAME(c, loc, IMPORT_NAME, alias->name, names);
+ if (s->v.Import.is_lazy) {
+ RETURN_IF_ERROR(codegen_validate_lazy_import(c, loc));
+ ADDOP_NAME_CUSTOM(c, loc, IMPORT_NAME, alias->name, names, 2, 1);
+ } else {
+ if (_PyCompile_InExceptionHandler(c) ||
+ _PyCompile_ScopeType(c) != COMPILE_SCOPE_MODULE) {
+ // force eager import in try/except block
+ ADDOP_NAME_CUSTOM(c, loc, IMPORT_NAME, alias->name, names, 2, 2);
+ } else {
+ ADDOP_NAME_CUSTOM(c, loc, IMPORT_NAME, alias->name, names, 2, 0);
+ }
+ }
if (alias->asname) {
r = codegen_import_as(c, loc, alias->name, alias->asname);
@@ -2930,13 +2963,29 @@ codegen_from_import(compiler *c, stmt_ty s)
ADDOP_LOAD_CONST_NEW(c, LOC(s), names);
+ identifier from = &_Py_STR(empty);
if (s->v.ImportFrom.module) {
- ADDOP_NAME(c, LOC(s), IMPORT_NAME, s->v.ImportFrom.module, names);
+ from = s->v.ImportFrom.module;
}
- else {
- _Py_DECLARE_STR(empty, "");
- ADDOP_NAME(c, LOC(s), IMPORT_NAME, &_Py_STR(empty), names);
+ if (s->v.ImportFrom.is_lazy) {
+ alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, 0);
+ if (PyUnicode_READ_CHAR(alias->name, 0) == '*') {
+ return _PyCompile_Error(c, LOC(s), "cannot lazy import *");
+ }
+ RETURN_IF_ERROR(codegen_validate_lazy_import(c, LOC(s)));
+ ADDOP_NAME_CUSTOM(c, LOC(s), IMPORT_NAME, from, names, 2, 1);
+ } else {
+ alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, 0);
+ if (_PyCompile_InExceptionHandler(c) ||
+ _PyCompile_ScopeType(c) != COMPILE_SCOPE_MODULE ||
+ PyUnicode_READ_CHAR(alias->name, 0) == '*') {
+ // forced non-lazy import due to try/except or import *
+ ADDOP_NAME_CUSTOM(c, LOC(s), IMPORT_NAME, from, names, 2, 2);
+ } else {
+ ADDOP_NAME_CUSTOM(c, LOC(s), IMPORT_NAME, from, names, 2, 0);
+ }
}
+
for (Py_ssize_t i = 0; i < n; i++) {
alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
identifier store_name;
diff --git a/Python/compile.c b/Python/compile.c
index 1f154004969..96779a0a219 100644
--- a/Python/compile.c
+++ b/Python/compile.c
@@ -800,6 +800,26 @@ _PyCompile_TopFBlock(compiler *c)
return &c->u->u_fblock[c->u->u_nfblocks - 1];
}
+bool
+_PyCompile_InExceptionHandler(compiler *c)
+{
+ for (Py_ssize_t i = 0; i < c->u->u_nfblocks; i++) {
+ fblockinfo *block = &c->u->u_fblock[i];
+ switch (block->fb_type) {
+ case COMPILE_FBLOCK_TRY_EXCEPT:
+ case COMPILE_FBLOCK_FINALLY_TRY:
+ case COMPILE_FBLOCK_FINALLY_END:
+ case COMPILE_FBLOCK_EXCEPTION_HANDLER:
+ case COMPILE_FBLOCK_EXCEPTION_GROUP_HANDLER:
+ case COMPILE_FBLOCK_HANDLER_CLEANUP:
+ return true;
+ default:
+ break;
+ }
+ }
+ return false;
+}
+
void
_PyCompile_DeferredAnnotations(compiler *c,
PyObject **deferred_annotations,
diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h
index f976e150451..9dead4eecc7 100644
--- a/Python/executor_cases.c.h
+++ b/Python/executor_cases.c.h
@@ -7447,6 +7447,32 @@
SET_CURRENT_CACHED_VALUES(0);
JUMP_TO_ERROR();
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (l_v == NULL) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_DECREF(v_o);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ SET_CURRENT_CACHED_VALUES(0);
+ JUMP_TO_ERROR();
+ }
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ int err = PyDict_SetItem(GLOBALS(), name, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (err < 0) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_DECREF(v_o);
+ Py_DECREF(l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ SET_CURRENT_CACHED_VALUES(0);
+ JUMP_TO_ERROR();
+ }
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
v = PyStackRef_FromPyObjectSteal(v_o);
_tos_cache0 = v;
_tos_cache1 = PyStackRef_ZERO_BITS;
@@ -10523,15 +10549,34 @@
oparg = CURRENT_OPARG();
fromlist = _stack_item_1;
level = _stack_item_0;
- PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
- stack_pointer[0] = level;
- stack_pointer[1] = fromlist;
- stack_pointer += 2;
- ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
+ PyObject *name = GETITEM(FRAME_CO_NAMES, oparg >> 2);
+ PyObject *res_o;
+ if (!(oparg & 0x02)) {
+ stack_pointer[0] = level;
+ stack_pointer[1] = fromlist;
+ stack_pointer += 2;
+ ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_LazyImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level),
+ oparg & 0x01);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
+ else {
+ stack_pointer[0] = level;
+ stack_pointer[1] = fromlist;
+ stack_pointer += 2;
+ ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_ImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level));
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
_PyFrame_SetStackPointer(frame, stack_pointer);
- PyObject *res_o = _PyEval_ImportName(tstate, frame, name,
- PyStackRef_AsPyObjectBorrow(fromlist),
- PyStackRef_AsPyObjectBorrow(level));
_PyStackRef tmp = fromlist;
fromlist = PyStackRef_NULL;
stack_pointer[-1] = fromlist;
@@ -10565,13 +10610,27 @@
oparg = CURRENT_OPARG();
from = _stack_item_0;
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
- stack_pointer[0] = from;
- stack_pointer += 1;
- ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
- _PyFrame_SetStackPointer(frame, stack_pointer);
- PyObject *res_o = _PyEval_ImportFrom(tstate, PyStackRef_AsPyObjectBorrow(from), name);
- stack_pointer = _PyFrame_GetStackPointer(frame);
+ PyObject *res_o;
+ if (PyLazyImport_CheckExact(PyStackRef_AsPyObjectBorrow(from))) {
+ stack_pointer[0] = from;
+ stack_pointer += 1;
+ ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_LazyImportFrom(
+ tstate, frame, PyStackRef_AsPyObjectBorrow(from), name);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
+ else {
+ stack_pointer[0] = from;
+ stack_pointer += 1;
+ ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__);
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_ImportFrom(
+ tstate, PyStackRef_AsPyObjectBorrow(from), name);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
if (res_o == NULL) {
+ stack_pointer[-1] = from;
SET_CURRENT_CACHED_VALUES(0);
JUMP_TO_ERROR();
}
diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h
index 202bf5edcf0..37fa6d67919 100644
--- a/Python/generated_cases.c.h
+++ b/Python/generated_cases.c.h
@@ -6371,9 +6371,19 @@
_PyStackRef res;
from = stack_pointer[-1];
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
- _PyFrame_SetStackPointer(frame, stack_pointer);
- PyObject *res_o = _PyEval_ImportFrom(tstate, PyStackRef_AsPyObjectBorrow(from), name);
- stack_pointer = _PyFrame_GetStackPointer(frame);
+ PyObject *res_o;
+ if (PyLazyImport_CheckExact(PyStackRef_AsPyObjectBorrow(from))) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_LazyImportFrom(
+ tstate, frame, PyStackRef_AsPyObjectBorrow(from), name);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
+ else {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_ImportFrom(
+ tstate, PyStackRef_AsPyObjectBorrow(from), name);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
if (res_o == NULL) {
JUMP_TO_LABEL(error);
}
@@ -6397,11 +6407,26 @@
_PyStackRef res;
fromlist = stack_pointer[-1];
level = stack_pointer[-2];
- PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
+ PyObject *name = GETITEM(FRAME_CO_NAMES, oparg >> 2);
+ PyObject *res_o;
+ if (!(oparg & 0x02)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_LazyImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level),
+ oparg & 0x01);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
+ else {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ res_o = _PyEval_ImportName(tstate, BUILTINS(), GLOBALS(),
+ LOCALS(), name,
+ PyStackRef_AsPyObjectBorrow(fromlist),
+ PyStackRef_AsPyObjectBorrow(level));
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
_PyFrame_SetStackPointer(frame, stack_pointer);
- PyObject *res_o = _PyEval_ImportName(tstate, frame, name,
- PyStackRef_AsPyObjectBorrow(fromlist),
- PyStackRef_AsPyObjectBorrow(level));
_PyStackRef tmp = fromlist;
fromlist = PyStackRef_NULL;
stack_pointer[-1] = fromlist;
@@ -9154,6 +9179,15 @@
}
JUMP_TO_LABEL(error);
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (v_o == NULL) {
+ JUMP_TO_LABEL(error);
+ }
+ }
}
else {
_PyFrame_SetStackPointer(frame, stack_pointer);
@@ -9178,6 +9212,15 @@
JUMP_TO_LABEL(error);
}
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (v_o == NULL) {
+ JUMP_TO_LABEL(error);
+ }
+ }
}
}
v = PyStackRef_FromPyObjectSteal(v_o);
@@ -9430,6 +9473,30 @@
if (v_o == NULL) {
JUMP_TO_LABEL(error);
}
+ if (PyLazyImport_CheckExact(v_o)) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ PyObject *l_v = _PyImport_LoadLazyImportTstate(tstate, v_o);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (l_v == NULL) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_DECREF(v_o);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ JUMP_TO_LABEL(error);
+ }
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ int err = PyDict_SetItem(GLOBALS(), name, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ if (err < 0) {
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_DECREF(v_o);
+ Py_DECREF(l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ JUMP_TO_LABEL(error);
+ }
+ _PyFrame_SetStackPointer(frame, stack_pointer);
+ Py_SETREF(v_o, l_v);
+ stack_pointer = _PyFrame_GetStackPointer(frame);
+ }
v = PyStackRef_FromPyObjectSteal(v_o);
stack_pointer[0] = v;
stack_pointer += 1;
diff --git a/Python/import.c b/Python/import.c
index c9e892c96b0..c20c55727d2 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -4,21 +4,28 @@
#include "pycore_audit.h" // _PySys_Audit()
#include "pycore_ceval.h"
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION()
+#include "pycore_dict.h" // _PyDict_Contains_KnownHash()
#include "pycore_hashtable.h" // _Py_hashtable_new_full()
#include "pycore_import.h" // _PyImport_BootstrapImp()
#include "pycore_initconfig.h" // _PyStatus_OK()
#include "pycore_interp.h" // struct _import_runtime_state
+#include "pycore_interpframe.h"
+#include "pycore_lazyimportobject.h"
+#include "pycore_long.h" // _PyLong_GetZero
#include "pycore_magic_number.h" // PYC_MAGIC_NUMBER_TOKEN
#include "pycore_moduleobject.h" // _PyModule_GetDef()
#include "pycore_namespace.h" // _PyNamespace_Type
#include "pycore_object.h" // _Py_SetImmortal()
+#include "pycore_pyatomic_ft_wrappers.h"
#include "pycore_pyerrors.h" // _PyErr_SetString()
#include "pycore_pyhash.h" // _Py_KeyedHash()
#include "pycore_pylifecycle.h"
#include "pycore_pymem.h" // _PyMem_DefaultRawFree()
#include "pycore_pystate.h" // _PyInterpreterState_GET()
+#include "pycore_setobject.h" // _PySet_NextEntry()
#include "pycore_sysmodule.h" // _PySys_ClearAttrString()
#include "pycore_time.h" // _PyTime_AsMicroseconds()
+#include "pycore_traceback.h"
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
#include "pycore_weakref.h" // _PyWeakref_GET_REF()
@@ -85,6 +92,8 @@ static struct _inittab *inittab_copy = NULL;
(interp)->imports.modules
#define MODULES_BY_INDEX(interp) \
(interp)->imports.modules_by_index
+#define LAZY_MODULES(interp) \
+ (interp)->imports.lazy_modules
#define IMPORTLIB(interp) \
(interp)->imports.importlib
#define OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) \
@@ -98,12 +107,30 @@ static struct _inittab *inittab_copy = NULL;
#define IMPORT_FUNC(interp) \
(interp)->imports.import_func
+#define LAZY_IMPORT_FUNC(interp) \
+ (interp)->imports.lazy_import_func
+
#define IMPORT_LOCK(interp) \
(interp)->imports.lock
#define FIND_AND_LOAD(interp) \
(interp)->imports.find_and_load
+#define LAZY_IMPORTS_MODE(interp) \
+ (interp)->imports.lazy_imports_mode
+
+#define LAZY_IMPORTS_FILTER(interp) \
+ (interp)->imports.lazy_imports_filter
+
+#ifdef Py_GIL_DISABLED
+#define LAZY_IMPORTS_LOCK(interp) PyMutex_Lock(&(interp)->imports.lazy_mutex)
+#define LAZY_IMPORTS_UNLOCK(interp) PyMutex_Unlock(&(interp)->imports.lazy_mutex)
+#else
+#define LAZY_IMPORTS_LOCK(interp)
+#define LAZY_IMPORTS_UNLOCK(interp)
+#endif
+
+
#define _IMPORT_TIME_HEADER(interp) \
do { \
if (FIND_AND_LOAD((interp)).header) { \
@@ -241,6 +268,20 @@ import_get_module(PyThreadState *tstate, PyObject *name)
return m;
}
+PyObject *
+_PyImport_InitLazyModules(PyInterpreterState *interp)
+{
+ assert(LAZY_MODULES(interp) == NULL);
+ LAZY_MODULES(interp) = PyDict_New();
+ return LAZY_MODULES(interp);
+}
+
+void
+_PyImport_ClearLazyModules(PyInterpreterState *interp)
+{
+ Py_CLEAR(LAZY_MODULES(interp));
+}
+
static int
import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
{
@@ -2147,7 +2188,8 @@ import_run_extension(PyThreadState *tstate, PyModInitFunction p0,
if (filename == NULL) {
return NULL;
}
- } else {
+ }
+ else {
filename = Py_NewRef(info->filename);
}
// XXX There's a refleak somewhere with the filename.
@@ -3539,6 +3581,13 @@ _PyImport_InitDefaultImportFunc(PyInterpreterState *interp)
return -1;
}
IMPORT_FUNC(interp) = import_func;
+
+ // Get the __lazy_import__ function
+ if (PyDict_GetItemStringRef(interp->builtins, "__lazy_import__",
+ &import_func) <= 0) {
+ return -1;
+ }
+ LAZY_IMPORT_FUNC(interp) = import_func;
return 0;
}
@@ -3548,6 +3597,11 @@ _PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
return func == IMPORT_FUNC(interp);
}
+int
+_PyImport_IsDefaultLazyImportFunc(PyInterpreterState *interp, PyObject *func)
+{
+ return func == LAZY_IMPORT_FUNC(interp);
+}
/* Import a module, either built-in, frozen, or external, and return
its module object WITH INCREMENTED REFERENCE COUNT */
@@ -3811,6 +3865,234 @@ resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level
return NULL;
}
+PyObject *
+_PyImport_ResolveName(PyThreadState *tstate, PyObject *name,
+ PyObject *globals, int level)
+{
+ return resolve_name(tstate, name, globals, level);
+}
+
+PyObject *
+_PyImport_LoadLazyImportTstate(PyThreadState *tstate, PyObject *lazy_import)
+{
+ PyObject *obj = NULL;
+ PyObject *fromlist = Py_None;
+ PyObject *import_func = NULL;
+ assert(lazy_import != NULL);
+ assert(PyLazyImport_CheckExact(lazy_import));
+
+ PyLazyImportObject *lz = (PyLazyImportObject *)lazy_import;
+ PyInterpreterState *interp = tstate->interp;
+
+ // Acquire the global import lock to serialize reification
+ _PyImport_AcquireLock(interp);
+
+ // Check if we are already importing this module, if so, then we want to
+ // return an error that indicates we've hit a cycle which will indicate
+ // the value isn't yet available.
+ PyObject *importing = interp->imports.lazy_importing_modules;
+ if (importing == NULL) {
+ importing = interp->imports.lazy_importing_modules = PySet_New(NULL);
+ if (importing == NULL) {
+ _PyImport_ReleaseLock(interp);
+ return NULL;
+ }
+ }
+
+ assert(PyAnySet_CheckExact(importing));
+ int is_loading = _PySet_Contains((PySetObject *)importing, lazy_import);
+ if (is_loading < 0) {
+ _PyImport_ReleaseLock(interp);
+ return NULL;
+ }
+ else if (is_loading == 1) {
+ PyObject *name = _PyLazyImport_GetName(lazy_import);
+ if (name == NULL) {
+ _PyImport_ReleaseLock(interp);
+ return NULL;
+ }
+ PyObject *errmsg = PyUnicode_FromFormat(
+ "cannot import name %R (most likely due to a circular import)",
+ name);
+ if (errmsg == NULL) {
+ Py_DECREF(name);
+ _PyImport_ReleaseLock(interp);
+ return NULL;
+ }
+ PyErr_SetImportErrorSubclass(PyExc_ImportCycleError, errmsg,
+ lz->lz_from, NULL);
+ Py_DECREF(errmsg);
+ Py_DECREF(name);
+ _PyImport_ReleaseLock(interp);
+ return NULL;
+ }
+ else if (PySet_Add(importing, lazy_import) < 0) {
+ _PyImport_ReleaseLock(interp);
+ goto error;
+ }
+
+ Py_ssize_t dot = -1;
+ int full = 0;
+ if (lz->lz_attr != NULL) {
+ full = 1;
+ }
+ if (!full) {
+ dot = PyUnicode_FindChar(lz->lz_from, '.', 0,
+ PyUnicode_GET_LENGTH(lz->lz_from), 1);
+ }
+ if (dot < 0) {
+ full = 1;
+ }
+
+ if (lz->lz_attr != NULL) {
+ if (PyUnicode_Check(lz->lz_attr)) {
+ fromlist = PyTuple_New(1);
+ if (fromlist == NULL) {
+ goto error;
+ }
+ Py_INCREF(lz->lz_attr);
+ PyTuple_SET_ITEM(fromlist, 0, lz->lz_attr);
+ }
+ else {
+ Py_INCREF(lz->lz_attr);
+ fromlist = lz->lz_attr;
+ }
+ }
+
+ PyObject *globals = PyEval_GetGlobals();
+
+ if (PyMapping_GetOptionalItem(lz->lz_builtins, &_Py_ID(__import__),
+ &import_func) < 0) {
+ goto error;
+ }
+ if (import_func == NULL) {
+ PyErr_SetString(PyExc_ImportError, "__import__ not found");
+ goto error;
+ }
+ if (full) {
+ obj = _PyEval_ImportNameWithImport(
+ tstate, import_func, globals, globals,
+ lz->lz_from, fromlist, _PyLong_GetZero()
+ );
+ }
+ else {
+ PyObject *name = PyUnicode_Substring(lz->lz_from, 0, dot);
+ if (name == NULL) {
+ goto error;
+ }
+ obj = _PyEval_ImportNameWithImport(
+ tstate, import_func, globals, globals,
+ name, fromlist, _PyLong_GetZero()
+ );
+ Py_DECREF(name);
+ }
+ if (obj == NULL) {
+ goto error;
+ }
+
+ if (lz->lz_attr != NULL && PyUnicode_Check(lz->lz_attr)) {
+ PyObject *from = obj;
+ obj = _PyEval_ImportFrom(tstate, from, lz->lz_attr);
+ Py_DECREF(from);
+ if (obj == NULL) {
+ goto error;
+ }
+ }
+
+ assert(!PyLazyImport_CheckExact(obj));
+
+ goto ok;
+
+error:
+ Py_CLEAR(obj);
+
+ // If an error occurred and we have frame information, add it to the
+ // exception.
+ if (PyErr_Occurred() && lz->lz_code != NULL && lz->lz_instr_offset >= 0) {
+ // Get the current exception - this already has the full traceback
+ // from the access point.
+ PyObject *exc = _PyErr_GetRaisedException(tstate);
+
+ // Get import name - this can fail and set an exception.
+ PyObject *import_name = _PyLazyImport_GetName(lazy_import);
+ if (!import_name) {
+ // Failed to get import name, just restore original exception.
+ _PyErr_SetRaisedException(tstate, exc);
+ goto ok;
+ }
+
+ // Resolve line number from instruction offset on demand.
+ int lineno = PyCode_Addr2Line((PyCodeObject *)lz->lz_code,
+ lz->lz_instr_offset*2);
+
+ // Get strings - these can return NULL on encoding errors.
+ const char *filename_str = PyUnicode_AsUTF8(lz->lz_code->co_filename);
+ if (!filename_str) {
+ // Unicode conversion failed - clear error and restore original
+ // exception.
+ PyErr_Clear();
+ Py_DECREF(import_name);
+ _PyErr_SetRaisedException(tstate, exc);
+ goto ok;
+ }
+
+ const char *funcname_str = PyUnicode_AsUTF8(lz->lz_code->co_name);
+ if (!funcname_str) {
+ // Unicode conversion failed - clear error and restore original
+ // exception.
+ PyErr_Clear();
+ Py_DECREF(import_name);
+ _PyErr_SetRaisedException(tstate, exc);
+ goto ok;
+ }
+
+ // Create a cause exception showing where the lazy import was declared.
+ PyObject *msg = PyUnicode_FromFormat(
+ "deferred import of '%U' raised an exception during resolution",
+ import_name
+ );
+ Py_DECREF(import_name); // Done with import_name.
+
+ if (!msg) {
+ // Failed to create message - restore original exception.
+ _PyErr_SetRaisedException(tstate, exc);
+ goto ok;
+ }
+
+ PyObject *cause_exc = PyObject_CallOneArg(PyExc_ImportError, msg);
+ Py_DECREF(msg); // Done with msg.
+
+ if (!cause_exc) {
+ // Failed to create exception - restore original.
+ _PyErr_SetRaisedException(tstate, exc);
+ goto ok;
+ }
+
+ // Add traceback entry for the lazy import declaration.
+ _PyErr_SetRaisedException(tstate, cause_exc);
+ _PyTraceback_Add(funcname_str, filename_str, lineno);
+ PyObject *cause_with_tb = _PyErr_GetRaisedException(tstate);
+
+ // Set the cause on the original exception.
+ PyException_SetCause(exc, cause_with_tb); // Steals ref to cause_with_tb.
+
+ // Restore the original exception with its full traceback.
+ _PyErr_SetRaisedException(tstate, exc);
+ }
+
+ok:
+ if (PySet_Discard(importing, lazy_import) < 0) {
+ Py_CLEAR(obj);
+ }
+
+ // Release the global import lock.
+ _PyImport_ReleaseLock(interp);
+
+ Py_XDECREF(fromlist);
+ Py_XDECREF(import_func);
+ return obj;
+}
+
static PyObject *
import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
{
@@ -3865,6 +4147,28 @@ import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
#undef accumulated
}
+static PyObject *
+get_abs_name(PyThreadState *tstate, PyObject *name, PyObject *globals,
+ int level)
+{
+ if (level > 0) {
+ return resolve_name(tstate, name, globals, level);
+ }
+ if (PyUnicode_GET_LENGTH(name) == 0) {
+ _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
+ return NULL;
+ }
+ return Py_NewRef(name);
+}
+
+PyObject *
+_PyImport_GetAbsName(PyThreadState *tstate, PyObject *name,
+ PyObject *globals, int level)
+{
+ return get_abs_name(tstate, name, globals, level);
+}
+
+
PyObject *
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
PyObject *locals, PyObject *fromlist,
@@ -3895,17 +4199,9 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
goto error;
}
- if (level > 0) {
- abs_name = resolve_name(tstate, name, globals, level);
- if (abs_name == NULL)
- goto error;
- }
- else { /* level == 0 */
- if (PyUnicode_GET_LENGTH(name) == 0) {
- _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
- goto error;
- }
- abs_name = Py_NewRef(name);
+ abs_name = get_abs_name(tstate, name, globals, level);
+ if (abs_name == NULL) {
+ goto error;
}
mod = import_get_module(tstate, abs_name);
@@ -4029,6 +4325,243 @@ PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
return final_mod;
}
+static PyObject *
+get_mod_dict(PyObject *module)
+{
+ if (PyModule_Check(module)) {
+ return Py_NewRef(_PyModule_GetDict(module));
+ }
+
+ return PyObject_GetAttr(module, &_Py_ID(__dict__));
+}
+
+// ensure we have the set for the parent module name in sys.lazy_modules.
+// Returns a new reference.
+static PyObject *
+ensure_lazy_submodules(PyDictObject *lazy_modules, PyObject *parent)
+{
+ PyObject *lazy_submodules;
+ Py_BEGIN_CRITICAL_SECTION(lazy_modules);
+ int err = _PyDict_GetItemRef_Unicode_LockHeld(lazy_modules, parent,
+ &lazy_submodules);
+ if (err == 0) {
+ // value isn't present
+ lazy_submodules = PySet_New(NULL);
+ if (lazy_submodules != NULL &&
+ _PyDict_SetItem_LockHeld(lazy_modules, parent,
+ lazy_submodules) < 0) {
+ Py_CLEAR(lazy_submodules);
+ }
+ }
+ Py_END_CRITICAL_SECTION();
+ return lazy_submodules;
+}
+
+static int
+register_lazy_on_parent(PyThreadState *tstate, PyObject *name,
+ PyObject *builtins)
+{
+ int ret = -1;
+ PyObject *parent = NULL;
+ PyObject *child = NULL;
+ PyObject *parent_module = NULL;
+ PyObject *parent_dict = NULL;
+
+ PyInterpreterState *interp = tstate->interp;
+ PyObject *lazy_modules = LAZY_MODULES(interp);
+ assert(lazy_modules != NULL);
+
+ Py_INCREF(name);
+ while (true) {
+ Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
+ PyUnicode_GET_LENGTH(name), -1);
+ if (dot < 0) {
+ ret = 0;
+ goto done;
+ }
+ parent = PyUnicode_Substring(name, 0, dot);
+ // If `parent` is NULL then this has hit the end of the import, no
+ // more "parent.child" in the import name. The entire import will be
+ // resolved lazily.
+ if (parent == NULL) {
+ goto done;
+ }
+ Py_XDECREF(child);
+ child = PyUnicode_Substring(name, dot + 1, PyUnicode_GET_LENGTH(name));
+ if (child == NULL) {
+ goto done;
+ }
+
+ // Record the child as being lazily imported from the parent.
+ PyObject *lazy_submodules = ensure_lazy_submodules(
+ (PyDictObject *)lazy_modules, parent);
+ if (lazy_submodules == NULL) {
+ goto done;
+ }
+
+ if (PySet_Add(lazy_submodules, child) < 0) {
+ Py_DECREF(lazy_submodules);
+ goto done;
+ }
+ Py_DECREF(lazy_submodules);
+
+ // Add the lazy import for the child to the parent.
+ Py_XSETREF(parent_module, PyImport_GetModule(parent));
+ if (parent_module != NULL) {
+ Py_XSETREF(parent_dict, get_mod_dict(parent_module));
+ if (parent_dict == NULL) {
+ goto done;
+ }
+ if (PyDict_CheckExact(parent_dict)) {
+ int contains = PyDict_Contains(parent_dict, child);
+ if (contains < 0) {
+ goto done;
+ }
+ if (!contains) {
+ PyObject *lazy_module_attr = _PyLazyImport_New(
+ tstate->current_frame, builtins, parent, child
+ );
+ if (lazy_module_attr == NULL) {
+ goto done;
+ }
+ if (PyDict_SetItem(parent_dict, child,
+ lazy_module_attr) < 0) {
+ Py_DECREF(lazy_module_attr);
+ goto done;
+ }
+ Py_DECREF(lazy_module_attr);
+ }
+ }
+ ret = 0;
+ goto done;
+ }
+
+ Py_SETREF(name, parent);
+ parent = NULL;
+ }
+
+done:
+ Py_XDECREF(parent_dict);
+ Py_XDECREF(parent_module);
+ Py_XDECREF(child);
+ Py_XDECREF(parent);
+ Py_XDECREF(name);
+ return ret;
+}
+
+static int
+register_from_lazy_on_parent(PyThreadState *tstate, PyObject *abs_name,
+ PyObject *from, PyObject *builtins)
+{
+ PyObject *fromname = PyUnicode_FromFormat("%U.%U", abs_name, from);
+ if (fromname == NULL) {
+ return -1;
+ }
+ int res = register_lazy_on_parent(tstate, fromname, builtins);
+ Py_DECREF(fromname);
+ return res;
+}
+
+PyObject *
+_PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
+ PyObject *name, PyObject *builtins,
+ PyObject *globals, PyObject *locals,
+ PyObject *fromlist, int level)
+{
+ PyObject *abs_name = get_abs_name(tstate, name, globals, level);
+ if (abs_name == NULL) {
+ return NULL;
+ }
+
+ PyInterpreterState *interp = tstate->interp;
+ _PyInterpreterFrame *frame = _PyEval_GetFrame();
+ if (frame == NULL || frame->f_globals != frame->f_locals) {
+ Py_DECREF(abs_name);
+ PyErr_SetString(PyExc_SyntaxError,
+ "'lazy import' is only allowed at module level");
+ return NULL;
+ }
+
+ // Check if the filter disables the lazy import.
+ // We must hold a reference to the filter while calling it to prevent
+ // use-after-free if another thread replaces it via
+ // PyImport_SetLazyImportsFilter.
+ LAZY_IMPORTS_LOCK(interp);
+ PyObject *filter = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
+ LAZY_IMPORTS_UNLOCK(interp);
+
+ if (filter != NULL) {
+ PyObject *modname;
+ if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &modname) < 0) {
+ Py_DECREF(filter);
+ Py_DECREF(abs_name);
+ return NULL;
+ }
+ if (modname == NULL) {
+ assert(!PyErr_Occurred());
+ modname = Py_NewRef(Py_None);
+ }
+ PyObject *args[] = {modname, name, fromlist};
+ PyObject *res = PyObject_Vectorcall(filter, args, 3, NULL);
+
+ Py_DECREF(modname);
+ Py_DECREF(filter);
+
+ if (res == NULL) {
+ Py_DECREF(abs_name);
+ return NULL;
+ }
+
+ int is_true = PyObject_IsTrue(res);
+ Py_DECREF(res);
+
+ if (is_true < 0) {
+ Py_DECREF(abs_name);
+ return NULL;
+ }
+ if (!is_true) {
+ Py_DECREF(abs_name);
+ return PyImport_ImportModuleLevelObject(
+ name, globals, locals, fromlist, level
+ );
+ }
+ }
+
+ // here, 'filter' is either NULL or is equivalent to a borrowed reference
+ PyObject *res = _PyLazyImport_New(frame, builtins, abs_name, fromlist);
+ if (res == NULL) {
+ Py_DECREF(abs_name);
+ return NULL;
+ }
+ if (fromlist && PyUnicode_Check(fromlist)) {
+ if (register_from_lazy_on_parent(tstate, abs_name, fromlist,
+ builtins) < 0) {
+ goto error;
+ }
+ }
+ else if (fromlist && PyTuple_Check(fromlist) &&
+ PyTuple_GET_SIZE(fromlist)) {
+ for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(fromlist); i++) {
+ if (register_from_lazy_on_parent(tstate, abs_name,
+ PyTuple_GET_ITEM(fromlist, i),
+ builtins) < 0)
+ {
+ goto error;
+ }
+ }
+ }
+ else if (register_lazy_on_parent(tstate, abs_name, builtins) < 0) {
+ goto error;
+ }
+
+ Py_DECREF(abs_name);
+ return res;
+error:
+ Py_DECREF(abs_name);
+ Py_DECREF(res);
+ return NULL;
+}
+
PyObject *
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
PyObject *fromlist, int level)
@@ -4235,6 +4768,10 @@ _PyImport_ClearCore(PyInterpreterState *interp)
Py_CLEAR(MODULES_BY_INDEX(interp));
Py_CLEAR(IMPORTLIB(interp));
Py_CLEAR(IMPORT_FUNC(interp));
+ Py_CLEAR(LAZY_IMPORT_FUNC(interp));
+ Py_CLEAR(interp->imports.lazy_modules);
+ Py_CLEAR(interp->imports.lazy_importing_modules);
+ Py_CLEAR(interp->imports.lazy_imports_filter);
}
void
@@ -4370,6 +4907,58 @@ PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
return result;
}
+int
+PyImport_SetLazyImportsFilter(PyObject *filter)
+{
+ if (filter == Py_None) {
+ filter = NULL;
+ }
+ if (filter != NULL && !PyCallable_Check(filter)) {
+ PyErr_SetString(PyExc_ValueError,
+ "filter provided but is not callable");
+ return -1;
+ }
+
+ PyInterpreterState *interp = _PyInterpreterState_GET();
+ // Exchange the filter w/ the lock held. We can't use Py_XSETREF
+ // because we need to release the lock before the decref.
+ LAZY_IMPORTS_LOCK(interp);
+ PyObject *old = LAZY_IMPORTS_FILTER(interp);
+ LAZY_IMPORTS_FILTER(interp) = Py_XNewRef(filter);
+ LAZY_IMPORTS_UNLOCK(interp);
+ Py_XDECREF(old);
+ return 0;
+}
+
+/* Return a strong reference to the current lazy imports filter
+ * or NULL if none exists. This function always succeeds.
+ */
+PyObject *
+PyImport_GetLazyImportsFilter(void)
+{
+ PyInterpreterState *interp = _PyInterpreterState_GET();
+ LAZY_IMPORTS_LOCK(interp);
+ PyObject *res = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
+ LAZY_IMPORTS_UNLOCK(interp);
+ return res;
+}
+
+int
+PyImport_SetLazyImportsMode(PyImport_LazyImportsMode mode)
+{
+ PyInterpreterState *interp = _PyInterpreterState_GET();
+ FT_ATOMIC_STORE_INT_RELAXED(LAZY_IMPORTS_MODE(interp), mode);
+ return 0;
+}
+
+/* Checks if lazy imports is globally enabled or disabled. Return 1 when
+ * globally forced on, 0 when globally forced off, or -1 when not set.*/
+PyImport_LazyImportsMode
+PyImport_GetLazyImportsMode(void)
+{
+ PyInterpreterState *interp = _PyInterpreterState_GET();
+ return FT_ATOMIC_LOAD_INT_RELAXED(LAZY_IMPORTS_MODE(interp));
+}
/**************/
/* the module */
@@ -4969,6 +5558,96 @@ _imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
}
+static int
+publish_lazy_imports_on_module(PyThreadState *tstate,
+ PyObject *lazy_submodules,
+ PyObject *name,
+ PyObject *module_dict)
+{
+ PyObject *builtins = _PyEval_GetBuiltins(tstate);
+ PyObject *attr_name;
+ Py_ssize_t pos = 0;
+ Py_hash_t hash;
+
+ // Enumerate the set of lazy submodules which have been imported from the
+ // parent module.
+ while (_PySet_NextEntryRef(lazy_submodules, &pos, &attr_name, &hash)) {
+ if (_PyDict_Contains_KnownHash(module_dict, attr_name, hash)) {
+ Py_DECREF(attr_name);
+ continue;
+ }
+ // Create a new lazy module attr for the subpackage which was
+ // previously lazily imported.
+ PyObject *lazy_module_attr = _PyLazyImport_New(tstate->current_frame, builtins,
+ name, attr_name);
+ if (lazy_module_attr == NULL) {
+ Py_DECREF(attr_name);
+ return -1;
+ }
+
+ // Publish on the module that was just imported.
+ if (PyDict_SetItem(module_dict, attr_name,
+ lazy_module_attr) < 0) {
+ Py_DECREF(lazy_module_attr);
+ Py_DECREF(attr_name);
+ return -1;
+ }
+ Py_DECREF(lazy_module_attr);
+ Py_DECREF(attr_name);
+ }
+ return 0;
+}
+
+/*[clinic input]
+_imp._set_lazy_attributes
+ modobj: object
+ name: unicode
+ /
+Sets attributes to lazy submodules on the module, as side effects.
+[clinic start generated code]*/
+
+static PyObject *
+_imp__set_lazy_attributes_impl(PyObject *module, PyObject *modobj,
+ PyObject *name)
+/*[clinic end generated code: output=3369bb3242b1f043 input=38ea6f30956dd7d6]*/
+{
+ PyThreadState *tstate = _PyThreadState_GET();
+ PyObject *module_dict = NULL;
+ PyObject *ret = NULL;
+ PyObject *lazy_modules = LAZY_MODULES(tstate->interp);
+ assert(lazy_modules != NULL);
+
+ PyObject *lazy_submodules;
+ if (PyDict_GetItemRef(lazy_modules, name, &lazy_submodules) < 0) {
+ return NULL;
+ }
+ else if (lazy_submodules == NULL) {
+ Py_RETURN_NONE;
+ }
+
+ module_dict = get_mod_dict(modobj);
+ if (module_dict == NULL || !PyDict_CheckExact(module_dict)) {
+ goto done;
+ }
+
+ assert(PyAnySet_CheckExact(lazy_submodules));
+ Py_BEGIN_CRITICAL_SECTION(lazy_submodules);
+ publish_lazy_imports_on_module(tstate, lazy_submodules, name, module_dict);
+ Py_END_CRITICAL_SECTION();
+ Py_DECREF(lazy_submodules);
+
+ // once a module is imported it is removed from sys.lazy_modules
+ if (PyDict_DelItem(lazy_modules, name) < 0) {
+ goto error;
+ }
+
+done:
+ ret = Py_NewRef(Py_None);
+
+error:
+ Py_XDECREF(module_dict);
+ return ret;
+}
PyDoc_STRVAR(doc_imp,
"(Extremely) low-level import machinery bits as used by importlib.");
@@ -4993,6 +5672,7 @@ static PyMethodDef imp_methods[] = {
_IMP_EXEC_BUILTIN_METHODDEF
_IMP__FIX_CO_FILENAME_METHODDEF
_IMP_SOURCE_HASH_METHODDEF
+ _IMP__SET_LAZY_ATTRIBUTES_METHODDEF
{NULL, NULL} /* sentinel */
};
diff --git a/Python/initconfig.c b/Python/initconfig.c
index 46fd8929041..5ffee9eaf9f 100644
--- a/Python/initconfig.c
+++ b/Python/initconfig.c
@@ -111,6 +111,7 @@ static const PyConfigSpec PYCONFIG_SPEC[] = {
SPEC(base_prefix, WSTR_OPT, PUBLIC, SYS_ATTR("base_prefix")),
SPEC(bytes_warning, UINT, PUBLIC, SYS_FLAG(9)),
SPEC(cpu_count, INT, PUBLIC, NO_SYS),
+ SPEC(lazy_imports, INT, PUBLIC, NO_SYS),
SPEC(exec_prefix, WSTR_OPT, PUBLIC, SYS_ATTR("exec_prefix")),
SPEC(executable, WSTR_OPT, PUBLIC, SYS_ATTR("executable")),
SPEC(inspect, BOOL, PUBLIC, SYS_FLAG(1)),
@@ -318,6 +319,8 @@ The following implementation-specific options are available:\n\
"\
-X importtime[=2]: show how long each import takes; use -X importtime=2 to\n\
log imports of already-loaded modules; also PYTHONPROFILEIMPORTTIME\n\
+-X lazy_imports=[all|none|normal]: control global lazy imports;\n\
+ default is normal; also PYTHON_LAZY_IMPORTS\n\
-X int_max_str_digits=N: limit the size of int<->str conversions;\n\
0 disables the limit; also PYTHONINTMAXSTRDIGITS\n\
-X no_debug_ranges: don't include extra location information in code objects;\n\
@@ -432,6 +435,7 @@ static const char usage_envvars[] =
"PYTHON_PRESITE: import this module before site (-X presite)\n"
#endif
"PYTHONPROFILEIMPORTTIME: show how long each import takes (-X importtime)\n"
+"PYTHON_LAZY_IMPORTS: control global lazy imports (-X lazy_imports)\n"
"PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files\n"
" (-X pycache_prefix)\n"
"PYTHONSAFEPATH : don't prepend a potentially unsafe path to sys.path.\n"
@@ -941,6 +945,8 @@ config_check_consistency(const PyConfig *config)
assert(config->int_max_str_digits >= 0);
// cpu_count can be -1 if the user doesn't override it.
assert(config->cpu_count != 0);
+ // lazy_imports can be -1 (default), 0 (off), or 1 (on).
+ assert(config->lazy_imports >= -1 && config->lazy_imports <= 1);
// config->use_frozen_modules is initialized later
// by _PyConfig_InitImportConfig().
assert(config->thread_inherit_context >= 0);
@@ -1052,6 +1058,7 @@ _PyConfig_InitCompatConfig(PyConfig *config)
config->_is_python_build = 0;
config->code_debug_ranges = 1;
config->cpu_count = -1;
+ config->lazy_imports = -1;
#ifdef Py_GIL_DISABLED
config->thread_inherit_context = 1;
config->context_aware_warnings = 1;
@@ -2300,6 +2307,49 @@ config_init_import_time(PyConfig *config)
return _PyStatus_OK();
}
+static PyStatus
+config_init_lazy_imports(PyConfig *config)
+{
+ int lazy_imports = -1;
+
+ const char *env = config_get_env(config, "PYTHON_LAZY_IMPORTS");
+ if (env) {
+ if (strcmp(env, "all") == 0) {
+ lazy_imports = 1;
+ }
+ else if (strcmp(env, "none") == 0) {
+ lazy_imports = 0;
+ }
+ else if (strcmp(env, "normal") == 0) {
+ lazy_imports = -1;
+ }
+ else {
+ return _PyStatus_ERR("PYTHON_LAZY_IMPORTS: invalid value; "
+ "expected 'all', 'none', or 'normal'");
+ }
+ config->lazy_imports = lazy_imports;
+ }
+
+ const wchar_t *x_value = config_get_xoption_value(config, L"lazy_imports");
+ if (x_value) {
+ if (wcscmp(x_value, L"all") == 0) {
+ lazy_imports = 1;
+ }
+ else if (wcscmp(x_value, L"none") == 0) {
+ lazy_imports = 0;
+ }
+ else if (wcscmp(x_value, L"normal") == 0) {
+ lazy_imports = -1;
+ }
+ else {
+ return _PyStatus_ERR("-X lazy_imports: invalid value; "
+ "expected 'all', 'none', or 'normal'");
+ }
+ config->lazy_imports = lazy_imports;
+ }
+ return _PyStatus_OK();
+}
+
static PyStatus
config_read_complex_options(PyConfig *config)
{
@@ -2323,6 +2373,13 @@ config_read_complex_options(PyConfig *config)
}
}
+ if (config->lazy_imports < 0) {
+ status = config_init_lazy_imports(config);
+ if (_PyStatus_EXCEPTION(status)) {
+ return status;
+ }
+ }
+
if (config->tracemalloc < 0) {
status = config_init_tracemalloc(config);
if (_PyStatus_EXCEPTION(status)) {
@@ -2712,6 +2769,9 @@ config_read(PyConfig *config, int compute_path_config)
if (config->tracemalloc < 0) {
config->tracemalloc = 0;
}
+ if (config->lazy_imports < 0) {
+ config->lazy_imports = -1; // Default is auto/unset
+ }
if (config->perf_profiling < 0) {
config->perf_profiling = 0;
}
diff --git a/Python/jit.c b/Python/jit.c
index 7e47b70f1f4..0791d042710 100644
--- a/Python/jit.c
+++ b/Python/jit.c
@@ -11,9 +11,11 @@
#include "pycore_floatobject.h"
#include "pycore_frame.h"
#include "pycore_function.h"
+#include "pycore_import.h"
#include "pycore_interpframe.h"
#include "pycore_interpolation.h"
#include "pycore_intrinsics.h"
+#include "pycore_lazyimportobject.h"
#include "pycore_list.h"
#include "pycore_long.h"
#include "pycore_mmap.h"
diff --git a/Python/pylifecycle.c b/Python/pylifecycle.c
index bb51f8d191c..7dfeb5b847b 100644
--- a/Python/pylifecycle.c
+++ b/Python/pylifecycle.c
@@ -15,6 +15,7 @@
#include "pycore_initconfig.h" // _PyStatus_OK()
#include "pycore_interpolation.h" // _PyInterpolation_InitTypes()
#include "pycore_long.h" // _PyLong_InitTypes()
+#include "pycore_moduleobject.h" // _PyModule_InitModuleDictWatcher()
#include "pycore_object.h" // _PyDebug_PrintTotalRefs()
#include "pycore_obmalloc.h" // _PyMem_init_obmalloc()
#include "pycore_optimizer.h" // _Py_Executors_InvalidateAll
@@ -632,6 +633,11 @@ pycore_create_interpreter(_PyRuntimeState *runtime,
_PyInterpreterState_SetWhence(interp, _PyInterpreterState_WHENCE_RUNTIME);
interp->_ready = 1;
+ /* Initialize the module dict watcher early, before any modules are created */
+ if (_PyModule_InitModuleDictWatcher(interp) != 0) {
+ return _PyStatus_ERR("failed to initialize module dict watcher");
+ }
+
status = _PyConfig_Copy(&interp->config, src_config);
if (_PyStatus_EXCEPTION(status)) {
return status;
@@ -1335,6 +1341,22 @@ init_interp_main(PyThreadState *tstate)
}
}
+ // Initialize lazy imports based on configuration. Do this after site
+ // module is imported to avoid circular imports during startup.
+ if (config->lazy_imports != -1) {
+ PyImport_LazyImportsMode lazy_mode;
+ if (config->lazy_imports == 1) {
+ lazy_mode = PyImport_LAZY_ALL;
+ }
+ else {
+ lazy_mode = PyImport_LAZY_NONE;
+ }
+ if (PyImport_SetLazyImportsMode(lazy_mode) < 0) {
+ return _PyStatus_ERR("failed to set lazy imports mode");
+ }
+ }
+ // If config->lazy_imports == -1, use the default mode, no change needed.
+
if (is_main_interp) {
#ifndef MS_WINDOWS
emit_stderr_warning_for_legacy_locale(interp->runtime);
@@ -1802,6 +1824,9 @@ finalize_modules(PyThreadState *tstate)
// initialization API)
_PyImport_ClearModulesByIndex(interp);
+ // Clear the dict of lazily loaded module nname to submodule names
+ _PyImport_ClearLazyModules(interp);
+
// Clear and delete the modules directory. Actual modules will
// still be there only if imported during the execution of some
// destructor.
@@ -2449,6 +2474,11 @@ new_interpreter(PyThreadState **tstate_p,
_PyInterpreterState_SetWhence(interp, whence);
interp->_ready = 1;
+ /* Initialize the module dict watcher early, before any modules are created */
+ if (_PyModule_InitModuleDictWatcher(interp) != 0) {
+ goto error;
+ }
+
/* From this point until the init_interp_create_gil() call,
we must not do anything that requires that the GIL be held
(or otherwise exist). That applies whether or not the new
diff --git a/Python/specialize.c b/Python/specialize.c
index 21e0eb802dd..7c02e929d47 100644
--- a/Python/specialize.c
+++ b/Python/specialize.c
@@ -8,6 +8,7 @@
#include "pycore_dict.h" // DICT_KEYS_UNICODE
#include "pycore_function.h" // _PyFunction_GetVersionForCurrentState()
#include "pycore_interpframe.h" // FRAME_SPECIALS_SIZE
+#include "pycore_lazyimportobject.h" // PyLazyImport_CheckExact
#include "pycore_list.h" // _PyListIterObject
#include "pycore_long.h" // _PyLong_IsNonNegativeCompact()
#include "pycore_moduleobject.h"
@@ -129,6 +130,7 @@ _PyCode_Quicken(_Py_CODEUNIT *instructions, Py_ssize_t size, int enable_counters
#define SPEC_FAIL_ATTR_BUILTIN_CLASS_METHOD 22
#define SPEC_FAIL_ATTR_CLASS_METHOD_OBJ 23
#define SPEC_FAIL_ATTR_OBJECT_SLOT 24
+#define SPEC_FAIL_ATTR_MODULE_LAZY_VALUE 25
#define SPEC_FAIL_ATTR_INSTANCE_ATTRIBUTE 26
#define SPEC_FAIL_ATTR_METACLASS_ATTRIBUTE 27
@@ -383,6 +385,10 @@ specialize_module_load_attr_lock_held(PyDictObject *dict, _Py_CODEUNIT *instr, P
}
PyObject *value;
Py_ssize_t index = _PyDict_LookupIndexAndValue(dict, name, &value);
+ if (value != NULL && PyLazyImport_CheckExact(value)) {
+ SPECIALIZATION_FAIL(LOAD_ATTR, SPEC_FAIL_ATTR_MODULE_LAZY_VALUE);
+ return -1;
+ }
assert(index != DKIX_ERROR);
if (index != (uint16_t)index) {
SPECIALIZATION_FAIL(LOAD_ATTR,
@@ -1307,16 +1313,17 @@ specialize_load_global_lock_held(
SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_LOAD_GLOBAL_NON_STRING_OR_SPLIT);
goto fail;
}
-#ifdef Py_GIL_DISABLED
PyObject *value;
Py_ssize_t index = _PyDict_LookupIndexAndValue((PyDictObject *)globals, name, &value);
-#else
- Py_ssize_t index = _PyDictKeys_StringLookup(globals_keys, name);
-#endif
if (index == DKIX_ERROR) {
SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_EXPECTED_ERROR);
goto fail;
}
+ if (value != NULL && PyLazyImport_CheckExact(value)) {
+ SPECIALIZATION_FAIL(LOAD_GLOBAL, SPEC_FAIL_ATTR_MODULE_LAZY_VALUE);
+ Py_DECREF(value);
+ goto fail;
+ }
PyInterpreterState *interp = _PyInterpreterState_GET();
if (index != DKIX_EMPTY) {
if (index != (uint16_t)index) {
diff --git a/Python/symtable.c b/Python/symtable.c
index 29ac8f6880c..beb6df88d09 100644
--- a/Python/symtable.c
+++ b/Python/symtable.c
@@ -141,6 +141,7 @@ ste_new(struct symtable *st, identifier name, _Py_block_ty block,
ste->ste_needs_classdict = 0;
ste->ste_has_conditional_annotations = 0;
ste->ste_in_conditional_block = 0;
+ ste->ste_in_try_block = 0;
ste->ste_in_unevaluated_annotation = 0;
ste->ste_annotation_block = NULL;
@@ -1747,6 +1748,13 @@ symtable_enter_type_param_block(struct symtable *st, identifier name,
#define LEAVE_CONDITIONAL_BLOCK(ST) \
(ST)->st_cur->ste_in_conditional_block = in_conditional_block;
+#define ENTER_TRY_BLOCK(ST) \
+ int in_try_block = (ST)->st_cur->ste_in_try_block; \
+ (ST)->st_cur->ste_in_try_block = 1;
+
+#define LEAVE_TRY_BLOCK(ST) \
+ (ST)->st_cur->ste_in_try_block = in_try_block;
+
#define ENTER_RECURSIVE() \
if (Py_EnterRecursiveCall(" during compilation")) { \
return 0; \
@@ -1808,6 +1816,38 @@ check_import_from(struct symtable *st, stmt_ty s)
return 1;
}
+static int
+check_lazy_import_context(struct symtable *st, stmt_ty s,
+ const char* import_type)
+{
+ // Check if inside try/except block.
+ if (st->st_cur->ste_in_try_block) {
+ PyErr_Format(PyExc_SyntaxError,
+ "lazy %s not allowed inside try/except blocks",
+ import_type);
+ SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
+ return 0;
+ }
+
+ // Check if inside function scope.
+ if (st->st_cur->ste_type == FunctionBlock) {
+ PyErr_Format(PyExc_SyntaxError,
+ "lazy %s not allowed inside functions", import_type);
+ SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
+ return 0;
+ }
+
+ // Check if inside class scope.
+ if (st->st_cur->ste_type == ClassBlock) {
+ PyErr_Format(PyExc_SyntaxError,
+ "lazy %s not allowed inside classes", import_type);
+ SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
+ return 0;
+ }
+
+ return 1;
+}
+
static bool
allows_top_level_await(struct symtable *st)
{
@@ -2076,19 +2116,23 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
break;
case Try_kind: {
ENTER_CONDITIONAL_BLOCK(st);
+ ENTER_TRY_BLOCK(st);
VISIT_SEQ(st, stmt, s->v.Try.body);
VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
VISIT_SEQ(st, stmt, s->v.Try.orelse);
VISIT_SEQ(st, stmt, s->v.Try.finalbody);
+ LEAVE_TRY_BLOCK(st);
LEAVE_CONDITIONAL_BLOCK(st);
break;
}
case TryStar_kind: {
ENTER_CONDITIONAL_BLOCK(st);
+ ENTER_TRY_BLOCK(st);
VISIT_SEQ(st, stmt, s->v.TryStar.body);
VISIT_SEQ(st, excepthandler, s->v.TryStar.handlers);
VISIT_SEQ(st, stmt, s->v.TryStar.orelse);
VISIT_SEQ(st, stmt, s->v.TryStar.finalbody);
+ LEAVE_TRY_BLOCK(st);
LEAVE_CONDITIONAL_BLOCK(st);
break;
}
@@ -2098,9 +2142,33 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
VISIT(st, expr, s->v.Assert.msg);
break;
case Import_kind:
+ if (s->v.Import.is_lazy) {
+ if (!check_lazy_import_context(st, s, "import")) {
+ return 0;
+ }
+ }
VISIT_SEQ(st, alias, s->v.Import.names);
break;
case ImportFrom_kind:
+ if (s->v.ImportFrom.is_lazy) {
+ if (!check_lazy_import_context(st, s, "from ... import")) {
+ return 0;
+ }
+
+ // Check for import *
+ for (Py_ssize_t i = 0; i < asdl_seq_LEN(s->v.ImportFrom.names);
+ i++) {
+ alias_ty alias = (alias_ty)asdl_seq_GET(
+ s->v.ImportFrom.names, i);
+ if (alias->name &&
+ _PyUnicode_EqualToASCIIString(alias->name, "*")) {
+ PyErr_SetString(PyExc_SyntaxError,
+ "lazy from ... import * is not allowed");
+ SET_ERROR_LOCATION(st->st_filename, LOCATION(s));
+ return 0;
+ }
+ }
+ }
VISIT_SEQ(st, alias, s->v.ImportFrom.names);
if (!check_import_from(st, s)) {
return 0;
diff --git a/Python/sysmodule.c b/Python/sysmodule.c
index 61dbe5edb87..28b2108940c 100644
--- a/Python/sysmodule.c
+++ b/Python/sysmodule.c
@@ -2785,6 +2785,128 @@ PyAPI_FUNC(int) PyUnstable_CopyPerfMapFile(const char* parent_filename) {
return 0;
}
+/*[clinic input]
+sys.set_lazy_imports_filter
+
+ filter: object
+
+Set the lazy imports filter callback.
+
+The filter is a callable which disables lazy imports when they
+would otherwise be enabled. Returns True if the import is still enabled
+or False to disable it. The callable is called with:
+
+(importing_module_name, imported_module_name, [fromlist])
+
+Pass None to clear the filter.
+[clinic start generated code]*/
+
+static PyObject *
+sys_set_lazy_imports_filter_impl(PyObject *module, PyObject *filter)
+/*[clinic end generated code: output=10251d49469c278c input=2eb48786bdd4ee42]*/
+{
+ if (PyImport_SetLazyImportsFilter(filter) < 0) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
+}
+
+/*[clinic input]
+sys.get_lazy_imports_filter
+
+Get the current lazy imports filter callback.
+
+Returns the filter callable or None if no filter is set.
+[clinic start generated code]*/
+
+static PyObject *
+sys_get_lazy_imports_filter_impl(PyObject *module)
+/*[clinic end generated code: output=3bf73022892165af input=cf1e07cb8e203c94]*/
+{
+ PyObject *filter = PyImport_GetLazyImportsFilter();
+ if (filter == NULL) {
+ assert(!PyErr_Occurred());
+ Py_RETURN_NONE;
+ }
+ return filter;
+}
+
+/*[clinic input]
+sys.set_lazy_imports
+
+ mode: object
+
+Sets the global lazy imports mode.
+
+The mode parameter must be one of the following strings:
+- "all": All top-level imports become potentially lazy
+- "none": All lazy imports are suppressed (even explicitly marked ones)
+- "normal": Only explicitly marked imports (with 'lazy' keyword) are lazy
+
+In addition to the mode, lazy imports can be controlled via the filter
+provided to sys.set_lazy_imports_filter
+
+[clinic start generated code]*/
+
+static PyObject *
+sys_set_lazy_imports_impl(PyObject *module, PyObject *mode)
+/*[clinic end generated code: output=1ff34ba6c4feaf73 input=f04e70d8bf9fe4f6]*/
+{
+ PyImport_LazyImportsMode lazy_mode;
+ if (!PyUnicode_Check(mode)) {
+ PyErr_SetString(PyExc_TypeError,
+ "mode must be a string: 'normal', 'all', or 'none'");
+ return NULL;
+ }
+ if (PyUnicode_CompareWithASCIIString(mode, "normal") == 0) {
+ lazy_mode = PyImport_LAZY_NORMAL;
+ }
+ else if (PyUnicode_CompareWithASCIIString(mode, "all") == 0) {
+ lazy_mode = PyImport_LAZY_ALL;
+ }
+ else if (PyUnicode_CompareWithASCIIString(mode, "none") == 0) {
+ lazy_mode = PyImport_LAZY_NONE;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "mode must be 'normal', 'all', or 'none'");
+ return NULL;
+ }
+
+ if (PyImport_SetLazyImportsMode(lazy_mode)) {
+ return NULL;
+ }
+ Py_RETURN_NONE;
+}
+
+/*[clinic input]
+sys.get_lazy_imports
+
+Gets the global lazy imports mode.
+
+Returns "all" if all top level imports are potentially lazy.
+Returns "none" if all explicitly marked lazy imports are suppressed.
+Returns "normal" if only explicitly marked imports are lazy.
+
+[clinic start generated code]*/
+
+static PyObject *
+sys_get_lazy_imports_impl(PyObject *module)
+/*[clinic end generated code: output=4147dec48c51ae99 input=8cb574f1e4e3003c]*/
+{
+ switch (PyImport_GetLazyImportsMode()) {
+ case PyImport_LAZY_NORMAL:
+ return PyUnicode_FromString("normal");
+ case PyImport_LAZY_ALL:
+ return PyUnicode_FromString("all");
+ case PyImport_LAZY_NONE:
+ return PyUnicode_FromString("none");
+ default:
+ PyErr_SetString(PyExc_RuntimeError, "unknown lazy imports mode");
+ return NULL;
+ }
+}
static PyMethodDef sys_methods[] = {
/* Might as well keep this in alphabetic order */
@@ -2850,6 +2972,10 @@ static PyMethodDef sys_methods[] = {
SYS_UNRAISABLEHOOK_METHODDEF
SYS_GET_INT_MAX_STR_DIGITS_METHODDEF
SYS_SET_INT_MAX_STR_DIGITS_METHODDEF
+ SYS_GET_LAZY_IMPORTS_METHODDEF
+ SYS_SET_LAZY_IMPORTS_METHODDEF
+ SYS_GET_LAZY_IMPORTS_FILTER_METHODDEF
+ SYS_SET_LAZY_IMPORTS_FILTER_METHODDEF
SYS__BASEREPL_METHODDEF
#ifdef Py_STATS
SYS__STATS_ON_METHODDEF
@@ -3374,6 +3500,7 @@ static PyStructSequence_Field flags_fields[] = {
{"gil", "-X gil"},
{"thread_inherit_context", "-X thread_inherit_context"},
{"context_aware_warnings", "-X context_aware_warnings"},
+ {"lazy_imports", "-X lazy_imports"},
{0}
};
@@ -3383,7 +3510,7 @@ static PyStructSequence_Desc flags_desc = {
"sys.flags", /* name */
flags__doc__, /* doc */
flags_fields, /* fields */
- 18
+ 19
};
static void
@@ -3476,6 +3603,7 @@ set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
#endif
SetFlag(config->thread_inherit_context);
SetFlag(config->context_aware_warnings);
+ SetFlag(config->lazy_imports);
#undef SetFlagObj
#undef SetFlag
return 0;
@@ -4203,6 +4331,15 @@ _PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
goto error;
}
+ PyObject *lazy_modules = _PyImport_InitLazyModules(interp); // borrowed reference
+ if (lazy_modules == NULL) {
+ goto error;
+ }
+
+ if (PyDict_SetItemString(sysdict, "lazy_modules", lazy_modules) < 0) {
+ goto error;
+ }
+
PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
if (_PyStatus_EXCEPTION(status)) {
return status;
diff --git a/Tools/c-analyzer/cpython/globals-to-fix.tsv b/Tools/c-analyzer/cpython/globals-to-fix.tsv
index 301784f773d..d645d2b6150 100644
--- a/Tools/c-analyzer/cpython/globals-to-fix.tsv
+++ b/Tools/c-analyzer/cpython/globals-to-fix.tsv
@@ -59,6 +59,7 @@ Objects/interpolationobject.c - _PyInterpolation_Type -
Objects/iterobject.c - PyCallIter_Type -
Objects/iterobject.c - PySeqIter_Type -
Objects/iterobject.c - _PyAnextAwaitable_Type -
+Objects/lazyimportobject.c - PyLazyImport_Type -
Objects/listobject.c - PyListIter_Type -
Objects/listobject.c - PyListRevIter_Type -
Objects/listobject.c - PyList_Type -
@@ -176,6 +177,7 @@ Objects/exceptions.c - _PyExc_StopIteration -
Objects/exceptions.c - _PyExc_GeneratorExit -
Objects/exceptions.c - _PyExc_SystemExit -
Objects/exceptions.c - _PyExc_KeyboardInterrupt -
+Objects/exceptions.c - _PyExc_ImportCycleError -
Objects/exceptions.c - _PyExc_ImportError -
Objects/exceptions.c - _PyExc_ModuleNotFoundError -
Objects/exceptions.c - _PyExc_OSError -
@@ -242,6 +244,7 @@ Objects/exceptions.c - PyExc_StopIteration -
Objects/exceptions.c - PyExc_GeneratorExit -
Objects/exceptions.c - PyExc_SystemExit -
Objects/exceptions.c - PyExc_KeyboardInterrupt -
+Objects/exceptions.c - PyExc_ImportCycleError -
Objects/exceptions.c - PyExc_ImportError -
Objects/exceptions.c - PyExc_ModuleNotFoundError -
Objects/exceptions.c - PyExc_OSError -
diff --git a/Tools/jit/template.c b/Tools/jit/template.c
index 3537c74a820..afdd9b77e7c 100644
--- a/Tools/jit/template.c
+++ b/Tools/jit/template.c
@@ -12,9 +12,11 @@
#include "pycore_frame.h"
#include "pycore_function.h"
#include "pycore_genobject.h"
+#include "pycore_import.h"
#include "pycore_interpframe.h"
#include "pycore_interpolation.h"
#include "pycore_intrinsics.h"
+#include "pycore_lazyimportobject.h"
#include "pycore_jit.h"
#include "pycore_list.h"
#include "pycore_long.h"
|