File size: 102,454 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 | diff --git a/Lib/test/.ruff.toml b/Lib/test/.ruff.toml
index 7b46139f786..b5be4c3afaf 100644
--- a/Lib/test/.ruff.toml
+++ b/Lib/test/.ruff.toml
@@ -14,6 +14,9 @@ extend-exclude = [
# New grammar constructions may not yet be recognized by Ruff,
# and tests re-use the same names as only the grammar is being checked.
"test_grammar.py",
+ # Lazy import syntax (PEP 810) is not yet supported by Ruff
+ "test_import/data/lazy_imports/*.py",
+ "test_import/data/lazy_imports/**/*.py",
]
[lint]
diff --git a/Lib/test/exception_hierarchy.txt b/Lib/test/exception_hierarchy.txt
index f2649aa2d41..98a5e950602 100644
--- a/Lib/test/exception_hierarchy.txt
+++ b/Lib/test/exception_hierarchy.txt
@@ -14,6 +14,7 @@ BaseException
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
+ │ └── ImportCycleError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
diff --git a/Lib/test/test_ast/data/ast_repr.txt b/Lib/test/test_ast/data/ast_repr.txt
index 1c1985519cd..cc6accd766b 100644
--- a/Lib/test/test_ast/data/ast_repr.txt
+++ b/Lib/test/test_ast/data/ast_repr.txt
@@ -69,10 +69,14 @@ Module(body=[Try(body=[Pass()], handlers=[ExceptHandler(type=Name(...), name='ex
Module(body=[TryStar(body=[Pass()], handlers=[ExceptHandler(type=Name(...), name='exc', body=[Pass(...)])], orelse=[Pass()], finalbody=[Pass()])], type_ignores=[])
Module(body=[Assert(test=Name(id='v', ctx=Load(...)), msg=None)], type_ignores=[])
Module(body=[Assert(test=Name(id='v', ctx=Load(...)), msg=Constant(value='message', kind=None))], type_ignores=[])
-Module(body=[Import(names=[alias(name='sys', asname=None)])], type_ignores=[])
-Module(body=[Import(names=[alias(name='foo', asname='bar')])], type_ignores=[])
-Module(body=[ImportFrom(module='sys', names=[alias(name='x', asname='y')], level=0)], type_ignores=[])
-Module(body=[ImportFrom(module='sys', names=[alias(name='v', asname=None)], level=0)], type_ignores=[])
+Module(body=[Import(names=[alias(name='sys', asname=None)], is_lazy=0)], type_ignores=[])
+Module(body=[Import(names=[alias(name='foo', asname='bar')], is_lazy=0)], type_ignores=[])
+Module(body=[ImportFrom(module='sys', names=[alias(name='x', asname='y')], level=0, is_lazy=0)], type_ignores=[])
+Module(body=[ImportFrom(module='sys', names=[alias(name='v', asname=None)], level=0, is_lazy=0)], type_ignores=[])
+Module(body=[Import(names=[alias(name='sys', asname=None)], is_lazy=1)], type_ignores=[])
+Module(body=[Import(names=[alias(name='foo', asname='bar')], is_lazy=1)], type_ignores=[])
+Module(body=[ImportFrom(module='sys', names=[alias(name='x', asname='y')], level=0, is_lazy=1)], type_ignores=[])
+Module(body=[ImportFrom(module='sys', names=[alias(name='v', asname=None)], level=0, is_lazy=1)], type_ignores=[])
Module(body=[Global(names=['v'])], type_ignores=[])
Module(body=[Expr(value=Constant(value=1, kind=None))], type_ignores=[])
Module(body=[Pass()], type_ignores=[])
diff --git a/Lib/test/test_ast/snippets.py b/Lib/test/test_ast/snippets.py
index b76f98901d2..a565ed10f8b 100644
--- a/Lib/test/test_ast/snippets.py
+++ b/Lib/test/test_ast/snippets.py
@@ -118,6 +118,12 @@
# ImportFrom
"from sys import x as y",
"from sys import v",
+ # Lazy Import
+ "lazy import sys",
+ "lazy import foo as bar",
+ # Lazy ImportFrom
+ "lazy from sys import x as y",
+ "lazy from sys import v",
# Global
"global v",
# Expr
@@ -460,10 +466,14 @@ def main():
('Module', [('TryStar', (1, 0, 7, 6), [('Pass', (2, 2, 2, 6))], [('ExceptHandler', (3, 0, 4, 6), ('Name', (3, 8, 3, 17), 'Exception', ('Load',)), 'exc', [('Pass', (4, 2, 4, 6))])], [('Pass', (5, 7, 5, 11))], [('Pass', (7, 2, 7, 6))])], []),
('Module', [('Assert', (1, 0, 1, 8), ('Name', (1, 7, 1, 8), 'v', ('Load',)), None)], []),
('Module', [('Assert', (1, 0, 1, 19), ('Name', (1, 7, 1, 8), 'v', ('Load',)), ('Constant', (1, 10, 1, 19), 'message', None))], []),
-('Module', [('Import', (1, 0, 1, 10), [('alias', (1, 7, 1, 10), 'sys', None)])], []),
-('Module', [('Import', (1, 0, 1, 17), [('alias', (1, 7, 1, 17), 'foo', 'bar')])], []),
-('Module', [('ImportFrom', (1, 0, 1, 22), 'sys', [('alias', (1, 16, 1, 22), 'x', 'y')], 0)], []),
-('Module', [('ImportFrom', (1, 0, 1, 17), 'sys', [('alias', (1, 16, 1, 17), 'v', None)], 0)], []),
+('Module', [('Import', (1, 0, 1, 10), [('alias', (1, 7, 1, 10), 'sys', None)], 0)], []),
+('Module', [('Import', (1, 0, 1, 17), [('alias', (1, 7, 1, 17), 'foo', 'bar')], 0)], []),
+('Module', [('ImportFrom', (1, 0, 1, 22), 'sys', [('alias', (1, 16, 1, 22), 'x', 'y')], 0, 0)], []),
+('Module', [('ImportFrom', (1, 0, 1, 17), 'sys', [('alias', (1, 16, 1, 17), 'v', None)], 0, 0)], []),
+('Module', [('Import', (1, 0, 1, 15), [('alias', (1, 12, 1, 15), 'sys', None)], 1)], []),
+('Module', [('Import', (1, 0, 1, 22), [('alias', (1, 12, 1, 22), 'foo', 'bar')], 1)], []),
+('Module', [('ImportFrom', (1, 0, 1, 27), 'sys', [('alias', (1, 21, 1, 27), 'x', 'y')], 0, 1)], []),
+('Module', [('ImportFrom', (1, 0, 1, 22), 'sys', [('alias', (1, 21, 1, 22), 'v', None)], 0, 1)], []),
('Module', [('Global', (1, 0, 1, 8), ['v'])], []),
('Module', [('Expr', (1, 0, 1, 1), ('Constant', (1, 0, 1, 1), 1, None))], []),
('Module', [('Pass', (1, 0, 1, 4))], []),
diff --git a/Lib/test/test_ast/test_ast.py b/Lib/test/test_ast/test_ast.py
index c5f42cb7888..f29f98beb2d 100644
--- a/Lib/test/test_ast/test_ast.py
+++ b/Lib/test/test_ast/test_ast.py
@@ -1701,8 +1701,8 @@ def check_text(code, empty, full, **kwargs):
check_text(
"import _ast as ast; from module import sub",
- empty="Module(body=[Import(names=[alias(name='_ast', asname='ast')]), ImportFrom(module='module', names=[alias(name='sub')], level=0)])",
- full="Module(body=[Import(names=[alias(name='_ast', asname='ast')]), ImportFrom(module='module', names=[alias(name='sub')], level=0)], type_ignores=[])",
+ empty="Module(body=[Import(names=[alias(name='_ast', asname='ast')], is_lazy=0), ImportFrom(module='module', names=[alias(name='sub')], level=0, is_lazy=0)])",
+ full="Module(body=[Import(names=[alias(name='_ast', asname='ast')], is_lazy=0), ImportFrom(module='module', names=[alias(name='sub')], level=0, is_lazy=0)], type_ignores=[])",
)
def test_copy_location(self):
diff --git a/Lib/test/test_capi/test_config.py b/Lib/test/test_capi/test_config.py
index b04d0923926..f10ad50d3be 100644
--- a/Lib/test/test_capi/test_config.py
+++ b/Lib/test/test_capi/test_config.py
@@ -62,6 +62,7 @@ def test_config_get(self):
("int_max_str_digits", int, None),
("interactive", bool, None),
("isolated", bool, None),
+ ("lazy_imports", int, None),
("malloc_stats", bool, None),
("pymalloc_hugepages", bool, None),
("module_search_paths", list[str], "path"),
diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py
index 8529afaa3f5..cefd64ddfe8 100644
--- a/Lib/test/test_dis.py
+++ b/Lib/test/test_dis.py
@@ -292,7 +292,7 @@ def wrap_func_w_kwargs():
1 LOAD_SMALL_INT 0
LOAD_CONST 1 (('*',))
- IMPORT_NAME 0 (math)
+ IMPORT_NAME 2 (math + eager)
CALL_INTRINSIC_1 2 (INTRINSIC_IMPORT_STAR)
POP_TOP
LOAD_CONST 2 (None)
diff --git a/Lib/test/test_embed.py b/Lib/test/test_embed.py
index 29b1249b10d..35246d7c484 100644
--- a/Lib/test/test_embed.py
+++ b/Lib/test/test_embed.py
@@ -635,6 +635,7 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase):
'tracemalloc': 0,
'perf_profiling': 0,
'import_time': 0,
+ 'lazy_imports': -1,
'thread_inherit_context': DEFAULT_THREAD_INHERIT_CONTEXT,
'context_aware_warnings': DEFAULT_CONTEXT_AWARE_WARNINGS,
'code_debug_ranges': True,
diff --git a/Lib/test/test_import/data/lazy_imports/basic2.py b/Lib/test/test_import/data/lazy_imports/basic2.py
new file mode 100644
index 00000000000..f93ec89d5ab
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic2.py
@@ -0,0 +1,4 @@
+def f():
+ pass
+
+x = 42
diff --git a/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode.py b/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode.py
new file mode 100644
index 00000000000..5076fa4894e
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode.py
@@ -0,0 +1,2 @@
+__lazy_modules__ = ['test.test_import.data.lazy_imports.basic2']
+import test.test_import.data.lazy_imports.basic2
diff --git a/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode_relative.py b/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode_relative.py
new file mode 100644
index 00000000000..e37759348f3
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode_relative.py
@@ -0,0 +1,2 @@
+__lazy_modules__ = ['test.test_import.data.lazy_imports.basic2']
+lazy from .basic2 import f
diff --git a/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode_used.py b/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode_used.py
new file mode 100644
index 00000000000..64f36645f68
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_compatibility_mode_used.py
@@ -0,0 +1,3 @@
+__lazy_modules__ = ['test.test_import.data.lazy_imports.basic2']
+import test.test_import.data.lazy_imports.basic2
+test.test_import.data.lazy_imports.basic2.f()
diff --git a/Lib/test/test_import/data/lazy_imports/basic_dir.py b/Lib/test/test_import/data/lazy_imports/basic_dir.py
new file mode 100644
index 00000000000..ca9e29d3d99
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_dir.py
@@ -0,0 +1,2 @@
+lazy import test.test_import.data.lazy_imports.basic2
+x = dir()
diff --git a/Lib/test/test_import/data/lazy_imports/basic_from_unused.py b/Lib/test/test_import/data/lazy_imports/basic_from_unused.py
new file mode 100644
index 00000000000..686caa86a6c
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_from_unused.py
@@ -0,0 +1 @@
+lazy from test.test_import.data.lazy_imports import basic2
diff --git a/Lib/test/test_import/data/lazy_imports/basic_unused.py b/Lib/test/test_import/data/lazy_imports/basic_unused.py
new file mode 100644
index 00000000000..bf8ae4613e4
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_unused.py
@@ -0,0 +1 @@
+lazy import test.test_import.data.lazy_imports.basic2
diff --git a/Lib/test/test_import/data/lazy_imports/basic_used.py b/Lib/test/test_import/data/lazy_imports/basic_used.py
new file mode 100644
index 00000000000..84e354750f8
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/basic_used.py
@@ -0,0 +1,3 @@
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
+
+basic2.f()
diff --git a/Lib/test/test_import/data/lazy_imports/broken_attr_module.py b/Lib/test/test_import/data/lazy_imports/broken_attr_module.py
new file mode 100644
index 00000000000..a60bca2bad0
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/broken_attr_module.py
@@ -0,0 +1,3 @@
+# Module that exists but doesn't have expected attributes
+x = 42
+# No 'nonexistent_attr' here
diff --git a/Lib/test/test_import/data/lazy_imports/broken_module.py b/Lib/test/test_import/data/lazy_imports/broken_module.py
new file mode 100644
index 00000000000..b49d4a4a15f
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/broken_module.py
@@ -0,0 +1,2 @@
+# Module that raises an error during import
+raise ValueError("This module always fails to import")
diff --git a/Lib/test/test_import/data/lazy_imports/compatibility_mode_func.py b/Lib/test/test_import/data/lazy_imports/compatibility_mode_func.py
new file mode 100644
index 00000000000..307338a0886
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/compatibility_mode_func.py
@@ -0,0 +1,5 @@
+__lazy_modules__ = ['test.test_import.data.lazy_imports.basic2']
+def f():
+ import test.test_import.data.lazy_imports.basic2
+
+f()
diff --git a/Lib/test/test_import/data/lazy_imports/compatibility_mode_try_except.py b/Lib/test/test_import/data/lazy_imports/compatibility_mode_try_except.py
new file mode 100644
index 00000000000..6d54e69a9a4
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/compatibility_mode_try_except.py
@@ -0,0 +1,5 @@
+__lazy_modules__ = ['test.test_import.data.lazy_imports.basic2']
+try:
+ import test.test_import.data.lazy_imports.basic2
+except:
+ pass
diff --git a/Lib/test/test_import/data/lazy_imports/dunder_lazy_import.py b/Lib/test/test_import/data/lazy_imports/dunder_lazy_import.py
new file mode 100644
index 00000000000..1a8a19c3c90
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/dunder_lazy_import.py
@@ -0,0 +1 @@
+basic = __lazy_import__('test.test_import.data.lazy_imports.basic2')
diff --git a/Lib/test/test_import/data/lazy_imports/dunder_lazy_import_builtins.py b/Lib/test/test_import/data/lazy_imports/dunder_lazy_import_builtins.py
new file mode 100644
index 00000000000..f1fed0fc317
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/dunder_lazy_import_builtins.py
@@ -0,0 +1,14 @@
+import sys
+
+def myimport(*args):
+ return sys.modules[__name__]
+
+
+new_globals = dict(globals())
+new_globals["__builtins__"] = {
+ "__import__": myimport,
+}
+basic2 = 42
+basic = __lazy_import__("test.test_import.data.lazy_imports.basic2",
+ globals=new_globals)
+basic
diff --git a/Lib/test/test_import/data/lazy_imports/dunder_lazy_import_used.py b/Lib/test/test_import/data/lazy_imports/dunder_lazy_import_used.py
new file mode 100644
index 00000000000..2432ca17b16
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/dunder_lazy_import_used.py
@@ -0,0 +1,3 @@
+basic = __lazy_import__('test.test_import.data.lazy_imports',
+ fromlist=("basic2", ))
+basic
diff --git a/Lib/test/test_import/data/lazy_imports/eager_import_func.py b/Lib/test/test_import/data/lazy_imports/eager_import_func.py
new file mode 100644
index 00000000000..89e643ac183
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/eager_import_func.py
@@ -0,0 +1,3 @@
+def f():
+ import test.test_import.data.lazy_imports.basic2 as basic2
+ return basic2
diff --git a/Lib/test/test_import/data/lazy_imports/global_filter.py b/Lib/test/test_import/data/lazy_imports/global_filter.py
new file mode 100644
index 00000000000..72cb5f2ef5a
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/global_filter.py
@@ -0,0 +1,10 @@
+import sys
+
+def filter(module_name, imported_name, from_list):
+ assert module_name == __name__
+ assert imported_name == "test.test_import.data.lazy_imports.basic2"
+ return False
+
+sys.set_lazy_imports_filter(filter)
+
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
diff --git a/Lib/test/test_import/data/lazy_imports/global_filter_from.py b/Lib/test/test_import/data/lazy_imports/global_filter_from.py
new file mode 100644
index 00000000000..733839d9c1e
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/global_filter_from.py
@@ -0,0 +1,11 @@
+import importlib
+
+def filter(module_name, imported_name, from_list):
+ assert module_name == __name__
+ assert imported_name == "test.test_import.data.lazy_imports.basic2"
+ assert from_list == ['f']
+ return False
+
+importlib.set_lazy_imports(None, filter)
+
+lazy from import test.test_import.data.lazy_imports.basic2 import f
diff --git a/Lib/test/test_import/data/lazy_imports/global_filter_from_true.py b/Lib/test/test_import/data/lazy_imports/global_filter_from_true.py
new file mode 100644
index 00000000000..c019f1ae811
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/global_filter_from_true.py
@@ -0,0 +1,11 @@
+import importlib
+
+def filter(module_name, imported_name, from_list):
+ assert module_name == __name__
+ assert imported_name == "test.test_import.data.lazy_imports.basic2"
+ assert from_list == ['f']
+ return True
+
+importlib.set_lazy_imports(None, filter)
+
+lazy from import test.test_import.data.lazy_imports.basic2 import f
diff --git a/Lib/test/test_import/data/lazy_imports/global_filter_true.py b/Lib/test/test_import/data/lazy_imports/global_filter_true.py
new file mode 100644
index 00000000000..4881b30fb02
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/global_filter_true.py
@@ -0,0 +1,11 @@
+import sys
+
+def filter(module_name, imported_name, from_list):
+ assert module_name == __name__
+ assert imported_name == "test.test_import.data.lazy_imports.basic2"
+ return True
+
+sys.set_lazy_imports("normal")
+sys.set_lazy_imports_filter(filter)
+
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
diff --git a/Lib/test/test_import/data/lazy_imports/global_off.py b/Lib/test/test_import/data/lazy_imports/global_off.py
new file mode 100644
index 00000000000..4f202744a9e
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/global_off.py
@@ -0,0 +1,5 @@
+import sys
+
+sys.set_lazy_imports("none")
+
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
diff --git a/Lib/test/test_import/data/lazy_imports/global_on.py b/Lib/test/test_import/data/lazy_imports/global_on.py
new file mode 100644
index 00000000000..3f8e1d2aa01
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/global_on.py
@@ -0,0 +1,5 @@
+import sys
+
+sys.set_lazy_imports("all")
+
+import test.test_import.data.lazy_imports.basic2 as basic2
diff --git a/Lib/test/test_import/data/lazy_imports/globals_access.py b/Lib/test/test_import/data/lazy_imports/globals_access.py
new file mode 100644
index 00000000000..c12c6a029c2
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/globals_access.py
@@ -0,0 +1,9 @@
+# Test that globals() returns lazy proxy objects without reifying
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
+
+def get_from_globals():
+ g = globals()
+ return g['basic2']
+
+def get_direct():
+ return basic2
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_class_body.py b/Lib/test/test_import/data/lazy_imports/lazy_class_body.py
new file mode 100644
index 00000000000..e154b78f6cd
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_class_body.py
@@ -0,0 +1,3 @@
+# SyntaxError: lazy import inside class body is not allowed
+class Foo:
+ lazy import json
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_compat_from.py b/Lib/test/test_import/data/lazy_imports/lazy_compat_from.py
new file mode 100644
index 00000000000..f887f47b92c
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_compat_from.py
@@ -0,0 +1,6 @@
+# Test __lazy_modules__ with from imports
+__lazy_modules__ = ['test.test_import.data.lazy_imports.basic2']
+from test.test_import.data.lazy_imports.basic2 import x, f
+
+def get_x():
+ return x
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_future_import.py b/Lib/test/test_import/data/lazy_imports/lazy_future_import.py
new file mode 100644
index 00000000000..8bd258b76b4
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_future_import.py
@@ -0,0 +1 @@
+lazy from __future__ import annotations
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_get_value.py b/Lib/test/test_import/data/lazy_imports/lazy_get_value.py
new file mode 100644
index 00000000000..0ff572fa1e3
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_get_value.py
@@ -0,0 +1,7 @@
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
+
+def f():
+ x = globals()
+ return x['basic2'].resolve()
+
+f()
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_import_func.py b/Lib/test/test_import/data/lazy_imports/lazy_import_func.py
new file mode 100644
index 00000000000..af758b51127
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_import_func.py
@@ -0,0 +1,2 @@
+def f():
+ lazy import foo
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_import_pkg.py b/Lib/test/test_import/data/lazy_imports/lazy_import_pkg.py
new file mode 100644
index 00000000000..79aa9a56739
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_import_pkg.py
@@ -0,0 +1,2 @@
+lazy import test.test_import.data.lazy_imports.pkg.bar
+x = test.test_import.data.lazy_imports.pkg.bar.f
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_try_except.py b/Lib/test/test_import/data/lazy_imports/lazy_try_except.py
new file mode 100644
index 00000000000..e58d1f929ca
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_try_except.py
@@ -0,0 +1,4 @@
+try:
+ lazy import foo
+except:
+ pass
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_try_except_from.py b/Lib/test/test_import/data/lazy_imports/lazy_try_except_from.py
new file mode 100644
index 00000000000..8c97553f486
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_try_except_from.py
@@ -0,0 +1,4 @@
+try:
+ lazy from foo import bar
+except:
+ pass
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_try_except_from_star.py b/Lib/test/test_import/data/lazy_imports/lazy_try_except_from_star.py
new file mode 100644
index 00000000000..b2370eaae77
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_try_except_from_star.py
@@ -0,0 +1 @@
+lazy from foo import *
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_with.py b/Lib/test/test_import/data/lazy_imports/lazy_with.py
new file mode 100644
index 00000000000..b383879936a
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_with.py
@@ -0,0 +1,3 @@
+import contextlib
+with contextlib.nullcontext():
+ lazy import test.test_import.data.lazy_imports.basic2
diff --git a/Lib/test/test_import/data/lazy_imports/lazy_with_from.py b/Lib/test/test_import/data/lazy_imports/lazy_with_from.py
new file mode 100644
index 00000000000..7936326a9e3
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/lazy_with_from.py
@@ -0,0 +1,3 @@
+import contextlib
+with contextlib.nullcontext():
+ lazy import test.test_import.data.lazy_imports.basic2 as basic2
diff --git a/Lib/test/test_import/data/lazy_imports/modules_dict.py b/Lib/test/test_import/data/lazy_imports/modules_dict.py
new file mode 100644
index 00000000000..327f866398c
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/modules_dict.py
@@ -0,0 +1,5 @@
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
+
+import sys
+mod = sys.modules[__name__]
+x = mod.__dict__
diff --git a/Lib/test/test_import/data/lazy_imports/modules_getattr.py b/Lib/test/test_import/data/lazy_imports/modules_getattr.py
new file mode 100644
index 00000000000..ae1d4bb3f97
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/modules_getattr.py
@@ -0,0 +1,5 @@
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
+
+import sys
+mod = sys.modules[__name__]
+x = mod.basic2
diff --git a/Lib/test/test_import/data/lazy_imports/modules_getattr_other.py b/Lib/test/test_import/data/lazy_imports/modules_getattr_other.py
new file mode 100644
index 00000000000..e4d83e6336d
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/modules_getattr_other.py
@@ -0,0 +1,5 @@
+lazy import test.test_import.data.lazy_imports.basic2 as basic2
+
+import sys
+mod = sys.modules[__name__]
+x = mod.__name__
diff --git a/Lib/test/test_import/data/lazy_imports/multi_from_import.py b/Lib/test/test_import/data/lazy_imports/multi_from_import.py
new file mode 100644
index 00000000000..96dc9757500
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/multi_from_import.py
@@ -0,0 +1,5 @@
+# Test that lazy from import with multiple names only reifies accessed names
+lazy from test.test_import.data.lazy_imports.basic2 import f, x
+
+def get_globals():
+ return globals()
diff --git a/Lib/test/test_import/data/lazy_imports/pkg/__init__.py b/Lib/test/test_import/data/lazy_imports/pkg/__init__.py
new file mode 100644
index 00000000000..2d76abaa89f
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/pkg/__init__.py
@@ -0,0 +1 @@
+x = 42
diff --git a/Lib/test/test_import/data/lazy_imports/pkg/b.py b/Lib/test/test_import/data/lazy_imports/pkg/b.py
new file mode 100644
index 00000000000..a266b7c7c0d
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/pkg/b.py
@@ -0,0 +1,2 @@
+def foo():
+ return 'foo'
diff --git a/Lib/test/test_import/data/lazy_imports/pkg/bar.py b/Lib/test/test_import/data/lazy_imports/pkg/bar.py
new file mode 100644
index 00000000000..b8d8b60b886
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/pkg/bar.py
@@ -0,0 +1,2 @@
+print("BAR_MODULE_LOADED")
+def f(): pass
diff --git a/Lib/test/test_import/data/lazy_imports/pkg/c.py b/Lib/test/test_import/data/lazy_imports/pkg/c.py
new file mode 100644
index 00000000000..0bb03119864
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/pkg/c.py
@@ -0,0 +1,4 @@
+lazy from . import b, x
+
+def get_globals():
+ return globals()
diff --git a/Lib/test/test_import/data/lazy_imports/relative_lazy.py b/Lib/test/test_import/data/lazy_imports/relative_lazy.py
new file mode 100644
index 00000000000..6273d3883ab
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/relative_lazy.py
@@ -0,0 +1,5 @@
+# Test relative imports with lazy keyword
+lazy from . import basic2
+
+def get_basic2():
+ return basic2
diff --git a/Lib/test/test_import/data/lazy_imports/relative_lazy_from.py b/Lib/test/test_import/data/lazy_imports/relative_lazy_from.py
new file mode 100644
index 00000000000..1bae2d6853d
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/relative_lazy_from.py
@@ -0,0 +1,8 @@
+# Test relative from imports with lazy keyword
+lazy from .basic2 import x, f
+
+def get_x():
+ return x
+
+def get_f():
+ return f
diff --git a/Lib/test/test_import/data/lazy_imports/try_except_eager.py b/Lib/test/test_import/data/lazy_imports/try_except_eager.py
new file mode 100644
index 00000000000..4cdaa9a9b48
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/try_except_eager.py
@@ -0,0 +1,4 @@
+try:
+ import test.test_import.data.lazy_imports.basic2
+except:
+ pass
diff --git a/Lib/test/test_import/data/lazy_imports/try_except_eager_from.py b/Lib/test/test_import/data/lazy_imports/try_except_eager_from.py
new file mode 100644
index 00000000000..6eadaaa71ca
--- /dev/null
+++ b/Lib/test/test_import/data/lazy_imports/try_except_eager_from.py
@@ -0,0 +1,4 @@
+try:
+ from test.test_import.data.lazy_imports.basic2 import f
+except:
+ pass
diff --git a/Lib/test/test_import/test_lazy_imports.py b/Lib/test/test_import/test_lazy_imports.py
new file mode 100644
index 00000000000..1193af95890
--- /dev/null
+++ b/Lib/test/test_import/test_lazy_imports.py
@@ -0,0 +1,1662 @@
+"""Tests for PEP 810 lazy imports."""
+
+import io
+import dis
+import subprocess
+import sys
+import textwrap
+import threading
+import types
+import unittest
+
+try:
+ import _testcapi
+except ImportError:
+ _testcapi = None
+
+
+class LazyImportTests(unittest.TestCase):
+ """Tests for basic lazy import functionality."""
+
+ def tearDown(self):
+ """Clean up any test modules from sys.modules."""
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+ sys.lazy_modules.clear()
+
+ def test_basic_unused(self):
+ """Lazy imported module should not be loaded if never accessed."""
+ import test.test_import.data.lazy_imports.basic_unused
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+ self.assertIn("test.test_import.data.lazy_imports", sys.lazy_modules)
+ self.assertEqual(sys.lazy_modules["test.test_import.data.lazy_imports"], {"basic2"})
+
+ def test_sys_lazy_modules(self):
+ try:
+ import test.test_import.data.lazy_imports.basic_from_unused
+ except ImportError as e:
+ self.fail('lazy import failed')
+
+ self.assertFalse("test.test_import.data.lazy_imports.basic2" in sys.modules)
+ self.assertIn("test.test_import.data.lazy_imports", sys.lazy_modules)
+ self.assertEqual(sys.lazy_modules["test.test_import.data.lazy_imports"], {"basic2"})
+ test.test_import.data.lazy_imports.basic_from_unused.basic2
+ self.assertNotIn("test.test_import.data", sys.lazy_modules)
+
+ def test_basic_unused_use_externally(self):
+ """Lazy import should load module when accessed from outside."""
+ from test.test_import.data.lazy_imports import basic_unused
+
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+ x = basic_unused.test.test_import.data.lazy_imports.basic2
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_basic_from_unused_use_externally(self):
+ """Lazy 'from' import should load when accessed from outside."""
+ from test.test_import.data.lazy_imports import basic_from_unused
+
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+ x = basic_from_unused.basic2
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_basic_unused_dir(self):
+ """dir() on module should not trigger lazy import reification."""
+ import test.test_import.data.lazy_imports.basic_unused
+
+ x = dir(test.test_import.data.lazy_imports.basic_unused)
+ self.assertIn("test", x)
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_basic_dir(self):
+ """dir() at module scope should not trigger lazy import reification."""
+ from test.test_import.data.lazy_imports import basic_dir
+
+ self.assertIn("test", basic_dir.x)
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_basic_used(self):
+ """Lazy import should load when accessed within the module."""
+ import test.test_import.data.lazy_imports.basic_used
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class GlobalLazyImportModeTests(unittest.TestCase):
+ """Tests for sys.set_lazy_imports() global mode control."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_global_off(self):
+ """Mode 'none' should disable lazy imports entirely."""
+ import test.test_import.data.lazy_imports.global_off
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_global_on(self):
+ """Mode 'all' should make regular imports lazy."""
+ import test.test_import.data.lazy_imports.global_on
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_global_filter(self):
+ """Filter returning False should prevent lazy loading."""
+ import test.test_import.data.lazy_imports.global_filter
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_global_filter_true(self):
+ """Filter returning True should allow lazy loading."""
+ import test.test_import.data.lazy_imports.global_filter_true
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_global_filter_from(self):
+ """Filter should work with 'from' imports."""
+ import test.test_import.data.lazy_imports.global_filter
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_global_filter_from_true(self):
+ """Filter returning True should allow lazy 'from' imports."""
+ import test.test_import.data.lazy_imports.global_filter_true
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class CompatibilityModeTests(unittest.TestCase):
+ """Tests for __lazy_modules__ compatibility mode."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_compatibility_mode(self):
+ """__lazy_modules__ should enable lazy imports for listed modules."""
+ import test.test_import.data.lazy_imports.basic_compatibility_mode
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_compatibility_mode_used(self):
+ """Using a lazy import from __lazy_modules__ should load the module."""
+ import test.test_import.data.lazy_imports.basic_compatibility_mode_used
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_compatibility_mode_func(self):
+ """Imports inside functions should be eager even in compatibility mode."""
+ import test.test_import.data.lazy_imports.compatibility_mode_func
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_compatibility_mode_try_except(self):
+ """Imports in try/except should be eager even in compatibility mode."""
+ import test.test_import.data.lazy_imports.compatibility_mode_try_except
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_compatibility_mode_relative(self):
+ """__lazy_modules__ should work with relative imports."""
+ import test.test_import.data.lazy_imports.basic_compatibility_mode_relative
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class ModuleIntrospectionTests(unittest.TestCase):
+ """Tests for module dict and getattr behavior with lazy imports."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_modules_dict(self):
+ """Accessing module.__dict__ should not trigger reification."""
+ import test.test_import.data.lazy_imports.modules_dict
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_modules_getattr(self):
+ """Module __getattr__ for lazy import name should trigger reification."""
+ import test.test_import.data.lazy_imports.modules_getattr
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_modules_getattr_other(self):
+ """Module __getattr__ for other names should not trigger reification."""
+ import test.test_import.data.lazy_imports.modules_getattr_other
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class LazyImportTypeTests(unittest.TestCase):
+ """Tests for the LazyImportType and its resolve() method."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_lazy_value_resolve(self):
+ """resolve() method should force the lazy import to load."""
+ import test.test_import.data.lazy_imports.lazy_get_value
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_lazy_import_type_exposed(self):
+ """LazyImportType should be exposed in types module."""
+ self.assertHasAttr(types, 'LazyImportType')
+ self.assertEqual(types.LazyImportType.__name__, 'lazy_import')
+
+ def test_lazy_import_type_cant_construct(self):
+ """LazyImportType should not be directly constructible."""
+ self.assertRaises(TypeError, types.LazyImportType, {}, "module")
+
+
+class SyntaxRestrictionTests(unittest.TestCase):
+ """Tests for syntax restrictions on lazy imports."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_lazy_try_except(self):
+ """lazy import inside try/except should raise SyntaxError."""
+ with self.assertRaises(SyntaxError):
+ import test.test_import.data.lazy_imports.lazy_try_except
+
+ def test_lazy_try_except_from(self):
+ """lazy from import inside try/except should raise SyntaxError."""
+ with self.assertRaises(SyntaxError):
+ import test.test_import.data.lazy_imports.lazy_try_except_from
+
+ def test_lazy_try_except_from_star(self):
+ """lazy from import * should raise SyntaxError."""
+ with self.assertRaises(SyntaxError):
+ import test.test_import.data.lazy_imports.lazy_try_except_from_star
+
+ def test_lazy_future_import(self):
+ """lazy from __future__ import should raise SyntaxError."""
+ with self.assertRaises(SyntaxError) as cm:
+ import test.test_import.data.lazy_imports.lazy_future_import
+ # Check we highlight 'lazy' (column offset 0, end offset 4)
+ self.assertEqual(cm.exception.offset, 1)
+ self.assertEqual(cm.exception.end_offset, 5)
+
+ def test_lazy_import_func(self):
+ """lazy import inside function should raise SyntaxError."""
+ with self.assertRaises(SyntaxError):
+ import test.test_import.data.lazy_imports.lazy_import_func
+
+ def test_lazy_import_exec_in_function(self):
+ """lazy import via exec() inside a function should raise SyntaxError."""
+ # exec() inside a function creates a non-module-level context
+ # where lazy imports are not allowed
+ def f():
+ exec("lazy import json")
+
+ with self.assertRaises(SyntaxError) as cm:
+ f()
+ self.assertIn("only allowed at module level", str(cm.exception))
+
+ def test_lazy_import_exec_at_module_level(self):
+ """lazy import via exec() at module level should work."""
+ # exec() at module level (globals == locals) should allow lazy imports
+ code = textwrap.dedent("""
+ import sys
+ exec("lazy import json")
+ # Should be lazy - not loaded yet
+ assert 'json' not in sys.modules
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class EagerImportInLazyModeTests(unittest.TestCase):
+ """Tests for imports that should remain eager even in lazy mode."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_try_except_eager(self):
+ """Imports in try/except should be eager even with mode='all'."""
+ sys.set_lazy_imports("all")
+ import test.test_import.data.lazy_imports.try_except_eager
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_try_except_eager_from(self):
+ """From imports in try/except should be eager even with mode='all'."""
+ sys.set_lazy_imports("all")
+ import test.test_import.data.lazy_imports.try_except_eager_from
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_eager_import_func(self):
+ """Imports inside functions should return modules, not proxies."""
+ sys.set_lazy_imports("all")
+ import test.test_import.data.lazy_imports.eager_import_func
+
+ f = test.test_import.data.lazy_imports.eager_import_func.f
+ self.assertEqual(type(f()), type(sys))
+
+
+class WithStatementTests(unittest.TestCase):
+ """Tests for lazy imports in with statement context."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_lazy_with(self):
+ """lazy import with 'with' statement should work."""
+ import test.test_import.data.lazy_imports.lazy_with
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_lazy_with_from(self):
+ """lazy from import with 'with' statement should work."""
+ import test.test_import.data.lazy_imports.lazy_with_from
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class PackageTests(unittest.TestCase):
+ """Tests for lazy imports with packages."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_lazy_import_pkg(self):
+ """lazy import of package submodule should load the package."""
+ import test.test_import.data.lazy_imports.lazy_import_pkg
+
+ self.assertIn("test.test_import.data.lazy_imports.pkg", sys.modules)
+ self.assertIn("test.test_import.data.lazy_imports.pkg.bar", sys.modules)
+
+ def test_lazy_import_pkg_cross_import(self):
+ """Cross-imports within package should preserve lazy imports."""
+ import test.test_import.data.lazy_imports.pkg.c
+
+ self.assertIn("test.test_import.data.lazy_imports.pkg", sys.modules)
+ self.assertIn("test.test_import.data.lazy_imports.pkg.c", sys.modules)
+ self.assertNotIn("test.test_import.data.lazy_imports.pkg.b", sys.modules)
+
+ g = test.test_import.data.lazy_imports.pkg.c.get_globals()
+ self.assertEqual(type(g["x"]), int)
+ self.assertEqual(type(g["b"]), types.LazyImportType)
+
+
+class DunderLazyImportTests(unittest.TestCase):
+ """Tests for __lazy_import__ builtin function."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_dunder_lazy_import(self):
+ """__lazy_import__ should create lazy import proxy."""
+ import test.test_import.data.lazy_imports.dunder_lazy_import
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_dunder_lazy_import_used(self):
+ """Using __lazy_import__ result should trigger module load."""
+ import test.test_import.data.lazy_imports.dunder_lazy_import_used
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_dunder_lazy_import_builtins(self):
+ """__lazy_import__ should use module's __builtins__ for __import__."""
+ from test.test_import.data.lazy_imports import dunder_lazy_import_builtins
+
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+ self.assertEqual(dunder_lazy_import_builtins.basic.basic2, 42)
+
+
+class SysLazyImportsAPITests(unittest.TestCase):
+ """Tests for sys lazy imports API functions."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_set_lazy_imports_requires_string(self):
+ """set_lazy_imports should reject non-string arguments."""
+ with self.assertRaises(TypeError):
+ sys.set_lazy_imports(True)
+ with self.assertRaises(TypeError):
+ sys.set_lazy_imports(None)
+ with self.assertRaises(TypeError):
+ sys.set_lazy_imports(1)
+
+ def test_set_lazy_imports_rejects_invalid_mode(self):
+ """set_lazy_imports should reject invalid mode strings."""
+ with self.assertRaises(ValueError):
+ sys.set_lazy_imports("invalid")
+ with self.assertRaises(ValueError):
+ sys.set_lazy_imports("on")
+ with self.assertRaises(ValueError):
+ sys.set_lazy_imports("off")
+
+ def test_get_lazy_imports_returns_string(self):
+ """get_lazy_imports should return string modes."""
+ sys.set_lazy_imports("normal")
+ self.assertEqual(sys.get_lazy_imports(), "normal")
+
+ sys.set_lazy_imports("all")
+ self.assertEqual(sys.get_lazy_imports(), "all")
+
+ sys.set_lazy_imports("none")
+ self.assertEqual(sys.get_lazy_imports(), "none")
+
+ def test_get_lazy_imports_filter_default(self):
+ """get_lazy_imports_filter should return None by default."""
+ sys.set_lazy_imports_filter(None)
+ self.assertIsNone(sys.get_lazy_imports_filter())
+
+ def test_set_and_get_lazy_imports_filter(self):
+ """set/get_lazy_imports_filter should round-trip filter function."""
+ def my_filter(name):
+ return name.startswith("test.")
+
+ sys.set_lazy_imports_filter(my_filter)
+ self.assertIs(sys.get_lazy_imports_filter(), my_filter)
+
+ def test_lazy_modules_attribute_is_set(self):
+ """sys.lazy_modules should be a set per PEP 810."""
+ self.assertIsInstance(sys.lazy_modules, dict)
+
+ def test_lazy_modules_tracks_lazy_imports(self):
+ """sys.lazy_modules should track lazily imported module names."""
+ code = textwrap.dedent("""
+ import sys
+ initial_count = len(sys.lazy_modules)
+ import test.test_import.data.lazy_imports.basic_unused
+ assert "test.test_import.data.lazy_imports" in sys.lazy_modules
+ assert sys.lazy_modules["test.test_import.data.lazy_imports"] == {"basic2"}
+ assert len(sys.lazy_modules) > initial_count
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class ErrorHandlingTests(unittest.TestCase):
+ """Tests for error handling during lazy import reification.
+
+ PEP 810: Errors during reification should show exception chaining with
+ both the lazy import definition location and the access location.
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_import_error_shows_chained_traceback(self):
+ """ImportError during reification should chain to show both definition and access."""
+ # Errors at reification must show where the lazy import was defined
+ # AND where the access happened, per PEP 810 "Reification" section
+ code = textwrap.dedent("""
+ import sys
+ lazy import test.test_import.data.lazy_imports.nonexistent_module
+
+ try:
+ x = test.test_import.data.lazy_imports.nonexistent_module
+ except ImportError as e:
+ # Should have __cause__ showing the original error
+ # The exception chain shows both where import was defined and where access happened
+ assert e.__cause__ is not None, "Expected chained exception"
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_attribute_error_on_from_import_shows_chained_traceback(self):
+ """Accessing missing attribute from lazy from-import should chain errors."""
+ # Tests 'lazy from module import nonexistent' behavior
+ code = textwrap.dedent("""
+ import sys
+ lazy from test.test_import.data.lazy_imports.basic2 import nonexistent_name
+
+ try:
+ x = nonexistent_name
+ except ImportError as e:
+ # PEP 810: Enhanced error reporting through exception chaining
+ assert e.__cause__ is not None, "Expected chained exception"
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_reification_retries_on_failure(self):
+ """Failed reification should allow retry on subsequent access.
+
+ PEP 810: "If reification fails, the lazy object is not reified or replaced.
+ Subsequent uses of the lazy object will re-try the reification."
+ """
+ code = textwrap.dedent("""
+ import sys
+ import types
+
+ lazy import test.test_import.data.lazy_imports.broken_module
+
+ # First access - should fail
+ try:
+ x = test.test_import.data.lazy_imports.broken_module
+ except ValueError:
+ pass
+
+ # The lazy object should still be a lazy proxy (not reified)
+ g = globals()
+ lazy_obj = g['test']
+ # The root 'test' binding should still allow retry
+ # Second access - should also fail (retry the import)
+ try:
+ x = test.test_import.data.lazy_imports.broken_module
+ except ValueError:
+ print("OK - retry worked")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_error_during_module_execution_propagates(self):
+ """Errors in module code during reification should propagate correctly."""
+ # Module that raises during import should propagate with chaining
+ code = textwrap.dedent("""
+ import sys
+ lazy import test.test_import.data.lazy_imports.broken_module
+
+ try:
+ _ = test.test_import.data.lazy_imports.broken_module
+ print("FAIL - should have raised")
+ except ValueError as e:
+ # The ValueError from the module should be the cause
+ if "always fails" in str(e) or (e.__cause__ and "always fails" in str(e.__cause__)):
+ print("OK")
+ else:
+ print(f"FAIL - wrong error: {e}")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class GlobalsAndDictTests(unittest.TestCase):
+ """Tests for globals() and __dict__ behavior with lazy imports.
+
+ PEP 810: "Calling globals() or accessing a module's __dict__ does not trigger
+ reification – they return the module's dictionary, and accessing lazy objects
+ through that dictionary still returns lazy proxy objects."
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_globals_returns_lazy_proxy_when_accessed_from_function(self):
+ """globals() accessed from a function should return lazy proxy without reification.
+
+ Note: At module level, accessing globals()['name'] triggers LOAD_NAME which
+ automatically resolves lazy imports. Inside a function, accessing globals()['name']
+ uses BINARY_SUBSCR which returns the lazy proxy without resolution.
+ """
+ code = textwrap.dedent("""
+ import sys
+ import types
+
+ lazy from test.test_import.data.lazy_imports.basic2 import x
+
+ # Check that module is not yet loaded
+ assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
+
+ def check_lazy():
+ # Access through globals() from inside a function
+ g = globals()
+ lazy_obj = g['x']
+ return type(lazy_obj) is types.LazyImportType
+
+ # Inside function, should get lazy proxy
+ is_lazy = check_lazy()
+ assert is_lazy, "Expected LazyImportType from function scope"
+
+ # Module should STILL not be loaded
+ assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_globals_dict_access_returns_lazy_proxy_inline(self):
+ """Accessing globals()['name'] inline should return lazy proxy.
+
+ Note: Assigning g['name'] to a local variable at module level triggers
+ reification due to STORE_NAME bytecode. Inline access preserves laziness.
+ """
+ code = textwrap.dedent("""
+ import sys
+ import types
+ lazy import json
+ # Inline access without assignment to local variable preserves lazy proxy
+ assert type(globals()['json']) is types.LazyImportType
+ assert 'json' not in sys.modules
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_module_dict_returns_lazy_proxy_without_reifying(self):
+ """module.__dict__ access should not trigger reification."""
+ import test.test_import.data.lazy_imports.globals_access
+
+ # Module not loaded yet via direct dict access
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ # Access via get_from_globals should return lazy proxy
+ lazy_obj = test.test_import.data.lazy_imports.globals_access.get_from_globals()
+ self.assertEqual(type(lazy_obj), types.LazyImportType)
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_direct_access_triggers_reification(self):
+ """Direct name access (not through globals()) should trigger reification."""
+ import test.test_import.data.lazy_imports.globals_access
+
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ # Direct access should reify
+ result = test.test_import.data.lazy_imports.globals_access.get_direct()
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_resolve_method_forces_reification(self):
+ """Calling resolve() on lazy proxy should force reification.
+
+ Note: Must access lazy proxy from within a function to avoid automatic
+ reification by LOAD_NAME at module level.
+ """
+ code = textwrap.dedent("""
+ import sys
+ import types
+
+ lazy from test.test_import.data.lazy_imports.basic2 import x
+
+ assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
+
+ def test_resolve():
+ g = globals()
+ lazy_obj = g['x']
+ assert type(lazy_obj) is types.LazyImportType, f"Expected lazy proxy, got {type(lazy_obj)}"
+
+ resolved = lazy_obj.resolve()
+
+ # Now module should be loaded
+ assert 'test.test_import.data.lazy_imports.basic2' in sys.modules
+ assert resolved == 42 # x is 42 in basic2.py
+ return True
+
+ assert test_resolve()
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_add_lazy_to_globals(self):
+ code = textwrap.dedent("""
+ import sys
+ import types
+
+ lazy from test.test_import.data.lazy_imports import basic2
+
+ assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
+
+ class C: pass
+ sneaky = C()
+ sneaky.x = 1
+
+ def f():
+ t = 0
+ for _ in range(5):
+ t += sneaky.x
+ return t
+
+ f()
+ globals()["sneaky"] = globals()["basic2"]
+ assert f() == 210
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class MultipleNameFromImportTests(unittest.TestCase):
+ """Tests for lazy from ... import with multiple names.
+
+ PEP 810: "When using lazy from ... import, each imported name is bound to a
+ lazy proxy object. The first access to any of these names triggers loading
+ of the entire module and reifies only that specific name to its actual value.
+ Other names remain as lazy proxies until they are accessed."
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_accessing_one_name_leaves_others_as_proxies(self):
+ """Accessing one name from multi-name import should leave others lazy."""
+ code = textwrap.dedent("""
+ import sys
+ import types
+
+ lazy from test.test_import.data.lazy_imports.basic2 import f, x
+
+ # Neither should be loaded yet
+ assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
+
+ g = globals()
+ assert type(g['f']) is types.LazyImportType
+ assert type(g['x']) is types.LazyImportType
+
+ # Access 'x' - this loads the module and reifies only 'x'
+ value = x
+ assert value == 42
+
+ # Module is now loaded
+ assert 'test.test_import.data.lazy_imports.basic2' in sys.modules
+
+ # 'x' should be reified (int), 'f' should still be lazy proxy
+ assert type(g['x']) is int, f"Expected int, got {type(g['x'])}"
+ assert type(g['f']) is types.LazyImportType, f"Expected LazyImportType, got {type(g['f'])}"
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_all_names_reified_after_all_accessed(self):
+ """All names should be reified after each is accessed."""
+ code = textwrap.dedent("""
+ import sys
+ import types
+
+ lazy from test.test_import.data.lazy_imports.basic2 import f, x
+
+ g = globals()
+
+ # Access both
+ _ = x
+ _ = f
+
+ # Both should be reified now
+ assert type(g['x']) is int
+ assert callable(g['f'])
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class SysLazyModulesTrackingTests(unittest.TestCase):
+ """Tests for sys.lazy_modules tracking behavior.
+
+ PEP 810: "When the module is reified, it's removed from sys.lazy_modules"
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_module_added_to_lazy_modules_on_lazy_import(self):
+ """Module should be added to sys.lazy_modules when lazily imported."""
+ # PEP 810 states lazy_modules tracks modules that have been lazily imported
+ # Note: The current implementation keeps modules in lazy_modules even after
+ # reification (primarily for diagnostics and introspection)
+ code = textwrap.dedent("""
+ import sys
+
+ initial_count = len(sys.lazy_modules)
+
+ lazy import test.test_import.data.lazy_imports.basic2
+
+ # Should be in lazy_modules after lazy import
+ assert "test.test_import.data.lazy_imports" in sys.lazy_modules
+ assert sys.lazy_modules["test.test_import.data.lazy_imports"] == {"basic2"}
+ assert len(sys.lazy_modules) > initial_count
+
+ # Trigger reification
+ _ = test.test_import.data.lazy_imports.basic2.x
+
+ # Module should still be tracked (for diagnostics per PEP 810)
+ assert "test.test_import.data.lazy_imports" not in sys.lazy_modules
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_lazy_modules_is_per_interpreter(self):
+ """Each interpreter should have independent sys.lazy_modules."""
+ # Basic test that sys.lazy_modules exists and is a set
+ self.assertIsInstance(sys.lazy_modules, dict)
+
+
+class CommandLineAndEnvVarTests(unittest.TestCase):
+ """Tests for command-line and environment variable control.
+
+ PEP 810: The global lazy imports flag can be controlled through:
+ - The -X lazy_imports=<mode> command-line option
+ - The PYTHON_LAZY_IMPORTS=<mode> environment variable
+ """
+
+ def test_cli_lazy_imports_all_makes_regular_imports_lazy(self):
+ """-X lazy_imports=all should make all imports potentially lazy."""
+ code = textwrap.dedent("""
+ import sys
+ # In 'all' mode, regular imports become lazy
+ import json
+ # json should not be in sys.modules yet (lazy)
+ # Actually accessing it triggers reification
+ if 'json' not in sys.modules:
+ print("LAZY")
+ else:
+ print("EAGER")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-X", "lazy_imports=all", "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("LAZY", result.stdout)
+
+ def test_cli_lazy_imports_none_forces_all_imports_eager(self):
+ """-X lazy_imports=none should force all imports to be eager."""
+ code = textwrap.dedent("""
+ import sys
+ # Even explicit lazy imports should be eager in 'none' mode
+ lazy import json
+ if 'json' in sys.modules:
+ print("EAGER")
+ else:
+ print("LAZY")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-X", "lazy_imports=none", "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("EAGER", result.stdout)
+
+ def test_cli_lazy_imports_normal_respects_lazy_keyword_only(self):
+ """-X lazy_imports=normal should respect lazy keyword only."""
+ # Note: Use test modules instead of stdlib modules to avoid
+ # modules already loaded by the interpreter startup
+ code = textwrap.dedent("""
+ import sys
+ import test.test_import.data.lazy_imports.basic2 # Should be eager
+ lazy import test.test_import.data.lazy_imports.pkg.b # Should be lazy
+
+ eager_loaded = 'test.test_import.data.lazy_imports.basic2' in sys.modules
+ lazy_loaded = 'test.test_import.data.lazy_imports.pkg.b' in sys.modules
+
+ if eager_loaded and not lazy_loaded:
+ print("OK")
+ else:
+ print(f"FAIL: eager={eager_loaded}, lazy={lazy_loaded}")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-X", "lazy_imports=normal", "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_env_var_lazy_imports_all_enables_global_lazy(self):
+ """PYTHON_LAZY_IMPORTS=all should enable global lazy imports."""
+ code = textwrap.dedent("""
+ import sys
+ import json
+ if 'json' not in sys.modules:
+ print("LAZY")
+ else:
+ print("EAGER")
+ """)
+ import os
+ env = os.environ.copy()
+ env["PYTHON_LAZY_IMPORTS"] = "all"
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True,
+ env=env
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("LAZY", result.stdout)
+
+ def test_env_var_lazy_imports_none_disables_all_lazy(self):
+ """PYTHON_LAZY_IMPORTS=none should disable all lazy imports."""
+ code = textwrap.dedent("""
+ import sys
+ lazy import json
+ if 'json' in sys.modules:
+ print("EAGER")
+ else:
+ print("LAZY")
+ """)
+ import os
+ env = os.environ.copy()
+ env["PYTHON_LAZY_IMPORTS"] = "none"
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True,
+ env=env
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("EAGER", result.stdout)
+
+ def test_cli_overrides_env_var(self):
+ """Command-line option should take precedence over environment variable."""
+ # PEP 810: -X lazy_imports takes precedence over PYTHON_LAZY_IMPORTS
+ code = textwrap.dedent("""
+ import sys
+ lazy import json
+ if 'json' in sys.modules:
+ print("EAGER")
+ else:
+ print("LAZY")
+ """)
+ import os
+ env = os.environ.copy()
+ env["PYTHON_LAZY_IMPORTS"] = "all" # env says all
+ result = subprocess.run(
+ [sys.executable, "-X", "lazy_imports=none", "-c", code], # CLI says none
+ capture_output=True,
+ text=True,
+ env=env
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ # CLI should win - imports should be eager
+ self.assertIn("EAGER", result.stdout)
+
+ def test_sys_set_lazy_imports_overrides_cli(self):
+ """sys.set_lazy_imports() should take precedence over CLI option."""
+ code = textwrap.dedent("""
+ import sys
+ sys.set_lazy_imports("none") # Override CLI
+ lazy import json
+ if 'json' in sys.modules:
+ print("EAGER")
+ else:
+ print("LAZY")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-X", "lazy_imports=all", "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("EAGER", result.stdout)
+
+
+class FilterFunctionSignatureTests(unittest.TestCase):
+ """Tests for the filter function signature per PEP 810.
+
+ PEP 810: func(importer: str, name: str, fromlist: tuple[str, ...] | None) -> bool
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_filter_receives_correct_arguments_for_import(self):
+ """Filter should receive (importer, name, fromlist=None) for 'import x'."""
+ code = textwrap.dedent("""
+ import sys
+
+ received_args = []
+
+ def my_filter(importer, name, fromlist):
+ received_args.append((importer, name, fromlist))
+ return True
+
+ sys.set_lazy_imports_filter(my_filter)
+
+ lazy import json
+
+ assert len(received_args) == 1, f"Expected 1 call, got {len(received_args)}"
+ importer, name, fromlist = received_args[0]
+ assert name == "json", f"Expected name='json', got {name!r}"
+ assert fromlist is None, f"Expected fromlist=None, got {fromlist!r}"
+ assert isinstance(importer, str), f"Expected str importer, got {type(importer)}"
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_filter_receives_fromlist_for_from_import(self):
+ """Filter should receive fromlist tuple for 'from x import y, z'."""
+ code = textwrap.dedent("""
+ import sys
+
+ received_args = []
+
+ def my_filter(importer, name, fromlist):
+ received_args.append((importer, name, fromlist))
+ return True
+
+ sys.set_lazy_imports_filter(my_filter)
+
+ lazy from json import dumps, loads
+
+ assert len(received_args) == 1, f"Expected 1 call, got {len(received_args)}"
+ importer, name, fromlist = received_args[0]
+ assert name == "json", f"Expected name='json', got {name!r}"
+ assert fromlist == ("dumps", "loads"), f"Expected ('dumps', 'loads'), got {fromlist!r}"
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_filter_returning_false_forces_eager_import(self):
+ """Filter returning False should make import eager."""
+ code = textwrap.dedent("""
+ import sys
+
+ def deny_filter(importer, name, fromlist):
+ return False
+
+ sys.set_lazy_imports_filter(deny_filter)
+
+ lazy import json
+
+ # Should be eager due to filter
+ if 'json' in sys.modules:
+ print("EAGER")
+ else:
+ print("LAZY")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
+ self.assertIn("EAGER", result.stdout)
+
+
+class AdditionalSyntaxRestrictionTests(unittest.TestCase):
+ """Additional syntax restriction tests per PEP 810."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_lazy_import_inside_class_raises_syntax_error(self):
+ """lazy import inside class body should raise SyntaxError."""
+ # PEP 810: "The soft keyword is only allowed at the global (module) level,
+ # not inside functions, class bodies, try blocks, or import *"
+ with self.assertRaises(SyntaxError):
+ import test.test_import.data.lazy_imports.lazy_class_body
+
+
+class MixedLazyEagerImportTests(unittest.TestCase):
+ """Tests for mixing lazy and eager imports of the same module.
+
+ PEP 810: "If module foo is imported both lazily and eagerly in the same
+ program, the eager import takes precedence and both bindings resolve to
+ the same module object."
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_eager_import_before_lazy_resolves_to_same_module(self):
+ """Eager import before lazy should make lazy resolve to same module."""
+ code = textwrap.dedent("""
+ import sys
+ import json # Eager import first
+
+ lazy import json as lazy_json # Lazy import same module
+
+ # lazy_json should resolve to the same object
+ assert json is lazy_json, "Lazy and eager imports should resolve to same module"
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_lazy_import_before_eager_resolves_to_same_module(self):
+ """Lazy import followed by eager should both point to same module."""
+ code = textwrap.dedent("""
+ import sys
+
+ lazy import json as lazy_json
+
+ # Lazy not loaded yet
+ assert 'json' not in sys.modules
+
+ import json # Eager import triggers load
+
+ # Both should be the same object
+ assert json is lazy_json
+ print("OK")
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class RelativeImportTests(unittest.TestCase):
+ """Tests for relative imports with lazy keyword."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_relative_lazy_import(self):
+ """lazy from . import submodule should work."""
+ from test.test_import.data.lazy_imports import relative_lazy
+
+ # basic2 should not be loaded yet
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ # Access triggers reification
+ result = relative_lazy.get_basic2()
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ def test_relative_lazy_from_import(self):
+ """lazy from .module import name should work."""
+ from test.test_import.data.lazy_imports import relative_lazy_from
+
+ # basic2 should not be loaded yet
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ # Access triggers reification
+ result = relative_lazy_from.get_x()
+ self.assertEqual(result, 42)
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class LazyModulesCompatibilityFromImportTests(unittest.TestCase):
+ """Tests for __lazy_modules__ with from imports.
+
+ PEP 810: "When a module is made lazy this way, from-imports using that
+ module are also lazy"
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_lazy_modules_makes_from_imports_lazy(self):
+ """__lazy_modules__ should make from imports of listed modules lazy."""
+ from test.test_import.data.lazy_imports import lazy_compat_from
+
+ # basic2 should not be loaded yet because it's in __lazy_modules__
+ self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+ # Access triggers reification
+ result = lazy_compat_from.get_x()
+ self.assertEqual(result, 42)
+ self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
+
+
+class ImportStateAtReificationTests(unittest.TestCase):
+ """Tests for import system state at reification time.
+
+ PEP 810: "Reification still calls __import__ to resolve the import, which uses
+ the state of the import system (e.g. sys.path, sys.meta_path, sys.path_hooks
+ and __import__) at reification time, not the state when the lazy import
+ statement was evaluated."
+ """
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_sys_path_at_reification_time_is_used(self):
+ """sys.path changes after lazy import should affect reification."""
+ code = textwrap.dedent("""
+ import sys
+ import tempfile
+ import os
+
+ # Create a temporary module
+ with tempfile.TemporaryDirectory() as tmpdir:
+ mod_path = os.path.join(tmpdir, "dynamic_test_module.py")
+ with open(mod_path, "w") as f:
+ f.write("VALUE = 'from_temp_dir'\\n")
+
+ # Lazy import before adding to path
+ lazy import dynamic_test_module
+
+ # Module cannot be found yet
+ try:
+ _ = dynamic_test_module
+ print("FAIL - should not find module")
+ except ModuleNotFoundError:
+ pass
+
+ # Now add temp dir to path
+ sys.path.insert(0, tmpdir)
+
+ # Now reification should succeed using current sys.path
+ assert dynamic_test_module.VALUE == 'from_temp_dir'
+ print("OK")
+
+ sys.path.remove(tmpdir)
+ """)
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class ThreadSafetyTests(unittest.TestCase):
+ """Tests for thread-safety of lazy imports."""
+
+ def tearDown(self):
+ for key in list(sys.modules.keys()):
+ if key.startswith('test.test_import.data.lazy_imports'):
+ del sys.modules[key]
+
+ sys.set_lazy_imports_filter(None)
+ sys.set_lazy_imports("normal")
+
+ def test_concurrent_lazy_import_reification(self):
+ """Multiple threads racing to reify the same lazy import should succeed."""
+ from test.test_import.data.lazy_imports import basic_unused
+
+ num_threads = 10
+ results = [None] * num_threads
+ errors = []
+ barrier = threading.Barrier(num_threads)
+
+ def access_lazy_import(idx):
+ try:
+ barrier.wait()
+ module = basic_unused.test.test_import.data.lazy_imports.basic2
+ results[idx] = module
+ except Exception as e:
+ errors.append((idx, e))
+
+ threads = [
+ threading.Thread(target=access_lazy_import, args=(i,))
+ for i in range(num_threads)
+ ]
+
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ self.assertEqual(errors, [], f"Errors occurred: {errors}")
+ self.assertTrue(all(r is not None for r in results))
+ first_module = results[0]
+ for r in results[1:]:
+ self.assertIs(r, first_module)
+
+ def test_concurrent_reification_multiple_modules(self):
+ """Multiple threads reifying different lazy imports concurrently."""
+ code = textwrap.dedent("""
+ import sys
+ import threading
+
+ sys.set_lazy_imports("all")
+
+ lazy import json
+ lazy import os
+ lazy import io
+ lazy import re
+
+ num_threads = 8
+ results = {}
+ errors = []
+ barrier = threading.Barrier(num_threads)
+
+ def access_modules(idx):
+ try:
+ barrier.wait()
+ mods = [json, os, io, re]
+ results[idx] = [type(m).__name__ for m in mods]
+ except Exception as e:
+ errors.append((idx, e))
+
+ threads = [
+ threading.Thread(target=access_modules, args=(i,))
+ for i in range(num_threads)
+ ]
+
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert not errors, f"Errors: {errors}"
+ for idx, mods in results.items():
+ assert all(m == 'module' for m in mods), f"Thread {idx} got: {mods}"
+
+ print("OK")
+ """)
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_concurrent_lazy_modules_set_updates(self):
+ """Multiple threads creating lazy imports should safely update sys.lazy_modules."""
+ code = textwrap.dedent("""
+ import sys
+ import threading
+
+ num_threads = 16
+ iterations = 50
+ errors = []
+ barrier = threading.Barrier(num_threads)
+
+ def create_lazy_imports(idx):
+ try:
+ barrier.wait()
+ for i in range(iterations):
+ exec(f"lazy import json as json_{idx}_{i}", globals())
+ exec(f"lazy import os as os_{idx}_{i}", globals())
+ except Exception as e:
+ errors.append((idx, e))
+
+ threads = [
+ threading.Thread(target=create_lazy_imports, args=(i,))
+ for i in range(num_threads)
+ ]
+
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert not errors, f"Errors: {errors}"
+ assert isinstance(sys.lazy_modules, dict), "sys.lazy_modules is not a dict"
+ print("OK")
+ """)
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_concurrent_reification_same_module_high_contention(self):
+ """High contention: many threads reifying the exact same lazy import."""
+ code = textwrap.dedent("""
+ import sys
+ import threading
+ import types
+
+ sys.set_lazy_imports("all")
+
+ lazy import json
+
+ num_threads = 20
+ results = [None] * num_threads
+ errors = []
+ barrier = threading.Barrier(num_threads)
+
+ def access_json(idx):
+ try:
+ barrier.wait()
+ for _ in range(100):
+ _ = json.dumps
+ _ = json.loads
+ results[idx] = json
+ except Exception as e:
+ errors.append((idx, e))
+
+ threads = [
+ threading.Thread(target=access_json, args=(i,))
+ for i in range(num_threads)
+ ]
+
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert not errors, f"Errors: {errors}"
+ assert all(r is not None for r in results), "Some threads got None"
+ first = results[0]
+ assert all(r is first for r in results), "Inconsistent module objects"
+ assert not isinstance(first, types.LazyImportType), "Got lazy import instead of module"
+ print("OK")
+ """)
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+ def test_concurrent_reification_with_module_attribute_access(self):
+ """Threads racing to reify and immediately access module attributes."""
+ code = textwrap.dedent("""
+ import sys
+ import threading
+
+ sys.set_lazy_imports("all")
+
+ lazy import collections
+ lazy import functools
+ lazy import itertools
+
+ num_threads = 12
+ results = {}
+ errors = []
+ barrier = threading.Barrier(num_threads)
+
+ def stress_lazy_imports(idx):
+ try:
+ barrier.wait()
+ for _ in range(50):
+ _ = collections.OrderedDict
+ _ = functools.partial
+ _ = itertools.chain
+ _ = collections.defaultdict
+ _ = functools.lru_cache
+ _ = itertools.islice
+ results[idx] = (
+ type(collections).__name__,
+ type(functools).__name__,
+ type(itertools).__name__,
+ )
+ except Exception as e:
+ errors.append((idx, e))
+
+ threads = [
+ threading.Thread(target=stress_lazy_imports, args=(i,))
+ for i in range(num_threads)
+ ]
+
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert not errors, f"Errors: {errors}"
+ for idx, types_tuple in results.items():
+ assert all(t == 'module' for t in types_tuple), f"Thread {idx}: {types_tuple}"
+ print("OK")
+ """)
+
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ capture_output=True,
+ text=True
+ )
+ self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
+ self.assertIn("OK", result.stdout)
+
+
+class LazyImportDisTests(unittest.TestCase):
+ def test_lazy_import_dis(self):
+ """dis should properly show lazy import"""
+ code = compile("lazy import foo", "exec", "exec")
+ f = io.StringIO()
+ dis.dis(code, file=f)
+ self.assertIn("foo + lazy", f.getvalue())
+
+ def test_normal_import_dis(self):
+ """non lazy imports should just show the name"""
+ code = compile("import foo", "exec", "exec")
+ f = io.StringIO()
+ dis.dis(code, file=f)
+ for line in f.getvalue().split('\n'):
+ if "IMPORT_NAME" in line:
+ self.assertIn("(foo)", line)
+ break
+ else:
+ self.assertFail("IMPORT_NAME not found")
+
+
+@unittest.skipIf(_testcapi is None, 'need the _testcapi module')
+class LazyCApiTests(unittest.TestCase):
+ def tearDown(self):
+ sys.set_lazy_imports("normal")
+ sys.set_lazy_imports_filter(None)
+
+ def test_set_matches_sys(self):
+ self.assertEqual(_testcapi.PyImport_GetLazyImportsMode(), sys.get_lazy_imports())
+ for mode in ("normal", "all", "none"):
+ _testcapi.PyImport_SetLazyImportsMode(mode)
+ self.assertEqual(_testcapi.PyImport_GetLazyImportsMode(), sys.get_lazy_imports())
+
+ def test_filter_matches_sys(self):
+ self.assertEqual(_testcapi.PyImport_GetLazyImportsFilter(), sys.get_lazy_imports_filter())
+
+ def filter(*args):
+ pass
+
+ _testcapi.PyImport_SetLazyImportsFilter(filter)
+ self.assertEqual(_testcapi.PyImport_GetLazyImportsFilter(), sys.get_lazy_imports_filter())
+
+ def test_set_bad_filter(self):
+ self.assertRaises(ValueError, _testcapi.PyImport_SetLazyImportsFilter, 42)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/Lib/test/test_pyrepl/test_utils.py b/Lib/test/test_pyrepl/test_utils.py
index 656a1e441e0..3c55b6bdaee 100644
--- a/Lib/test/test_pyrepl/test_utils.py
+++ b/Lib/test/test_pyrepl/test_utils.py
@@ -89,10 +89,42 @@ def test_gen_colors_keyword_highlighting(self):
("obj.list", [(".", "op")]),
("obj.match", [(".", "op")]),
("b. \\\n format", [(".", "op")]),
+ ("lazy", []),
+ ("lazy()", [('(', 'op'), (')', 'op')]),
# highlights
("set", [("set", "builtin")]),
("list", [("list", "builtin")]),
(" \n dict", [("dict", "builtin")]),
+ (
+ " lazy import",
+ [("lazy", "soft_keyword"), ("import", "keyword")],
+ ),
+ (
+ "lazy from cool_people import pablo",
+ [
+ ("lazy", "soft_keyword"),
+ ("from", "keyword"),
+ ("import", "keyword"),
+ ],
+ ),
+ (
+ "if sad: lazy import happy",
+ [
+ ("if", "keyword"),
+ (":", "op"),
+ ("lazy", "soft_keyword"),
+ ("import", "keyword"),
+ ],
+ ),
+ (
+ "pass; lazy import z",
+ [
+ ("pass", "keyword"),
+ (";", "op"),
+ ("lazy", "soft_keyword"),
+ ("import", "keyword"),
+ ],
+ ),
]
for code, expected_highlights in cases:
with self.subTest(code=code):
diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py
index 93f0b98de71..19427f2469e 100644
--- a/Lib/test/test_syntax.py
+++ b/Lib/test/test_syntax.py
@@ -3475,6 +3475,128 @@ def test_ifexp_body_stmt_else_stmt(self):
]:
self._check_error(f"x = {lhs_stmt} if 1 else {rhs_stmt}", msg)
+
+class LazyImportRestrictionTestCase(SyntaxErrorTestCase):
+ """Test syntax restrictions for lazy imports."""
+
+ def test_lazy_import_in_try_block(self):
+ """Test that lazy imports are not allowed inside try blocks."""
+ self._check_error("""\
+try:
+ lazy import os
+except:
+ pass
+""", "lazy import not allowed inside try/except blocks")
+
+ self._check_error("""\
+try:
+ lazy from sys import path
+except ImportError:
+ pass
+""", "lazy from ... import not allowed inside try/except blocks")
+
+ def test_lazy_import_in_trystar_block(self):
+ """Test that lazy imports are not allowed inside try* blocks."""
+ self._check_error("""\
+try:
+ lazy import json
+except* Exception:
+ pass
+""", "lazy import not allowed inside try/except blocks")
+
+ self._check_error("""\
+try:
+ lazy from collections import defaultdict
+except* ImportError:
+ pass
+""", "lazy from ... import not allowed inside try/except blocks")
+
+ def test_lazy_import_in_except_block(self):
+ """Test that lazy imports are not allowed inside except blocks."""
+ self._check_error("""\
+try:
+ sys.modules # trigger the except block
+except* Exception:
+ lazy import sys
+""", "lazy import not allowed inside try/except blocks")
+
+ def test_lazy_import_in_function(self):
+ """Test that lazy imports are not allowed inside functions."""
+ self._check_error("""\
+def func():
+ lazy import math
+""", "lazy import not allowed inside functions")
+
+ self._check_error("""\
+def func():
+ lazy from datetime import datetime
+""", "lazy from ... import not allowed inside functions")
+
+ def test_lazy_import_in_async_function(self):
+ """Test that lazy imports are not allowed inside async functions."""
+ self._check_error("""\
+async def async_func():
+ lazy import asyncio
+""", "lazy import not allowed inside functions")
+
+ self._check_error("""\
+async def async_func():
+ lazy from json import loads
+""", "lazy from ... import not allowed inside functions")
+
+ def test_lazy_import_in_class(self):
+ """Test that lazy imports are not allowed inside classes."""
+ self._check_error("""\
+class MyClass:
+ lazy import typing
+""", "lazy import not allowed inside classes")
+
+ self._check_error("""\
+class MyClass:
+ lazy from abc import ABC
+""", "lazy from ... import not allowed inside classes")
+
+ def test_lazy_import_star_forbidden(self):
+ """Test that 'lazy from ... import *' is forbidden everywhere."""
+ # At module level should also be forbidden
+ self._check_error("lazy from os import *",
+ "lazy from ... import \\* is not allowed")
+
+ # Inside function should give lazy function error first
+ self._check_error("""\
+def func():
+ lazy from sys import *
+""", "lazy from ... import not allowed inside functions")
+
+ def test_lazy_import_nested_scopes(self):
+ """Test lazy imports in nested scopes."""
+ self._check_error("""\
+class Outer:
+ def method(self):
+ lazy import sys
+""", "lazy import not allowed inside functions")
+
+ self._check_error("""\
+def outer():
+ class Inner:
+ lazy import json
+""", "lazy import not allowed inside classes")
+
+ self._check_error("""\
+def outer():
+ def inner():
+ lazy from collections import deque
+""", "lazy from ... import not allowed inside functions")
+
+ def test_lazy_import_valid_cases(self):
+ """Test that lazy imports work at module level."""
+ # These should compile without errors
+ compile("lazy import os", "<test>", "exec")
+ compile("lazy from sys import path", "<test>", "exec")
+ compile("lazy import json as j", "<test>", "exec")
+ compile("lazy from datetime import datetime as dt", "<test>", "exec")
+
+
def load_tests(loader, tests, pattern):
tests.addTest(doctest.DocTestSuite())
return tests
diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py
index b44e0c9779a..8974361c253 100644
--- a/Lib/test/test_sys.py
+++ b/Lib/test/test_sys.py
@@ -865,7 +865,8 @@ def test_sys_flags(self):
"dont_write_bytecode", "no_user_site", "no_site",
"ignore_environment", "verbose", "bytes_warning", "quiet",
"hash_randomization", "isolated", "dev_mode", "utf8_mode",
- "warn_default_encoding", "safe_path", "int_max_str_digits")
+ "warn_default_encoding", "safe_path", "int_max_str_digits",
+ "lazy_imports")
for attr in attrs:
self.assertHasAttr(sys.flags, attr)
attr_type = bool if attr in ("dev_mode", "safe_path") else int
diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py
index a4a49fd44bb..eaca62b12d3 100644
--- a/Lib/test/test_traceback.py
+++ b/Lib/test/test_traceback.py
@@ -5319,5 +5319,47 @@ def expected(t, m, fn, l, f, E, e, z):
]
self.assertEqual(actual, expected(**colors))
+
+class TestLazyImportSuggestions(unittest.TestCase):
+ """Test that lazy imports are not reified when computing AttributeError suggestions."""
+
+ def test_attribute_error_does_not_reify_lazy_imports(self):
+ """Printing an AttributeError should not trigger lazy import reification."""
+ # pkg.bar prints "BAR_MODULE_LOADED" when imported.
+ # If lazy import is reified during suggestion computation, we'll see it.
+ code = textwrap.dedent("""
+ lazy import test.test_import.data.lazy_imports.pkg.bar
+ test.test_import.data.lazy_imports.pkg.nonexistent
+ """)
+ rc, stdout, stderr = assert_python_failure('-c', code)
+ self.assertNotIn(b"BAR_MODULE_LOADED", stdout)
+
+ def test_traceback_formatting_does_not_reify_lazy_imports(self):
+ """Formatting a traceback should not trigger lazy import reification."""
+ code = textwrap.dedent("""
+ import traceback
+ lazy import test.test_import.data.lazy_imports.pkg.bar
+ try:
+ test.test_import.data.lazy_imports.pkg.nonexistent
+ except AttributeError:
+ traceback.format_exc()
+ print("OK")
+ """)
+ rc, stdout, stderr = assert_python_ok('-c', code)
+ self.assertIn(b"OK", stdout)
+ self.assertNotIn(b"BAR_MODULE_LOADED", stdout)
+
+ def test_suggestion_still_works_for_non_lazy_attributes(self):
+ """Suggestions should still work for non-lazy module attributes."""
+ code = textwrap.dedent("""
+ lazy import test.test_import.data.lazy_imports.pkg.bar
+ # Typo for __name__
+ test.test_import.data.lazy_imports.pkg.__nme__
+ """)
+ rc, stdout, stderr = assert_python_failure('-c', code)
+ self.assertIn(b"__name__", stderr)
+ self.assertNotIn(b"BAR_MODULE_LOADED", stdout)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index b0d2348c0e1..39d57c5f5b6 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -41,7 +41,7 @@ def clear_typing_caches():
class TypesTests(unittest.TestCase):
def test_names(self):
- c_only_names = {'CapsuleType'}
+ c_only_names = {'CapsuleType', 'LazyImportType'}
ignored = {'new_class', 'resolve_bases', 'prepare_class',
'get_original_bases', 'DynamicClassAttribute', 'coroutine'}
@@ -55,10 +55,11 @@ def test_names(self):
'CoroutineType', 'EllipsisType', 'FrameType', 'FunctionType',
'FrameLocalsProxyType',
'GeneratorType', 'GenericAlias', 'GetSetDescriptorType',
- 'LambdaType', 'MappingProxyType', 'MemberDescriptorType',
- 'MethodDescriptorType', 'MethodType', 'MethodWrapperType',
- 'ModuleType', 'NoneType', 'NotImplementedType', 'SimpleNamespace',
- 'TracebackType', 'UnionType', 'WrapperDescriptorType',
+ 'LambdaType', 'LazyImportType', 'MappingProxyType',
+ 'MemberDescriptorType', 'MethodDescriptorType', 'MethodType',
+ 'MethodWrapperType', 'ModuleType', 'NoneType',
+ 'NotImplementedType', 'SimpleNamespace', 'TracebackType',
+ 'UnionType', 'WrapperDescriptorType',
}
self.assertEqual(all_names, set(c_types.__all__))
self.assertEqual(all_names - c_only_names, set(py_types.__all__))
|