1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322
|
import asyncio
import builtins
import collections
import copy
import datetime
import functools
import gc
import importlib
import inspect
import io
import linecache
import os
import dis
from os.path import normcase
import _pickle
import pickle
import shutil
import stat
import sys
import subprocess
import time
import types
import tempfile
import textwrap
from typing import Unpack
import unicodedata
import unittest
import unittest.mock
import warnings
import weakref
try:
from concurrent.futures import ThreadPoolExecutor
except ImportError:
ThreadPoolExecutor = None
from test.support import cpython_only, import_helper, suppress_immortalization
from test.support import MISSING_C_DOCSTRINGS, ALWAYS_EQ
from test.support.import_helper import DirsOnSysPath, ready_to_import
from test.support.os_helper import TESTFN, temp_cwd
from test.support.script_helper import assert_python_ok, assert_python_failure, kill_python
from test.support import has_subprocess_support, SuppressCrashReport
from test import support
from test.test_inspect import inspect_fodder as mod
from test.test_inspect import inspect_fodder2 as mod2
from test.test_inspect import inspect_stock_annotations
from test.test_inspect import inspect_stringized_annotations
from test.test_inspect import inspect_stringized_annotations_2
from test.test_inspect import inspect_stringized_annotations_pep695
# Functions tested in this suite:
# ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode,
# isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers,
# getdoc, getfile, getmodule, getsourcefile, getcomments, getsource,
# getclasstree, getargvalues, formatargvalues, currentframe,
# stack, trace, ismethoddescriptor, isdatadescriptor, ismethodwrapper
# NOTE: There are some additional tests relating to interaction with
# zipimport in the test_zipimport_support test module.
modfile = mod.__file__
if modfile.endswith(('c', 'o')):
modfile = modfile[:-1]
# Normalize file names: on Windows, the case of file names of compiled
# modules depends on the path used to start the python executable.
modfile = normcase(modfile)
def revise(filename, *args):
return (normcase(filename),) + args
git = mod.StupidGit()
def tearDownModule():
if support.has_socket_support:
asyncio.set_event_loop_policy(None)
def signatures_with_lexicographic_keyword_only_parameters():
"""
Yields a whole bunch of functions with only keyword-only parameters,
where those parameters are always in lexicographically sorted order.
"""
parameters = ['a', 'bar', 'c', 'delta', 'ephraim', 'magical', 'yoyo', 'z']
for i in range(1, 2**len(parameters)):
p = []
bit = 1
for j in range(len(parameters)):
if i & (bit << j):
p.append(parameters[j])
fn_text = "def foo(*, " + ", ".join(p) + "): pass"
symbols = {}
exec(fn_text, symbols, symbols)
yield symbols['foo']
def unsorted_keyword_only_parameters_fn(*, throw, out, the, baby, with_,
the_, bathwater):
pass
unsorted_keyword_only_parameters = 'throw out the baby with_ the_ bathwater'.split()
class IsTestBase(unittest.TestCase):
predicates = set([inspect.isbuiltin, inspect.isclass, inspect.iscode,
inspect.isframe, inspect.isfunction, inspect.ismethod,
inspect.ismodule, inspect.istraceback,
inspect.isgenerator, inspect.isgeneratorfunction,
inspect.iscoroutine, inspect.iscoroutinefunction,
inspect.isasyncgen, inspect.isasyncgenfunction,
inspect.ismethodwrapper])
def istest(self, predicate, exp):
obj = eval(exp)
self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
for other in self.predicates - set([predicate]):
if (predicate == inspect.isgeneratorfunction or \
predicate == inspect.isasyncgenfunction or \
predicate == inspect.iscoroutinefunction) and \
other == inspect.isfunction:
continue
self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))
def test__all__(self):
support.check__all__(self, inspect, not_exported=("modulesbyfile",))
def generator_function_example(self):
for i in range(2):
yield i
async def async_generator_function_example(self):
async for i in range(2):
yield i
async def coroutine_function_example(self):
return 'spam'
@types.coroutine
def gen_coroutine_function_example(self):
yield
return 'spam'
def meth_noargs(): pass
def meth_o(object, /): pass
def meth_self_noargs(self, /): pass
def meth_self_o(self, object, /): pass
def meth_type_noargs(type, /): pass
def meth_type_o(type, object, /): pass
class TestPredicates(IsTestBase):
def test_excluding_predicates(self):
global tb
self.istest(inspect.isbuiltin, 'sys.exit')
self.istest(inspect.isbuiltin, '[].append')
self.istest(inspect.iscode, 'mod.spam.__code__')
try:
1/0
except Exception as e:
tb = e.__traceback__
self.istest(inspect.isframe, 'tb.tb_frame')
self.istest(inspect.istraceback, 'tb')
if hasattr(types, 'GetSetDescriptorType'):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
finally:
# Clear traceback and all the frames and local variables hanging to it.
tb = None
self.istest(inspect.isfunction, 'mod.spam')
self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
self.istest(inspect.ismethod, 'git.argue')
self.istest(inspect.ismethod, 'mod.custom_method')
self.istest(inspect.ismodule, 'mod')
self.istest(inspect.ismethoddescriptor, 'int.__add__')
self.istest(inspect.isdatadescriptor, 'collections.defaultdict.default_factory')
self.istest(inspect.isgenerator, '(x for x in range(2))')
self.istest(inspect.isgeneratorfunction, 'generator_function_example')
self.istest(inspect.isasyncgen,
'async_generator_function_example(1)')
self.istest(inspect.isasyncgenfunction,
'async_generator_function_example')
with warnings.catch_warnings():
warnings.simplefilter("ignore")
self.istest(inspect.iscoroutine, 'coroutine_function_example(1)')
self.istest(inspect.iscoroutinefunction, 'coroutine_function_example')
if hasattr(types, 'MemberDescriptorType'):
self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
else:
self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
self.istest(inspect.ismethodwrapper, "object().__str__")
self.istest(inspect.ismethodwrapper, "object().__eq__")
self.istest(inspect.ismethodwrapper, "object().__repr__")
self.assertFalse(inspect.ismethodwrapper(type))
self.assertFalse(inspect.ismethodwrapper(int))
self.assertFalse(inspect.ismethodwrapper(type("AnyClass", (), {})))
def test_iscoroutine(self):
async_gen_coro = async_generator_function_example(1)
gen_coro = gen_coroutine_function_example(1)
coro = coroutine_function_example(1)
class PMClass:
async_generator_partialmethod_example = functools.partialmethod(
async_generator_function_example)
coroutine_partialmethod_example = functools.partialmethod(
coroutine_function_example)
gen_coroutine_partialmethod_example = functools.partialmethod(
gen_coroutine_function_example)
# partialmethods on the class, bound to an instance
pm_instance = PMClass()
async_gen_coro_pmi = pm_instance.async_generator_partialmethod_example
gen_coro_pmi = pm_instance.gen_coroutine_partialmethod_example
coro_pmi = pm_instance.coroutine_partialmethod_example
# partialmethods on the class, unbound but accessed via the class
async_gen_coro_pmc = PMClass.async_generator_partialmethod_example
gen_coro_pmc = PMClass.gen_coroutine_partialmethod_example
coro_pmc = PMClass.coroutine_partialmethod_example
self.assertFalse(
inspect.iscoroutinefunction(gen_coroutine_function_example))
self.assertFalse(
inspect.iscoroutinefunction(
functools.partial(functools.partial(
gen_coroutine_function_example))))
self.assertFalse(inspect.iscoroutinefunction(gen_coro_pmi))
self.assertFalse(inspect.iscoroutinefunction(gen_coro_pmc))
self.assertFalse(inspect.iscoroutinefunction(inspect))
self.assertFalse(inspect.iscoroutine(gen_coro))
self.assertTrue(
inspect.isgeneratorfunction(gen_coroutine_function_example))
self.assertTrue(
inspect.isgeneratorfunction(
functools.partial(functools.partial(
gen_coroutine_function_example))))
self.assertTrue(inspect.isgeneratorfunction(gen_coro_pmi))
self.assertTrue(inspect.isgeneratorfunction(gen_coro_pmc))
self.assertTrue(inspect.isgenerator(gen_coro))
async def _fn3():
pass
@inspect.markcoroutinefunction
def fn3():
return _fn3()
self.assertTrue(inspect.iscoroutinefunction(fn3))
self.assertTrue(
inspect.iscoroutinefunction(
inspect.markcoroutinefunction(lambda: _fn3())
)
)
class Cl:
async def __call__(self):
pass
self.assertFalse(inspect.iscoroutinefunction(Cl))
# instances with async def __call__ are NOT recognised.
self.assertFalse(inspect.iscoroutinefunction(Cl()))
# unless explicitly marked.
self.assertTrue(inspect.iscoroutinefunction(
inspect.markcoroutinefunction(Cl())
))
class Cl2:
@inspect.markcoroutinefunction
def __call__(self):
pass
self.assertFalse(inspect.iscoroutinefunction(Cl2))
# instances with marked __call__ are NOT recognised.
self.assertFalse(inspect.iscoroutinefunction(Cl2()))
# unless explicitly marked.
self.assertTrue(inspect.iscoroutinefunction(
inspect.markcoroutinefunction(Cl2())
))
class Cl3:
@inspect.markcoroutinefunction
@classmethod
def do_something_classy(cls):
pass
@inspect.markcoroutinefunction
@staticmethod
def do_something_static():
pass
self.assertTrue(inspect.iscoroutinefunction(Cl3.do_something_classy))
self.assertTrue(inspect.iscoroutinefunction(Cl3.do_something_static))
self.assertFalse(
inspect.iscoroutinefunction(unittest.mock.Mock()))
self.assertTrue(
inspect.iscoroutinefunction(unittest.mock.AsyncMock()))
self.assertTrue(
inspect.iscoroutinefunction(coroutine_function_example))
self.assertTrue(
inspect.iscoroutinefunction(
functools.partial(functools.partial(
coroutine_function_example))))
self.assertTrue(inspect.iscoroutinefunction(coro_pmi))
self.assertTrue(inspect.iscoroutinefunction(coro_pmc))
self.assertTrue(inspect.iscoroutine(coro))
self.assertFalse(
inspect.isgeneratorfunction(unittest.mock.Mock()))
self.assertFalse(
inspect.isgeneratorfunction(unittest.mock.AsyncMock()))
self.assertFalse(
inspect.isgeneratorfunction(coroutine_function_example))
self.assertFalse(
inspect.isgeneratorfunction(
functools.partial(functools.partial(
coroutine_function_example))))
self.assertFalse(inspect.isgeneratorfunction(coro_pmi))
self.assertFalse(inspect.isgeneratorfunction(coro_pmc))
self.assertFalse(inspect.isgenerator(coro))
self.assertFalse(
inspect.isasyncgenfunction(unittest.mock.Mock()))
self.assertFalse(
inspect.isasyncgenfunction(unittest.mock.AsyncMock()))
self.assertFalse(
inspect.isasyncgenfunction(coroutine_function_example))
self.assertTrue(
inspect.isasyncgenfunction(async_generator_function_example))
self.assertTrue(
inspect.isasyncgenfunction(
functools.partial(functools.partial(
async_generator_function_example))))
self.assertTrue(inspect.isasyncgenfunction(async_gen_coro_pmi))
self.assertTrue(inspect.isasyncgenfunction(async_gen_coro_pmc))
self.assertTrue(inspect.isasyncgen(async_gen_coro))
coro.close(); gen_coro.close(); # silence warnings
def test_isawaitable(self):
def gen(): yield
self.assertFalse(inspect.isawaitable(gen()))
coro = coroutine_function_example(1)
gen_coro = gen_coroutine_function_example(1)
self.assertTrue(inspect.isawaitable(coro))
self.assertTrue(inspect.isawaitable(gen_coro))
class Future:
def __await__():
pass
self.assertTrue(inspect.isawaitable(Future()))
self.assertFalse(inspect.isawaitable(Future))
class NotFuture: pass
not_fut = NotFuture()
not_fut.__await__ = lambda: None
self.assertFalse(inspect.isawaitable(not_fut))
coro.close(); gen_coro.close() # silence warnings
def test_isroutine(self):
# method
self.assertTrue(inspect.isroutine(git.argue))
self.assertTrue(inspect.isroutine(mod.custom_method))
self.assertTrue(inspect.isroutine([].count))
# function
self.assertTrue(inspect.isroutine(mod.spam))
self.assertTrue(inspect.isroutine(mod.StupidGit.abuse))
# slot-wrapper
self.assertTrue(inspect.isroutine(object.__init__))
self.assertTrue(inspect.isroutine(object.__str__))
self.assertTrue(inspect.isroutine(object.__lt__))
self.assertTrue(inspect.isroutine(int.__lt__))
# method-wrapper
self.assertTrue(inspect.isroutine(object().__init__))
self.assertTrue(inspect.isroutine(object().__str__))
self.assertTrue(inspect.isroutine(object().__lt__))
self.assertTrue(inspect.isroutine((42).__lt__))
# method-descriptor
self.assertTrue(inspect.isroutine(str.join))
self.assertTrue(inspect.isroutine(list.append))
self.assertTrue(inspect.isroutine(''.join))
self.assertTrue(inspect.isroutine([].append))
# object
self.assertFalse(inspect.isroutine(object))
self.assertFalse(inspect.isroutine(object()))
self.assertFalse(inspect.isroutine(str()))
# module
self.assertFalse(inspect.isroutine(mod))
# type
self.assertFalse(inspect.isroutine(type))
self.assertFalse(inspect.isroutine(int))
self.assertFalse(inspect.isroutine(type('some_class', (), {})))
# partial
self.assertFalse(inspect.isroutine(functools.partial(mod.spam)))
def test_isroutine_singledispatch(self):
self.assertTrue(inspect.isroutine(functools.singledispatch(mod.spam)))
class A:
@functools.singledispatchmethod
def method(self, arg):
pass
@functools.singledispatchmethod
@classmethod
def class_method(cls, arg):
pass
@functools.singledispatchmethod
@staticmethod
def static_method(arg):
pass
self.assertTrue(inspect.isroutine(A.method))
self.assertTrue(inspect.isroutine(A().method))
self.assertTrue(inspect.isroutine(A.static_method))
self.assertTrue(inspect.isroutine(A.class_method))
def test_isclass(self):
self.istest(inspect.isclass, 'mod.StupidGit')
self.assertTrue(inspect.isclass(list))
class CustomGetattr(object):
def __getattr__(self, attr):
return None
self.assertFalse(inspect.isclass(CustomGetattr()))
def test_get_slot_members(self):
class C(object):
__slots__ = ("a", "b")
x = C()
x.a = 42
members = dict(inspect.getmembers(x))
self.assertIn('a', members)
self.assertNotIn('b', members)
def test_isabstract(self):
from abc import ABCMeta, abstractmethod
class AbstractClassExample(metaclass=ABCMeta):
@abstractmethod
def foo(self):
pass
class ClassExample(AbstractClassExample):
def foo(self):
pass
a = ClassExample()
# Test general behaviour.
self.assertTrue(inspect.isabstract(AbstractClassExample))
self.assertFalse(inspect.isabstract(ClassExample))
self.assertFalse(inspect.isabstract(a))
self.assertFalse(inspect.isabstract(int))
self.assertFalse(inspect.isabstract(5))
def test_isabstract_during_init_subclass(self):
from abc import ABCMeta, abstractmethod
isabstract_checks = []
class AbstractChecker(metaclass=ABCMeta):
def __init_subclass__(cls):
isabstract_checks.append(inspect.isabstract(cls))
class AbstractClassExample(AbstractChecker):
@abstractmethod
def foo(self):
pass
class ClassExample(AbstractClassExample):
def foo(self):
pass
self.assertEqual(isabstract_checks, [True, False])
isabstract_checks.clear()
class AbstractChild(AbstractClassExample):
pass
class AbstractGrandchild(AbstractChild):
pass
class ConcreteGrandchild(ClassExample):
pass
self.assertEqual(isabstract_checks, [True, True, False])
class TestInterpreterStack(IsTestBase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
git.abuse(7, 8, 9)
def test_abuse_done(self):
self.istest(inspect.istraceback, 'git.ex.__traceback__')
self.istest(inspect.isframe, 'mod.fr')
def test_stack(self):
self.assertTrue(len(mod.st) >= 5)
frame1, frame2, frame3, frame4, *_ = mod.st
frameinfo = revise(*frame1[1:])
self.assertEqual(frameinfo,
(modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0))
self.assertEqual(frame1.positions, dis.Positions(16, 16, 9, 24))
frameinfo = revise(*frame2[1:])
self.assertEqual(frameinfo,
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0))
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22))
frameinfo = revise(*frame3[1:])
self.assertEqual(frameinfo,
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0))
self.assertEqual(frame3.positions, dis.Positions(43, 43, 12, 25))
frameinfo = revise(*frame4[1:])
self.assertEqual(frameinfo,
(modfile, 39, 'abuse', [' self.argue(a, b, c)\n'], 0))
self.assertEqual(frame4.positions, dis.Positions(39, 39, 8, 27))
# Test named tuple fields
record = mod.st[0]
self.assertIs(record.frame, mod.fr)
self.assertEqual(record.lineno, 16)
self.assertEqual(record.filename, mod.__file__)
self.assertEqual(record.function, 'eggs')
self.assertIn('inspect.stack()', record.code_context[0])
self.assertEqual(record.index, 0)
def test_trace(self):
self.assertEqual(len(git.tr), 3)
frame1, frame2, frame3, = git.tr
self.assertEqual(revise(*frame1[1:]),
(modfile, 43, 'argue', [' spam(a, b, c)\n'], 0))
self.assertEqual(frame1.positions, dis.Positions(43, 43, 12, 25))
self.assertEqual(revise(*frame2[1:]),
(modfile, 9, 'spam', [' eggs(b + d, c + f)\n'], 0))
self.assertEqual(frame2.positions, dis.Positions(9, 9, 4, 22))
self.assertEqual(revise(*frame3[1:]),
(modfile, 18, 'eggs', [' q = y / 0\n'], 0))
self.assertEqual(frame3.positions, dis.Positions(18, 18, 8, 13))
def test_frame(self):
args, varargs, varkw, locals = inspect.getargvalues(mod.fr)
self.assertEqual(args, ['x', 'y'])
self.assertEqual(varargs, None)
self.assertEqual(varkw, None)
self.assertEqual(locals, {'x': 11, 'p': 11, 'y': 14})
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
'(x=11, y=14)')
def test_previous_frame(self):
args, varargs, varkw, locals = inspect.getargvalues(mod.fr.f_back)
self.assertEqual(args, ['a', 'b', 'c', 'd', 'e', 'f'])
self.assertEqual(varargs, 'g')
self.assertEqual(varkw, 'h')
self.assertEqual(inspect.formatargvalues(args, varargs, varkw, locals),
'(a=7, b=8, c=9, d=3, e=4, f=5, *g=(), **h={})')
class GetSourceBase(unittest.TestCase):
# Subclasses must override.
fodderModule = None
def setUp(self):
with open(inspect.getsourcefile(self.fodderModule), encoding="utf-8") as fp:
self.source = fp.read()
def sourcerange(self, top, bottom):
lines = self.source.split("\n")
return "\n".join(lines[top-1:bottom]) + ("\n" if bottom else "")
def assertSourceEqual(self, obj, top, bottom):
self.assertEqual(inspect.getsource(obj),
self.sourcerange(top, bottom))
class SlotUser:
'Docstrings for __slots__'
__slots__ = {'power': 'measured in kilowatts',
'distance': 'measured in kilometers'}
class TestRetrievingSourceCode(GetSourceBase):
fodderModule = mod
def test_getclasses(self):
classes = inspect.getmembers(mod, inspect.isclass)
self.assertEqual(classes,
[('FesteringGob', mod.FesteringGob),
('MalodorousPervert', mod.MalodorousPervert),
('ParrotDroppings', mod.ParrotDroppings),
('StupidGit', mod.StupidGit),
('Tit', mod.MalodorousPervert),
('WhichComments', mod.WhichComments),
])
tree = inspect.getclasstree([cls[1] for cls in classes])
self.assertEqual(tree,
[(object, ()),
[(mod.ParrotDroppings, (object,)),
[(mod.FesteringGob, (mod.MalodorousPervert,
mod.ParrotDroppings))
],
(mod.StupidGit, (object,)),
[(mod.MalodorousPervert, (mod.StupidGit,)),
[(mod.FesteringGob, (mod.MalodorousPervert,
mod.ParrotDroppings))
]
],
(mod.WhichComments, (object,),)
]
])
tree = inspect.getclasstree([cls[1] for cls in classes], True)
self.assertEqual(tree,
[(object, ()),
[(mod.ParrotDroppings, (object,)),
(mod.StupidGit, (object,)),
[(mod.MalodorousPervert, (mod.StupidGit,)),
[(mod.FesteringGob, (mod.MalodorousPervert,
mod.ParrotDroppings))
]
],
(mod.WhichComments, (object,),)
]
])
def test_getfunctions(self):
functions = inspect.getmembers(mod, inspect.isfunction)
self.assertEqual(functions, [('after_closing', mod.after_closing),
('eggs', mod.eggs),
('lobbest', mod.lobbest),
('spam', mod.spam)])
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_getdoc(self):
self.assertEqual(inspect.getdoc(mod), 'A module docstring.')
self.assertEqual(inspect.getdoc(mod.StupidGit),
'A longer,\n\nindented\n\ndocstring.')
self.assertEqual(inspect.getdoc(git.abuse),
'Another\n\ndocstring\n\ncontaining\n\ntabs')
self.assertEqual(inspect.getdoc(SlotUser.power),
'measured in kilowatts')
self.assertEqual(inspect.getdoc(SlotUser.distance),
'measured in kilometers')
@unittest.skipIf(sys.flags.optimize >= 2,
"Docstrings are omitted with -O2 and above")
def test_getdoc_inherited(self):
self.assertEqual(inspect.getdoc(mod.FesteringGob),
'A longer,\n\nindented\n\ndocstring.')
self.assertEqual(inspect.getdoc(mod.FesteringGob.abuse),
'Another\n\ndocstring\n\ncontaining\n\ntabs')
self.assertEqual(inspect.getdoc(mod.FesteringGob().abuse),
'Another\n\ndocstring\n\ncontaining\n\ntabs')
self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction),
'The automatic gainsaying.')
@unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings")
def test_finddoc(self):
finddoc = inspect._finddoc
self.assertEqual(finddoc(int), int.__doc__)
self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__)
self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__)
self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__)
self.assertEqual(finddoc(int.real), int.real.__doc__)
cleandoc_testdata = [
# first line should have different margin
(' An\n indented\n docstring.', 'An\nindented\n docstring.'),
# trailing whitespace are not removed.
(' An \n \n indented \n docstring. ',
'An \n \nindented \n docstring. '),
# NUL is not termination.
('doc\0string\n\n second\0line\n third\0line\0',
'doc\0string\n\nsecond\0line\nthird\0line\0'),
# first line is lstrip()-ped. other lines are kept when no margin.[w:
(' ', ''),
# compiler.cleandoc() doesn't strip leading/trailing newlines
# to keep maximum backward compatibility.
# inspect.cleandoc() removes them.
('\n\n\n first paragraph\n\n second paragraph\n\n',
'\n\n\nfirst paragraph\n\n second paragraph\n\n'),
(' \n \n \n ', '\n \n \n '),
]
def test_cleandoc(self):
func = inspect.cleandoc
for i, (input, expected) in enumerate(self.cleandoc_testdata):
# only inspect.cleandoc() strip \n
expected = expected.strip('\n')
with self.subTest(i=i):
self.assertEqual(func(input), expected)
@cpython_only
def test_c_cleandoc(self):
try:
import _testinternalcapi
except ImportError:
return unittest.skip("requires _testinternalcapi")
func = _testinternalcapi.compiler_cleandoc
for i, (input, expected) in enumerate(self.cleandoc_testdata):
with self.subTest(i=i):
self.assertEqual(func(input), expected)
def test_getcomments(self):
self.assertEqual(inspect.getcomments(mod), '# line 1\n')
self.assertEqual(inspect.getcomments(mod.StupidGit), '# line 20\n')
self.assertEqual(inspect.getcomments(mod2.cls160), '# line 159\n')
# If the object source file is not available, return None.
co = compile('x=1', '_non_existing_filename.py', 'exec')
self.assertIsNone(inspect.getcomments(co))
# If the object has been defined in C, return None.
self.assertIsNone(inspect.getcomments(list))
def test_getmodule(self):
# Check actual module
self.assertEqual(inspect.getmodule(mod), mod)
# Check class (uses __module__ attribute)
self.assertEqual(inspect.getmodule(mod.StupidGit), mod)
# Check a method (no __module__ attribute, falls back to filename)
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
# Do it again (check the caching isn't broken)
self.assertEqual(inspect.getmodule(mod.StupidGit.abuse), mod)
# Check a builtin
self.assertEqual(inspect.getmodule(str), sys.modules["builtins"])
# Check filename override
self.assertEqual(inspect.getmodule(None, modfile), mod)
def test_getmodule_file_not_found(self):
# See bpo-45406
def _getabsfile(obj, _filename):
raise FileNotFoundError('bad file')
with unittest.mock.patch('inspect.getabsfile', _getabsfile):
f = inspect.currentframe()
self.assertIsNone(inspect.getmodule(f))
inspect.getouterframes(f) # smoke test
def test_getframeinfo_get_first_line(self):
frame_info = inspect.getframeinfo(self.fodderModule.fr, 50)
self.assertEqual(frame_info.code_context[0], "# line 1\n")
self.assertEqual(frame_info.code_context[1], "'A module docstring.'\n")
def test_getsource(self):
self.assertSourceEqual(git.abuse, 29, 39)
self.assertSourceEqual(mod.StupidGit, 21, 51)
self.assertSourceEqual(mod.lobbest, 75, 76)
self.assertSourceEqual(mod.after_closing, 120, 120)
def test_getsourcefile(self):
self.assertEqual(normcase(inspect.getsourcefile(mod.spam)), modfile)
self.assertEqual(normcase(inspect.getsourcefile(git.abuse)), modfile)
fn = "_non_existing_filename_used_for_sourcefile_test.py"
co = compile("x=1", fn, "exec")
self.assertEqual(inspect.getsourcefile(co), None)
linecache.cache[co.co_filename] = (1, None, "None", co.co_filename)
try:
self.assertEqual(normcase(inspect.getsourcefile(co)), fn)
finally:
del linecache.cache[co.co_filename]
def test_getsource_empty_file(self):
with temp_cwd() as cwd:
with open('empty_file.py', 'w'):
pass
sys.path.insert(0, cwd)
try:
import empty_file
self.assertEqual(inspect.getsource(empty_file), '\n')
self.assertEqual(inspect.getsourcelines(empty_file), (['\n'], 0))
finally:
sys.path.remove(cwd)
def test_getfile(self):
self.assertEqual(inspect.getfile(mod.StupidGit), mod.__file__)
def test_getfile_builtin_module(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(sys)
self.assertTrue(str(e.exception).startswith('<module'))
def test_getfile_builtin_class(self):
with self.assertRaises(TypeError) as e:
inspect.getfile(int)
self.assertTrue(str(e.exception).startswith('<class'))
def test_getfile_builtin_function_or_method(self):
with self.assertRaises(TypeError) as e_abs:
inspect.getfile(abs)
self.assertIn('expected, got', str(e_abs.exception))
with self.assertRaises(TypeError) as e_append:
inspect.getfile(list.append)
self.assertIn('expected, got', str(e_append.exception))
@suppress_immortalization()
def test_getfile_class_without_module(self):
class CM(type):
@property
def __module__(cls):
raise AttributeError
class C(metaclass=CM):
pass
with self.assertRaises(TypeError):
inspect.getfile(C)
def test_getfile_broken_repr(self):
class ErrorRepr:
def __repr__(self):
raise Exception('xyz')
er = ErrorRepr()
with self.assertRaises(TypeError):
inspect.getfile(er)
def test_getmodule_recursion(self):
from types import ModuleType
name = '__inspect_dummy'
m = sys.modules[name] = ModuleType(name)
m.__file__ = "<string>" # hopefully not a real filename...
m.__loader__ = "dummy" # pretend the filename is understood by a loader
exec("def x(): pass", m.__dict__)
self.assertEqual(inspect.getsourcefile(m.x.__code__), '<string>')
del sys.modules[name]
inspect.getmodule(compile('a=10','','single'))
def test_proceed_with_fake_filename(self):
'''doctest monkeypatches linecache to enable inspection'''
fn, source = '<test>', 'def x(): pass\n'
getlines = linecache.getlines
def monkey(filename, module_globals=None):
if filename == fn:
return source.splitlines(keepends=True)
else:
return getlines(filename, module_globals)
linecache.getlines = monkey
try:
ns = {}
exec(compile(source, fn, 'single'), ns)
inspect.getsource(ns["x"])
finally:
linecache.getlines = getlines
def test_getsource_on_code_object(self):
self.assertSourceEqual(mod.eggs.__code__, 12, 18)
def test_getsource_on_generated_class(self):
A = type('A', (unittest.TestCase,), {})
self.assertEqual(inspect.getsourcefile(A), __file__)
self.assertEqual(inspect.getfile(A), __file__)
self.assertIs(inspect.getmodule(A), sys.modules[__name__])
self.assertRaises(OSError, inspect.getsource, A)
self.assertRaises(OSError, inspect.getsourcelines, A)
self.assertIsNone(inspect.getcomments(A))
def test_getsource_on_class_without_firstlineno(self):
__firstlineno__ = 1
class C:
nonlocal __firstlineno__
self.assertRaises(OSError, inspect.getsource, C)
class TestGetsourceStdlib(unittest.TestCase):
# Test Python implementations of the stdlib modules
def test_getsource_stdlib_collections_abc(self):
import collections.abc
lines, lineno = inspect.getsourcelines(collections.abc.Sequence)
self.assertEqual(lines[0], 'class Sequence(Reversible, Collection):\n')
src = inspect.getsource(collections.abc.Sequence)
self.assertEqual(src.splitlines(True), lines)
def test_getsource_stdlib_tomllib(self):
import tomllib
self.assertRaises(OSError, inspect.getsource, tomllib.TOMLDecodeError)
self.assertRaises(OSError, inspect.getsourcelines, tomllib.TOMLDecodeError)
def test_getsource_stdlib_abc(self):
# Pure Python implementation
abc = import_helper.import_fresh_module('abc', blocked=['_abc'])
with support.swap_item(sys.modules, 'abc', abc):
self.assertRaises(OSError, inspect.getsource, abc.ABCMeta)
self.assertRaises(OSError, inspect.getsourcelines, abc.ABCMeta)
# With C acceleration
import abc
try:
src = inspect.getsource(abc.ABCMeta)
lines, lineno = inspect.getsourcelines(abc.ABCMeta)
except OSError:
pass
else:
self.assertEqual(lines[0], ' class ABCMeta(type):\n')
self.assertEqual(src.splitlines(True), lines)
def test_getsource_stdlib_decimal(self):
# Pure Python implementation
decimal = import_helper.import_fresh_module('decimal', blocked=['_decimal'])
with support.swap_item(sys.modules, 'decimal', decimal):
src = inspect.getsource(decimal.Decimal)
lines, lineno = inspect.getsourcelines(decimal.Decimal)
self.assertEqual(lines[0], 'class Decimal(object):\n')
self.assertEqual(src.splitlines(True), lines)
class TestGetsourceInteractive(unittest.TestCase):
@support.force_not_colorized
def test_getclasses_interactive(self):
# bpo-44648: simulate a REPL session;
# there is no `__file__` in the __main__ module
code = "import sys, inspect; \
assert not hasattr(sys.modules['__main__'], '__file__'); \
A = type('A', (), {}); \
inspect.getsource(A)"
_, _, stderr = assert_python_failure("-c", code, __isolated=True)
self.assertIn(b'OSError: source code not available', stderr)
class TestGettingSourceOfToplevelFrames(GetSourceBase):
fodderModule = mod
def test_range_toplevel_frame(self):
self.maxDiff = None
self.assertSourceEqual(mod.currentframe, 1, None)
def test_range_traceback_toplevel_frame(self):
self.assertSourceEqual(mod.tb, 1, None)
class TestDecorators(GetSourceBase):
fodderModule = mod2
def test_wrapped_decorator(self):
self.assertSourceEqual(mod2.wrapped, 14, 17)
def test_replacing_decorator(self):
self.assertSourceEqual(mod2.gone, 9, 10)
def test_getsource_unwrap(self):
self.assertSourceEqual(mod2.real, 130, 132)
def test_decorator_with_lambda(self):
self.assertSourceEqual(mod2.func114, 113, 115)
class TestOneliners(GetSourceBase):
fodderModule = mod2
def test_oneline_lambda(self):
# Test inspect.getsource with a one-line lambda function.
self.assertSourceEqual(mod2.oll, 25, 25)
def test_threeline_lambda(self):
# Test inspect.getsource with a three-line lambda function,
# where the second and third lines are _not_ indented.
self.assertSourceEqual(mod2.tll, 28, 30)
def test_twoline_indented_lambda(self):
# Test inspect.getsource with a two-line lambda function,
# where the second line _is_ indented.
self.assertSourceEqual(mod2.tlli, 33, 34)
def test_parenthesized_multiline_lambda(self):
# Test inspect.getsource with a parenthesized multi-line lambda
# function.
self.assertSourceEqual(mod2.parenthesized_lambda, 279, 279)
self.assertSourceEqual(mod2.parenthesized_lambda2, 281, 281)
self.assertSourceEqual(mod2.parenthesized_lambda3, 283, 283)
def test_post_line_parenthesized_lambda(self):
# Test inspect.getsource with a parenthesized multi-line lambda
# function.
self.assertSourceEqual(mod2.post_line_parenthesized_lambda1, 286, 287)
def test_nested_lambda(self):
# Test inspect.getsource with a nested lambda function.
self.assertSourceEqual(mod2.nested_lambda, 291, 292)
def test_onelinefunc(self):
# Test inspect.getsource with a regular one-line function.
self.assertSourceEqual(mod2.onelinefunc, 37, 37)
def test_manyargs(self):
# Test inspect.getsource with a regular function where
# the arguments are on two lines and _not_ indented and
# the body on the second line with the last arguments.
self.assertSourceEqual(mod2.manyargs, 40, 41)
def test_twolinefunc(self):
# Test inspect.getsource with a regular function where
# the body is on two lines, following the argument list and
# continued on the next line by a \\.
self.assertSourceEqual(mod2.twolinefunc, 44, 45)
def test_lambda_in_list(self):
# Test inspect.getsource with a one-line lambda function
# defined in a list, indented.
self.assertSourceEqual(mod2.a[1], 49, 49)
def test_anonymous(self):
# Test inspect.getsource with a lambda function defined
# as argument to another function.
self.assertSourceEqual(mod2.anonymous, 55, 55)
def test_enum(self):
self.assertSourceEqual(mod2.enum322, 322, 323)
self.assertSourceEqual(mod2.enum326, 326, 327)
self.assertSourceEqual(mod2.flag330, 330, 331)
self.assertSourceEqual(mod2.flag334, 334, 335)
self.assertRaises(OSError, inspect.getsource, mod2.simple_enum338)
self.assertRaises(OSError, inspect.getsource, mod2.simple_enum339)
self.assertRaises(OSError, inspect.getsource, mod2.simple_flag340)
self.assertRaises(OSError, inspect.getsource, mod2.simple_flag341)
def test_namedtuple(self):
self.assertSourceEqual(mod2.nt346, 346, 348)
self.assertRaises(OSError, inspect.getsource, mod2.nt351)
def test_typeddict(self):
self.assertSourceEqual(mod2.td354, 354, 356)
self.assertRaises(OSError, inspect.getsource, mod2.td359)
def test_dataclass(self):
self.assertSourceEqual(mod2.dc364, 364, 367)
self.assertRaises(OSError, inspect.getsource, mod2.dc370)
self.assertRaises(OSError, inspect.getsource, mod2.dc371)
class TestBlockComments(GetSourceBase):
fodderModule = mod
def test_toplevel_class(self):
self.assertSourceEqual(mod.WhichComments, 96, 114)
def test_class_method(self):
self.assertSourceEqual(mod.WhichComments.f, 99, 104)
def test_class_async_method(self):
self.assertSourceEqual(mod.WhichComments.asyncf, 109, 112)
class TestBuggyCases(GetSourceBase):
fodderModule = mod2
def test_with_comment(self):
self.assertSourceEqual(mod2.with_comment, 58, 59)
def test_multiline_sig(self):
self.assertSourceEqual(mod2.multiline_sig[0], 63, 64)
def test_nested_class(self):
self.assertSourceEqual(mod2.func69().func71, 71, 72)
def test_one_liner_followed_by_non_name(self):
self.assertSourceEqual(mod2.func77, 77, 77)
def test_one_liner_dedent_non_name(self):
self.assertSourceEqual(mod2.cls82.func83, 83, 83)
def test_with_comment_instead_of_docstring(self):
self.assertSourceEqual(mod2.func88, 88, 90)
def test_method_in_dynamic_class(self):
self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
# This should not skip for CPython, but might on a repackaged python where
# unicodedata is not an external module, or on pypy.
@unittest.skipIf(not hasattr(unicodedata, '__file__') or
unicodedata.__file__.endswith('.py'),
"unicodedata is not an external binary module")
def test_findsource_binary(self):
self.assertRaises(OSError, inspect.getsource, unicodedata)
self.assertRaises(OSError, inspect.findsource, unicodedata)
def test_findsource_code_in_linecache(self):
lines = ["x=1"]
co = compile(lines[0], "_dynamically_created_file", "exec")
self.assertRaises(OSError, inspect.findsource, co)
self.assertRaises(OSError, inspect.getsource, co)
linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
try:
self.assertEqual(inspect.findsource(co), (lines,0))
self.assertEqual(inspect.getsource(co), lines[0])
finally:
del linecache.cache[co.co_filename]
def test_findsource_without_filename(self):
for fname in ['', '<string>']:
co = compile('x=1', fname, "exec")
self.assertRaises(IOError, inspect.findsource, co)
self.assertRaises(IOError, inspect.getsource, co)
def test_findsource_on_func_with_out_of_bounds_lineno(self):
mod_len = len(inspect.getsource(mod))
src = '\n' * 2* mod_len + "def f(): pass"
co = compile(src, mod.__file__, "exec")
g, l = {}, {}
eval(co, g, l)
func = l['f']
self.assertEqual(func.__code__.co_firstlineno, 1+2*mod_len)
with self.assertRaisesRegex(OSError, "lineno is out of bounds"):
inspect.findsource(func)
def test_findsource_on_class_with_out_of_bounds_lineno(self):
mod_len = len(inspect.getsource(mod))
src = '\n' * 2* mod_len + "class A: pass"
co = compile(src, mod.__file__, "exec")
g, l = {'__name__': mod.__name__}, {}
eval(co, g, l)
cls = l['A']
self.assertEqual(cls.__firstlineno__, 1+2*mod_len)
with self.assertRaisesRegex(OSError, "lineno is out of bounds"):
inspect.findsource(cls)
def test_getsource_on_method(self):
self.assertSourceEqual(mod2.ClassWithMethod.method, 118, 119)
def test_getsource_on_class_code_object(self):
self.assertSourceEqual(mod2.ClassWithCodeObject.code, 315, 317)
def test_nested_func(self):
self.assertSourceEqual(mod2.cls135.func136, 136, 139)
def test_class_definition_in_multiline_string_definition(self):
self.assertSourceEqual(mod2.cls149, 149, 152)
def test_class_definition_in_multiline_comment(self):
self.assertSourceEqual(mod2.cls160, 160, 163)
def test_nested_class_definition_indented_string(self):
self.assertSourceEqual(mod2.cls173.cls175, 175, 176)
def test_nested_class_definition(self):
self.assertSourceEqual(mod2.cls183, 183, 188)
self.assertSourceEqual(mod2.cls183.cls185, 185, 188)
def test_class_decorator(self):
self.assertSourceEqual(mod2.cls196, 194, 201)
self.assertSourceEqual(mod2.cls196.cls200, 198, 201)
@support.requires_docstrings
def test_class_inside_conditional(self):
# We skip this test when docstrings are not present,
# because docstrings are one of the main factors of
# finding the correct class in the source code.
self.assertSourceEqual(mod2.cls238.cls239, 239, 240)
def test_multiple_children_classes(self):
self.assertSourceEqual(mod2.cls203, 203, 209)
self.assertSourceEqual(mod2.cls203.cls204, 204, 206)
self.assertSourceEqual(mod2.cls203.cls204.cls205, 205, 206)
self.assertSourceEqual(mod2.cls203.cls207, 207, 209)
self.assertSourceEqual(mod2.cls203.cls207.cls205, 208, 209)
def test_nested_class_definition_inside_function(self):
self.assertSourceEqual(mod2.func212(), 213, 214)
self.assertSourceEqual(mod2.cls213, 218, 222)
self.assertSourceEqual(mod2.cls213().func219(), 220, 221)
def test_class_with_method_from_other_module(self):
with tempfile.TemporaryDirectory() as tempdir:
with open(os.path.join(tempdir, 'inspect_actual%spy' % os.extsep),
'w', encoding='utf-8') as f:
f.write(textwrap.dedent("""
import inspect_other
class A:
def f(self):
pass
class A:
def f(self):
pass # correct one
A.f = inspect_other.A.f
"""))
with open(os.path.join(tempdir, 'inspect_other%spy' % os.extsep),
'w', encoding='utf-8') as f:
f.write(textwrap.dedent("""
class A:
def f(self):
pass
"""))
with DirsOnSysPath(tempdir):
import inspect_actual
self.assertIn("correct", inspect.getsource(inspect_actual.A))
# Remove the module from sys.modules to force it to be reloaded.
# This is necessary when the test is run multiple times.
sys.modules.pop("inspect_actual")
@unittest.skipIf(
support.is_emscripten or support.is_wasi,
"socket.accept is broken"
)
def test_nested_class_definition_inside_async_function(self):
import asyncio
self.addCleanup(asyncio.set_event_loop_policy, None)
self.assertSourceEqual(asyncio.run(mod2.func225()), 226, 227)
self.assertSourceEqual(mod2.cls226, 231, 235)
self.assertSourceEqual(asyncio.run(mod2.cls226().func232()), 233, 234)
def test_class_definition_same_name_diff_methods(self):
self.assertSourceEqual(mod2.cls296, 296, 298)
self.assertSourceEqual(mod2.cls310, 310, 312)
class TestNoEOL(GetSourceBase):
def setUp(self):
self.tempdir = TESTFN + '_dir'
os.mkdir(self.tempdir)
with open(os.path.join(self.tempdir, 'inspect_fodder3%spy' % os.extsep),
'w', encoding='utf-8') as f:
f.write("class X:\n pass # No EOL")
with DirsOnSysPath(self.tempdir):
import inspect_fodder3 as mod3
self.fodderModule = mod3
super().setUp()
def tearDown(self):
shutil.rmtree(self.tempdir)
def test_class(self):
self.assertSourceEqual(self.fodderModule.X, 1, 2)
class TestComplexDecorator(GetSourceBase):
fodderModule = mod2
def test_parens_in_decorator(self):
self.assertSourceEqual(self.fodderModule.complex_decorated, 273, 275)
class _BrokenDataDescriptor(object):
"""
A broken data descriptor. See bug #1785.
"""
def __get__(*args):
raise AttributeError("broken data descriptor")
def __set__(*args):
raise RuntimeError
def __getattr__(*args):
raise AttributeError("broken data descriptor")
class _BrokenMethodDescriptor(object):
"""
A broken method descriptor. See bug #1785.
"""
def __get__(*args):
raise AttributeError("broken method descriptor")
def __getattr__(*args):
raise AttributeError("broken method descriptor")
# Helper for testing classify_class_attrs.
def attrs_wo_objs(cls):
return [t[:3] for t in inspect.classify_class_attrs(cls)]
class TestClassesAndFunctions(unittest.TestCase):
def test_newstyle_mro(self):
# The same w/ new-class MRO.
class A(object): pass
class B(A): pass
class C(A): pass
class D(B, C): pass
expected = (D, B, C, A, object)
got = inspect.getmro(D)
self.assertEqual(expected, got)
def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None,
varkw_e=None, defaults_e=None,
posonlyargs_e=[], kwonlyargs_e=[],
kwonlydefaults_e=None,
ann_e={}):
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
inspect.getfullargspec(routine)
self.assertEqual(args, args_e)
self.assertEqual(varargs, varargs_e)
self.assertEqual(varkw, varkw_e)
self.assertEqual(defaults, defaults_e)
self.assertEqual(kwonlyargs, kwonlyargs_e)
self.assertEqual(kwonlydefaults, kwonlydefaults_e)
self.assertEqual(ann, ann_e)
def test_getfullargspec(self):
self.assertFullArgSpecEquals(mod2.keyworded, [], varargs_e='arg1',
kwonlyargs_e=['arg2'],
kwonlydefaults_e={'arg2':1})
self.assertFullArgSpecEquals(mod2.annotated, ['arg1'],
ann_e={'arg1' : list})
self.assertFullArgSpecEquals(mod2.keyword_only_arg, [],
kwonlyargs_e=['arg'])
self.assertFullArgSpecEquals(mod2.all_markers, ['a', 'b', 'c', 'd'],
kwonlyargs_e=['e', 'f'])
self.assertFullArgSpecEquals(mod2.all_markers_with_args_and_kwargs,
['a', 'b', 'c', 'd'],
varargs_e='args',
varkw_e='kwargs',
kwonlyargs_e=['e', 'f'])
self.assertFullArgSpecEquals(mod2.all_markers_with_defaults, ['a', 'b', 'c', 'd'],
defaults_e=(1,2,3),
kwonlyargs_e=['e', 'f'],
kwonlydefaults_e={'e': 4, 'f': 5})
def test_argspec_api_ignores_wrapped(self):
# Issue 20684: low level introspection API must ignore __wrapped__
@functools.wraps(mod.spam)
def ham(x, y):
pass
# Basic check
self.assertFullArgSpecEquals(ham, ['x', 'y'])
self.assertFullArgSpecEquals(functools.partial(ham),
['x', 'y'])
def test_getfullargspec_signature_attr(self):
def test():
pass
spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY)
test.__signature__ = inspect.Signature(parameters=(spam_param,))
self.assertFullArgSpecEquals(test, ['spam'])
def test_getfullargspec_signature_annos(self):
def test(a:'spam') -> 'ham': pass
spec = inspect.getfullargspec(test)
self.assertEqual(test.__annotations__, spec.annotations)
def test(): pass
spec = inspect.getfullargspec(test)
self.assertEqual(test.__annotations__, spec.annotations)
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_getfullargspec_builtin_methods(self):
self.assertFullArgSpecEquals(_pickle.Pickler.dump, ['self', 'obj'])
self.assertFullArgSpecEquals(_pickle.Pickler(io.BytesIO()).dump, ['self', 'obj'])
self.assertFullArgSpecEquals(
os.stat,
args_e=['path'],
kwonlyargs_e=['dir_fd', 'follow_symlinks'],
kwonlydefaults_e={'dir_fd': None, 'follow_symlinks': True})
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_getfullargspec_builtin_func(self):
_testcapi = import_helper.import_module("_testcapi")
builtin = _testcapi.docstring_with_signature_with_defaults
spec = inspect.getfullargspec(builtin)
self.assertEqual(spec.defaults[0], 'avocado')
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_getfullargspec_builtin_func_no_signature(self):
_testcapi = import_helper.import_module("_testcapi")
builtin = _testcapi.docstring_no_signature
with self.assertRaises(TypeError):
inspect.getfullargspec(builtin)
cls = _testcapi.DocStringNoSignatureTest
obj = _testcapi.DocStringNoSignatureTest()
tests = [
(_testcapi.docstring_no_signature_noargs, meth_noargs),
(_testcapi.docstring_no_signature_o, meth_o),
(cls.meth_noargs, meth_self_noargs),
(cls.meth_o, meth_self_o),
(obj.meth_noargs, meth_self_noargs),
(obj.meth_o, meth_self_o),
(cls.meth_noargs_class, meth_type_noargs),
(cls.meth_o_class, meth_type_o),
(cls.meth_noargs_static, meth_noargs),
(cls.meth_o_static, meth_o),
(cls.meth_noargs_coexist, meth_self_noargs),
(cls.meth_o_coexist, meth_self_o),
(time.time, meth_noargs),
(str.lower, meth_self_noargs),
(''.lower, meth_self_noargs),
(set.add, meth_self_o),
(set().add, meth_self_o),
(set.__contains__, meth_self_o),
(set().__contains__, meth_self_o),
(datetime.datetime.__dict__['utcnow'], meth_type_noargs),
(datetime.datetime.utcnow, meth_type_noargs),
(dict.__dict__['__class_getitem__'], meth_type_o),
(dict.__class_getitem__, meth_type_o),
]
try:
import _stat
except ImportError:
# if the _stat extension is not available, stat.S_IMODE() is
# implemented in Python, not in C
pass
else:
tests.append((stat.S_IMODE, meth_o))
for builtin, template in tests:
with self.subTest(builtin):
self.assertEqual(inspect.getfullargspec(builtin),
inspect.getfullargspec(template))
def test_getfullargspec_definition_order_preserved_on_kwonly(self):
for fn in signatures_with_lexicographic_keyword_only_parameters():
signature = inspect.getfullargspec(fn)
l = list(signature.kwonlyargs)
sorted_l = sorted(l)
self.assertTrue(l)
self.assertEqual(l, sorted_l)
signature = inspect.getfullargspec(unsorted_keyword_only_parameters_fn)
l = list(signature.kwonlyargs)
self.assertEqual(l, unsorted_keyword_only_parameters)
def test_classify_newstyle(self):
class A(object):
def s(): pass
s = staticmethod(s)
def c(cls): pass
c = classmethod(c)
def getp(self): pass
p = property(getp)
def m(self): pass
def m1(self): pass
datablob = '1'
dd = _BrokenDataDescriptor()
md = _BrokenMethodDescriptor()
attrs = attrs_wo_objs(A)
self.assertIn(('__new__', 'static method', object), attrs,
'missing __new__')
self.assertIn(('__init__', 'method', object), attrs, 'missing __init__')
self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertIn(('m', 'method', A), attrs,
'missing plain method: %r' % attrs)
self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
class B(A):
def m(self): pass
attrs = attrs_wo_objs(B)
self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertIn(('m', 'method', B), attrs, 'missing plain method')
self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
class C(A):
def m(self): pass
def c(self): pass
attrs = attrs_wo_objs(C)
self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertIn(('c', 'method', C), attrs, 'missing plain method')
self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertIn(('m', 'method', C), attrs, 'missing plain method')
self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
class D(B, C):
def m1(self): pass
attrs = attrs_wo_objs(D)
self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertIn(('c', 'method', C), attrs, 'missing plain method')
self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertIn(('m', 'method', B), attrs, 'missing plain method')
self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
self.assertIn(('datablob', 'data', A), attrs, 'missing data')
self.assertIn(('md', 'method', A), attrs, 'missing method descriptor')
self.assertIn(('dd', 'data', A), attrs, 'missing data descriptor')
def test_classify_builtin_types(self):
# Simple sanity check that all built-in types can have their
# attributes classified.
for name in dir(__builtins__):
builtin = getattr(__builtins__, name)
if isinstance(builtin, type):
inspect.classify_class_attrs(builtin)
attrs = attrs_wo_objs(bool)
self.assertIn(('__new__', 'static method', bool), attrs,
'missing __new__')
self.assertIn(('from_bytes', 'class method', int), attrs,
'missing class method')
self.assertIn(('to_bytes', 'method', int), attrs,
'missing plain method')
self.assertIn(('__add__', 'method', int), attrs,
'missing plain method')
self.assertIn(('__and__', 'method', bool), attrs,
'missing plain method')
def test_classify_DynamicClassAttribute(self):
class Meta(type):
def __getattr__(self, name):
if name == 'ham':
return 'spam'
return super().__getattr__(name)
class VA(metaclass=Meta):
@types.DynamicClassAttribute
def ham(self):
return 'eggs'
should_find_dca = inspect.Attribute('ham', 'data', VA, VA.__dict__['ham'])
self.assertIn(should_find_dca, inspect.classify_class_attrs(VA))
should_find_ga = inspect.Attribute('ham', 'data', Meta, 'spam')
self.assertIn(should_find_ga, inspect.classify_class_attrs(VA))
def test_classify_overrides_bool(self):
class NoBool(object):
def __eq__(self, other):
return NoBool()
def __bool__(self):
raise NotImplementedError(
"This object does not specify a boolean value")
class HasNB(object):
dd = NoBool()
should_find_attr = inspect.Attribute('dd', 'data', HasNB, HasNB.dd)
self.assertIn(should_find_attr, inspect.classify_class_attrs(HasNB))
def test_classify_metaclass_class_attribute(self):
class Meta(type):
fish = 'slap'
def __dir__(self):
return ['__class__', '__module__', '__name__', 'fish']
class Class(metaclass=Meta):
pass
should_find = inspect.Attribute('fish', 'data', Meta, 'slap')
self.assertIn(should_find, inspect.classify_class_attrs(Class))
def test_classify_VirtualAttribute(self):
class Meta(type):
def __dir__(cls):
return ['__class__', '__module__', '__name__', 'BOOM']
def __getattr__(self, name):
if name =='BOOM':
return 42
return super().__getattr(name)
class Class(metaclass=Meta):
pass
should_find = inspect.Attribute('BOOM', 'data', Meta, 42)
self.assertIn(should_find, inspect.classify_class_attrs(Class))
def test_classify_VirtualAttribute_multi_classes(self):
class Meta1(type):
def __dir__(cls):
return ['__class__', '__module__', '__name__', 'one']
def __getattr__(self, name):
if name =='one':
return 1
return super().__getattr__(name)
class Meta2(type):
def __dir__(cls):
return ['__class__', '__module__', '__name__', 'two']
def __getattr__(self, name):
if name =='two':
return 2
return super().__getattr__(name)
class Meta3(Meta1, Meta2):
def __dir__(cls):
return list(sorted(set(['__class__', '__module__', '__name__', 'three'] +
Meta1.__dir__(cls) + Meta2.__dir__(cls))))
def __getattr__(self, name):
if name =='three':
return 3
return super().__getattr__(name)
class Class1(metaclass=Meta1):
pass
class Class2(Class1, metaclass=Meta3):
pass
should_find1 = inspect.Attribute('one', 'data', Meta1, 1)
should_find2 = inspect.Attribute('two', 'data', Meta2, 2)
should_find3 = inspect.Attribute('three', 'data', Meta3, 3)
cca = inspect.classify_class_attrs(Class2)
for sf in (should_find1, should_find2, should_find3):
self.assertIn(sf, cca)
def test_classify_class_attrs_with_buggy_dir(self):
class M(type):
def __dir__(cls):
return ['__class__', '__name__', 'missing']
class C(metaclass=M):
pass
attrs = [a[0] for a in inspect.classify_class_attrs(C)]
self.assertNotIn('missing', attrs)
def test_getmembers_descriptors(self):
class A(object):
dd = _BrokenDataDescriptor()
md = _BrokenMethodDescriptor()
def pred_wrapper(pred):
# A quick'n'dirty way to discard standard attributes of new-style
# classes.
class Empty(object):
pass
def wrapped(x):
if '__name__' in dir(x) and hasattr(Empty, x.__name__):
return False
return pred(x)
return wrapped
ismethoddescriptor = pred_wrapper(inspect.ismethoddescriptor)
isdatadescriptor = pred_wrapper(inspect.isdatadescriptor)
self.assertEqual(inspect.getmembers(A, ismethoddescriptor),
[('md', A.__dict__['md'])])
self.assertEqual(inspect.getmembers(A, isdatadescriptor),
[('dd', A.__dict__['dd'])])
class B(A):
pass
self.assertEqual(inspect.getmembers(B, ismethoddescriptor),
[('md', A.__dict__['md'])])
self.assertEqual(inspect.getmembers(B, isdatadescriptor),
[('dd', A.__dict__['dd'])])
def test_getmembers_method(self):
class B:
def f(self):
pass
self.assertIn(('f', B.f), inspect.getmembers(B))
self.assertNotIn(('f', B.f), inspect.getmembers(B, inspect.ismethod))
b = B()
self.assertIn(('f', b.f), inspect.getmembers(b))
self.assertIn(('f', b.f), inspect.getmembers(b, inspect.ismethod))
def test_getmembers_custom_dir(self):
class CorrectDir:
def __init__(self, attr):
self.attr = attr
def method(self):
return self.attr + 1
def __dir__(self):
return ['attr', 'method']
cd = CorrectDir(5)
self.assertEqual(inspect.getmembers(cd), [
('attr', 5),
('method', cd.method),
])
self.assertEqual(inspect.getmembers(cd, inspect.ismethod), [
('method', cd.method),
])
def test_getmembers_custom_broken_dir(self):
# inspect.getmembers calls `dir()` on the passed object inside.
# if `__dir__` mentions some non-existent attribute,
# we still need to return others correctly.
class BrokenDir:
existing = 1
def method(self):
return self.existing + 1
def __dir__(self):
return ['method', 'missing', 'existing']
bd = BrokenDir()
self.assertEqual(inspect.getmembers(bd), [
('existing', 1),
('method', bd.method),
])
self.assertEqual(inspect.getmembers(bd, inspect.ismethod), [
('method', bd.method),
])
def test_getmembers_custom_duplicated_dir(self):
# Duplicates in `__dir__` must not fail and return just one result.
class DuplicatedDir:
attr = 1
def __dir__(self):
return ['attr', 'attr']
dd = DuplicatedDir()
self.assertEqual(inspect.getmembers(dd), [
('attr', 1),
])
def test_getmembers_VirtualAttribute(self):
class M(type):
def __getattr__(cls, name):
if name == 'eggs':
return 'scrambled'
return super().__getattr__(name)
class A(metaclass=M):
@types.DynamicClassAttribute
def eggs(self):
return 'spam'
class B:
def __getattr__(self, attribute):
return None
self.assertIn(('eggs', 'scrambled'), inspect.getmembers(A))
self.assertIn(('eggs', 'spam'), inspect.getmembers(A()))
b = B()
self.assertIn(('__getattr__', b.__getattr__), inspect.getmembers(b))
def test_getmembers_static(self):
class A:
@property
def name(self):
raise NotImplementedError
@types.DynamicClassAttribute
def eggs(self):
raise NotImplementedError
a = A()
instance_members = inspect.getmembers_static(a)
class_members = inspect.getmembers_static(A)
self.assertIn(('name', inspect.getattr_static(a, 'name')), instance_members)
self.assertIn(('eggs', inspect.getattr_static(a, 'eggs')), instance_members)
self.assertIn(('name', inspect.getattr_static(A, 'name')), class_members)
self.assertIn(('eggs', inspect.getattr_static(A, 'eggs')), class_members)
def test_getmembers_with_buggy_dir(self):
class M(type):
def __dir__(cls):
return ['__class__', '__name__', 'missing']
class C(metaclass=M):
pass
attrs = [a[0] for a in inspect.getmembers(C)]
self.assertNotIn('missing', attrs)
def test_get_annotations_with_stock_annotations(self):
def foo(a:int, b:str): pass
self.assertEqual(inspect.get_annotations(foo), {'a': int, 'b': str})
foo.__annotations__ = {'a': 'foo', 'b':'str'}
self.assertEqual(inspect.get_annotations(foo), {'a': 'foo', 'b': 'str'})
self.assertEqual(inspect.get_annotations(foo, eval_str=True, locals=locals()), {'a': foo, 'b': str})
self.assertEqual(inspect.get_annotations(foo, eval_str=True, globals=locals()), {'a': foo, 'b': str})
isa = inspect_stock_annotations
self.assertEqual(inspect.get_annotations(isa), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.MyClass), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.function), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function2), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function3), {'a': 'int', 'b': 'str', 'c': 'MyClass'})
self.assertEqual(inspect.get_annotations(inspect), {}) # inspect module has no annotations
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass), {})
self.assertEqual(inspect.get_annotations(isa.unannotated_function), {})
self.assertEqual(inspect.get_annotations(isa, eval_str=True), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=True), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.function, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=True), {'a': int, 'b': str, 'c': isa.MyClass, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=True), {'a': int, 'b': str, 'c': isa.MyClass})
self.assertEqual(inspect.get_annotations(inspect, eval_str=True), {})
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=True), {})
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=True), {})
self.assertEqual(inspect.get_annotations(isa, eval_str=False), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=False), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.function, eval_str=False), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=False), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=False), {'a': 'int', 'b': 'str', 'c': 'MyClass'})
self.assertEqual(inspect.get_annotations(inspect, eval_str=False), {})
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=False), {})
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=False), {})
def times_three(fn):
@functools.wraps(fn)
def wrapper(a, b):
return fn(a*3, b*3)
return wrapper
wrapped = times_three(isa.function)
self.assertEqual(wrapped(1, 'x'), isa.MyClass(3, 'xxx'))
self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
self.assertEqual(inspect.get_annotations(wrapped), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(wrapped, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(wrapped, eval_str=False), {'a': int, 'b': str, 'return': isa.MyClass})
def test_get_annotations_with_stringized_annotations(self):
isa = inspect_stringized_annotations
self.assertEqual(inspect.get_annotations(isa), {'a': 'int', 'b': 'str'})
self.assertEqual(inspect.get_annotations(isa.MyClass), {'a': 'int', 'b': 'str'})
self.assertEqual(inspect.get_annotations(isa.function), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
self.assertEqual(inspect.get_annotations(isa.function2), {'a': 'int', 'b': "'str'", 'c': 'MyClass', 'return': 'MyClass'})
self.assertEqual(inspect.get_annotations(isa.function3), {'a': "'int'", 'b': "'str'", 'c': "'MyClass'"})
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass), {})
self.assertEqual(inspect.get_annotations(isa.unannotated_function), {})
self.assertEqual(inspect.get_annotations(isa, eval_str=True), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=True), {'a': int, 'b': str})
self.assertEqual(inspect.get_annotations(isa.function, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=True), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=True), {'a': 'int', 'b': 'str', 'c': 'MyClass'})
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=True), {})
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=True), {})
self.assertEqual(inspect.get_annotations(isa, eval_str=False), {'a': 'int', 'b': 'str'})
self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=False), {'a': 'int', 'b': 'str'})
self.assertEqual(inspect.get_annotations(isa.function, eval_str=False), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
self.assertEqual(inspect.get_annotations(isa.function2, eval_str=False), {'a': 'int', 'b': "'str'", 'c': 'MyClass', 'return': 'MyClass'})
self.assertEqual(inspect.get_annotations(isa.function3, eval_str=False), {'a': "'int'", 'b': "'str'", 'c': "'MyClass'"})
self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=False), {})
self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=False), {})
isa2 = inspect_stringized_annotations_2
self.assertEqual(inspect.get_annotations(isa2), {})
self.assertEqual(inspect.get_annotations(isa2, eval_str=True), {})
self.assertEqual(inspect.get_annotations(isa2, eval_str=False), {})
def times_three(fn):
@functools.wraps(fn)
def wrapper(a, b):
return fn(a*3, b*3)
return wrapper
wrapped = times_three(isa.function)
self.assertEqual(wrapped(1, 'x'), isa.MyClass(3, 'xxx'))
self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
self.assertEqual(inspect.get_annotations(wrapped), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
self.assertEqual(inspect.get_annotations(wrapped, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
self.assertEqual(inspect.get_annotations(wrapped, eval_str=False), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
# test that local namespace lookups work
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations), {'x': 'mytype'})
self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True), {'x': int})
def test_pep695_generic_class_with_future_annotations(self):
ann_module695 = inspect_stringized_annotations_pep695
A_annotations = inspect.get_annotations(ann_module695.A, eval_str=True)
A_type_params = ann_module695.A.__type_params__
self.assertIs(A_annotations["x"], A_type_params[0])
self.assertEqual(A_annotations["y"].__args__[0], Unpack[A_type_params[1]])
self.assertIs(A_annotations["z"].__args__[0], A_type_params[2])
def test_pep695_generic_class_with_future_annotations_and_local_shadowing(self):
B_annotations = inspect.get_annotations(
inspect_stringized_annotations_pep695.B, eval_str=True
)
self.assertEqual(B_annotations, {"x": int, "y": str, "z": bytes})
def test_pep695_generic_class_with_future_annotations_name_clash_with_global_vars(self):
ann_module695 = inspect_stringized_annotations_pep695
C_annotations = inspect.get_annotations(ann_module695.C, eval_str=True)
self.assertEqual(
set(C_annotations.values()),
set(ann_module695.C.__type_params__)
)
def test_pep_695_generic_function_with_future_annotations(self):
ann_module695 = inspect_stringized_annotations_pep695
generic_func_annotations = inspect.get_annotations(
ann_module695.generic_function, eval_str=True
)
func_t_params = ann_module695.generic_function.__type_params__
self.assertEqual(
generic_func_annotations.keys(), {"x", "y", "z", "zz", "return"}
)
self.assertIs(generic_func_annotations["x"], func_t_params[0])
self.assertEqual(generic_func_annotations["y"], Unpack[func_t_params[1]])
self.assertIs(generic_func_annotations["z"].__origin__, func_t_params[2])
self.assertIs(generic_func_annotations["zz"].__origin__, func_t_params[2])
def test_pep_695_generic_function_with_future_annotations_name_clash_with_global_vars(self):
self.assertEqual(
set(
inspect.get_annotations(
inspect_stringized_annotations_pep695.generic_function_2,
eval_str=True
).values()
),
set(
inspect_stringized_annotations_pep695.generic_function_2.__type_params__
)
)
def test_pep_695_generic_method_with_future_annotations(self):
ann_module695 = inspect_stringized_annotations_pep695
generic_method_annotations = inspect.get_annotations(
ann_module695.D.generic_method, eval_str=True
)
params = {
param.__name__: param
for param in ann_module695.D.generic_method.__type_params__
}
self.assertEqual(
generic_method_annotations,
{"x": params["Foo"], "y": params["Bar"], "return": None}
)
def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_vars(self):
self.assertEqual(
set(
inspect.get_annotations(
inspect_stringized_annotations_pep695.D.generic_method_2,
eval_str=True
).values()
),
set(
inspect_stringized_annotations_pep695.D.generic_method_2.__type_params__
)
)
def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_and_local_vars(self):
self.assertEqual(
inspect.get_annotations(
inspect_stringized_annotations_pep695.E, eval_str=True
),
{"x": str},
)
def test_pep_695_generics_with_future_annotations_nested_in_function(self):
results = inspect_stringized_annotations_pep695.nested()
self.assertEqual(
set(results.F_annotations.values()),
set(results.F.__type_params__)
)
self.assertEqual(
set(results.F_meth_annotations.values()),
set(results.F.generic_method.__type_params__)
)
self.assertNotEqual(
set(results.F_meth_annotations.values()),
set(results.F.__type_params__)
)
self.assertEqual(
set(results.F_meth_annotations.values()).intersection(results.F.__type_params__),
set()
)
self.assertEqual(results.G_annotations, {"x": str})
self.assertEqual(
set(results.generic_func_annotations.values()),
set(results.generic_func.__type_params__)
)
class TestFormatAnnotation(unittest.TestCase):
def test_typing_replacement(self):
from test.typinganndata.ann_module9 import ann, ann1
self.assertEqual(inspect.formatannotation(ann), 'Union[List[str], int]')
self.assertEqual(inspect.formatannotation(ann1), 'Union[List[testModule.typing.A], int]')
class TestIsMethodDescriptor(unittest.TestCase):
def test_custom_descriptors(self):
class MethodDescriptor:
def __get__(self, *_): pass
class MethodDescriptorSub(MethodDescriptor):
pass
class DataDescriptorWithNoGet:
def __set__(self, *_): pass
class DataDescriptorWithGetSet:
def __get__(self, *_): pass
def __set__(self, *_): pass
class DataDescriptorWithGetDelete:
def __get__(self, *_): pass
def __delete__(self, *_): pass
class DataDescriptorSub(DataDescriptorWithNoGet,
DataDescriptorWithGetDelete):
pass
# Custom method descriptors:
self.assertTrue(
inspect.ismethoddescriptor(MethodDescriptor()),
'__get__ and no __set__/__delete__ => method descriptor')
self.assertTrue(
inspect.ismethoddescriptor(MethodDescriptorSub()),
'__get__ (inherited) and no __set__/__delete__'
' => method descriptor')
# Custom data descriptors:
self.assertFalse(
inspect.ismethoddescriptor(DataDescriptorWithNoGet()),
'__set__ (and no __get__) => not a method descriptor')
self.assertFalse(
inspect.ismethoddescriptor(DataDescriptorWithGetSet()),
'__get__ and __set__ => not a method descriptor')
self.assertFalse(
inspect.ismethoddescriptor(DataDescriptorWithGetDelete()),
'__get__ and __delete__ => not a method descriptor')
self.assertFalse(
inspect.ismethoddescriptor(DataDescriptorSub()),
'__get__, __set__ and __delete__ => not a method descriptor')
# Classes of descriptors (are *not* descriptors themselves):
self.assertFalse(inspect.ismethoddescriptor(MethodDescriptor))
self.assertFalse(inspect.ismethoddescriptor(MethodDescriptorSub))
self.assertFalse(inspect.ismethoddescriptor(DataDescriptorSub))
def test_builtin_descriptors(self):
builtin_slot_wrapper = int.__add__ # This one is mentioned in docs.
class Owner:
def instance_method(self): pass
@classmethod
def class_method(cls): pass
@staticmethod
def static_method(): pass
@property
def a_property(self): pass
class Slotermeyer:
__slots__ = 'a_slot',
def function():
pass
a_lambda = lambda: None
# Example builtin method descriptors:
self.assertTrue(
inspect.ismethoddescriptor(builtin_slot_wrapper),
'a builtin slot wrapper is a method descriptor')
self.assertTrue(
inspect.ismethoddescriptor(Owner.__dict__['class_method']),
'a classmethod object is a method descriptor')
self.assertTrue(
inspect.ismethoddescriptor(Owner.__dict__['static_method']),
'a staticmethod object is a method descriptor')
# Example builtin data descriptors:
self.assertFalse(
inspect.ismethoddescriptor(Owner.__dict__['a_property']),
'a property is not a method descriptor')
self.assertFalse(
inspect.ismethoddescriptor(Slotermeyer.__dict__['a_slot']),
'a slot is not a method descriptor')
# `types.MethodType`/`types.FunctionType` instances (they *are*
# method descriptors, but `ismethoddescriptor()` explicitly
# excludes them):
self.assertFalse(inspect.ismethoddescriptor(Owner().instance_method))
self.assertFalse(inspect.ismethoddescriptor(Owner().class_method))
self.assertFalse(inspect.ismethoddescriptor(Owner().static_method))
self.assertFalse(inspect.ismethoddescriptor(Owner.instance_method))
self.assertFalse(inspect.ismethoddescriptor(Owner.class_method))
self.assertFalse(inspect.ismethoddescriptor(Owner.static_method))
self.assertFalse(inspect.ismethoddescriptor(function))
self.assertFalse(inspect.ismethoddescriptor(a_lambda))
self.assertFalse(inspect.ismethoddescriptor(functools.partial(function)))
def test_descriptor_being_a_class(self):
class MethodDescriptorMeta(type):
def __get__(self, *_): pass
class ClassBeingMethodDescriptor(metaclass=MethodDescriptorMeta):
pass
# `ClassBeingMethodDescriptor` itself *is* a method descriptor,
# but it is *also* a class, and `ismethoddescriptor()` explicitly
# excludes classes.
self.assertFalse(
inspect.ismethoddescriptor(ClassBeingMethodDescriptor),
'classes (instances of type) are explicitly excluded')
def test_non_descriptors(self):
class Test:
pass
self.assertFalse(inspect.ismethoddescriptor(Test()))
self.assertFalse(inspect.ismethoddescriptor(Test))
self.assertFalse(inspect.ismethoddescriptor([42]))
self.assertFalse(inspect.ismethoddescriptor(42))
class TestIsDataDescriptor(unittest.TestCase):
def test_custom_descriptors(self):
class NonDataDescriptor:
def __get__(self, value, type=None): pass
class DataDescriptor0:
def __set__(self, name, value): pass
class DataDescriptor1:
def __delete__(self, name): pass
class DataDescriptor2:
__set__ = None
self.assertFalse(inspect.isdatadescriptor(NonDataDescriptor()),
'class with only __get__ not a data descriptor')
self.assertTrue(inspect.isdatadescriptor(DataDescriptor0()),
'class with __set__ is a data descriptor')
self.assertTrue(inspect.isdatadescriptor(DataDescriptor1()),
'class with __delete__ is a data descriptor')
self.assertTrue(inspect.isdatadescriptor(DataDescriptor2()),
'class with __set__ = None is a data descriptor')
def test_slot(self):
class Slotted:
__slots__ = 'foo',
self.assertTrue(inspect.isdatadescriptor(Slotted.foo),
'a slot is a data descriptor')
def test_property(self):
class Propertied:
@property
def a_property(self):
pass
self.assertTrue(inspect.isdatadescriptor(Propertied.a_property),
'a property is a data descriptor')
def test_functions(self):
class Test(object):
def instance_method(self): pass
@classmethod
def class_method(cls): pass
@staticmethod
def static_method(): pass
def function():
pass
a_lambda = lambda: None
self.assertFalse(inspect.isdatadescriptor(Test().instance_method),
'a instance method is not a data descriptor')
self.assertFalse(inspect.isdatadescriptor(Test().class_method),
'a class method is not a data descriptor')
self.assertFalse(inspect.isdatadescriptor(Test().static_method),
'a static method is not a data descriptor')
self.assertFalse(inspect.isdatadescriptor(function),
'a function is not a data descriptor')
self.assertFalse(inspect.isdatadescriptor(a_lambda),
'a lambda is not a data descriptor')
_global_ref = object()
class TestGetClosureVars(unittest.TestCase):
def test_name_resolution(self):
# Basic test of the 4 different resolution mechanisms
def f(nonlocal_ref):
def g(local_ref):
print(local_ref, nonlocal_ref, _global_ref, unbound_ref)
return g
_arg = object()
nonlocal_vars = {"nonlocal_ref": _arg}
global_vars = {"_global_ref": _global_ref}
builtin_vars = {"print": print}
unbound_names = {"unbound_ref"}
expected = inspect.ClosureVars(nonlocal_vars, global_vars,
builtin_vars, unbound_names)
self.assertEqual(inspect.getclosurevars(f(_arg)), expected)
def test_generator_closure(self):
def f(nonlocal_ref):
def g(local_ref):
print(local_ref, nonlocal_ref, _global_ref, unbound_ref)
yield
return g
_arg = object()
nonlocal_vars = {"nonlocal_ref": _arg}
global_vars = {"_global_ref": _global_ref}
builtin_vars = {"print": print}
unbound_names = {"unbound_ref"}
expected = inspect.ClosureVars(nonlocal_vars, global_vars,
builtin_vars, unbound_names)
self.assertEqual(inspect.getclosurevars(f(_arg)), expected)
def test_method_closure(self):
class C:
def f(self, nonlocal_ref):
def g(local_ref):
print(local_ref, nonlocal_ref, _global_ref, unbound_ref)
return g
_arg = object()
nonlocal_vars = {"nonlocal_ref": _arg}
global_vars = {"_global_ref": _global_ref}
builtin_vars = {"print": print}
unbound_names = {"unbound_ref"}
expected = inspect.ClosureVars(nonlocal_vars, global_vars,
builtin_vars, unbound_names)
self.assertEqual(inspect.getclosurevars(C().f(_arg)), expected)
def test_attribute_same_name_as_global_var(self):
class C:
_global_ref = object()
def f():
print(C._global_ref, _global_ref)
nonlocal_vars = {"C": C}
global_vars = {"_global_ref": _global_ref}
builtin_vars = {"print": print}
unbound_names = {"_global_ref"}
expected = inspect.ClosureVars(nonlocal_vars, global_vars,
builtin_vars, unbound_names)
self.assertEqual(inspect.getclosurevars(f), expected)
def test_nonlocal_vars(self):
# More complex tests of nonlocal resolution
def _nonlocal_vars(f):
return inspect.getclosurevars(f).nonlocals
def make_adder(x):
def add(y):
return x + y
return add
def curry(func, arg1):
return lambda arg2: func(arg1, arg2)
def less_than(a, b):
return a < b
# The infamous Y combinator.
def Y(le):
def g(f):
return le(lambda x: f(f)(x))
Y.g_ref = g
return g(g)
def check_y_combinator(func):
self.assertEqual(_nonlocal_vars(func), {'f': Y.g_ref})
inc = make_adder(1)
add_two = make_adder(2)
greater_than_five = curry(less_than, 5)
self.assertEqual(_nonlocal_vars(inc), {'x': 1})
self.assertEqual(_nonlocal_vars(add_two), {'x': 2})
self.assertEqual(_nonlocal_vars(greater_than_five),
{'arg1': 5, 'func': less_than})
self.assertEqual(_nonlocal_vars((lambda x: lambda y: x + y)(3)),
{'x': 3})
Y(check_y_combinator)
def test_getclosurevars_empty(self):
def foo(): pass
_empty = inspect.ClosureVars({}, {}, {}, set())
self.assertEqual(inspect.getclosurevars(lambda: True), _empty)
self.assertEqual(inspect.getclosurevars(foo), _empty)
def test_getclosurevars_error(self):
class T: pass
self.assertRaises(TypeError, inspect.getclosurevars, 1)
self.assertRaises(TypeError, inspect.getclosurevars, list)
self.assertRaises(TypeError, inspect.getclosurevars, {})
def _private_globals(self):
code = """def f(): print(path)"""
ns = {}
exec(code, ns)
return ns["f"], ns
def test_builtins_fallback(self):
f, ns = self._private_globals()
ns.pop("__builtins__", None)
expected = inspect.ClosureVars({}, {}, {"print":print}, {"path"})
self.assertEqual(inspect.getclosurevars(f), expected)
def test_builtins_as_dict(self):
f, ns = self._private_globals()
ns["__builtins__"] = {"path":1}
expected = inspect.ClosureVars({}, {}, {"path":1}, {"print"})
self.assertEqual(inspect.getclosurevars(f), expected)
def test_builtins_as_module(self):
f, ns = self._private_globals()
ns["__builtins__"] = os
expected = inspect.ClosureVars({}, {}, {"path":os.path}, {"print"})
self.assertEqual(inspect.getclosurevars(f), expected)
class TestGetcallargsFunctions(unittest.TestCase):
def assertEqualCallArgs(self, func, call_params_string, locs=None):
locs = dict(locs or {}, func=func)
r1 = eval('func(%s)' % call_params_string, None, locs)
r2 = eval('inspect.getcallargs(func, %s)' % call_params_string, None,
locs)
self.assertEqual(r1, r2)
def assertEqualException(self, func, call_param_string, locs=None):
locs = dict(locs or {}, func=func)
try:
eval('func(%s)' % call_param_string, None, locs)
except Exception as e:
ex1 = e
else:
self.fail('Exception not raised')
try:
eval('inspect.getcallargs(func, %s)' % call_param_string, None,
locs)
except Exception as e:
ex2 = e
else:
self.fail('Exception not raised')
self.assertIs(type(ex1), type(ex2))
self.assertEqual(str(ex1), str(ex2))
del ex1, ex2
def makeCallable(self, signature):
"""Create a function that returns its locals()"""
code = "lambda %s: locals()"
return eval(code % signature)
def test_plain(self):
f = self.makeCallable('a, b=1')
self.assertEqualCallArgs(f, '2')
self.assertEqualCallArgs(f, '2, 3')
self.assertEqualCallArgs(f, 'a=2')
self.assertEqualCallArgs(f, 'b=3, a=2')
self.assertEqualCallArgs(f, '2, b=3')
# expand *iterable / **mapping
self.assertEqualCallArgs(f, '*(2,)')
self.assertEqualCallArgs(f, '*[2]')
self.assertEqualCallArgs(f, '*(2, 3)')
self.assertEqualCallArgs(f, '*[2, 3]')
self.assertEqualCallArgs(f, '**{"a":2}')
self.assertEqualCallArgs(f, 'b=3, **{"a":2}')
self.assertEqualCallArgs(f, '2, **{"b":3}')
self.assertEqualCallArgs(f, '**{"b":3, "a":2}')
# expand UserList / UserDict
self.assertEqualCallArgs(f, '*collections.UserList([2])')
self.assertEqualCallArgs(f, '*collections.UserList([2, 3])')
self.assertEqualCallArgs(f, '**collections.UserDict(a=2)')
self.assertEqualCallArgs(f, '2, **collections.UserDict(b=3)')
self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3)')
def test_varargs(self):
f = self.makeCallable('a, b=1, *c')
self.assertEqualCallArgs(f, '2')
self.assertEqualCallArgs(f, '2, 3')
self.assertEqualCallArgs(f, '2, 3, 4')
self.assertEqualCallArgs(f, '*(2,3,4)')
self.assertEqualCallArgs(f, '2, *[3,4]')
self.assertEqualCallArgs(f, '2, 3, *collections.UserList([4])')
def test_varkw(self):
f = self.makeCallable('a, b=1, **c')
self.assertEqualCallArgs(f, 'a=2')
self.assertEqualCallArgs(f, '2, b=3, c=4')
self.assertEqualCallArgs(f, 'b=3, a=2, c=4')
self.assertEqualCallArgs(f, 'c=4, **{"a":2, "b":3}')
self.assertEqualCallArgs(f, '2, c=4, **{"b":3}')
self.assertEqualCallArgs(f, 'b=2, **{"a":3, "c":4}')
self.assertEqualCallArgs(f, '**collections.UserDict(a=2, b=3, c=4)')
self.assertEqualCallArgs(f, '2, c=4, **collections.UserDict(b=3)')
self.assertEqualCallArgs(f, 'b=2, **collections.UserDict(a=3, c=4)')
def test_varkw_only(self):
# issue11256:
f = self.makeCallable('**c')
self.assertEqualCallArgs(f, '')
self.assertEqualCallArgs(f, 'a=1')
self.assertEqualCallArgs(f, 'a=1, b=2')
self.assertEqualCallArgs(f, 'c=3, **{"a": 1, "b": 2}')
self.assertEqualCallArgs(f, '**collections.UserDict(a=1, b=2)')
self.assertEqualCallArgs(f, 'c=3, **collections.UserDict(a=1, b=2)')
def test_keyword_only(self):
f = self.makeCallable('a=3, *, c, d=2')
self.assertEqualCallArgs(f, 'c=3')
self.assertEqualCallArgs(f, 'c=3, a=3')
self.assertEqualCallArgs(f, 'a=2, c=4')
self.assertEqualCallArgs(f, '4, c=4')
self.assertEqualException(f, '')
self.assertEqualException(f, '3')
self.assertEqualException(f, 'a=3')
self.assertEqualException(f, 'd=4')
f = self.makeCallable('*, c, d=2')
self.assertEqualCallArgs(f, 'c=3')
self.assertEqualCallArgs(f, 'c=3, d=4')
self.assertEqualCallArgs(f, 'd=4, c=3')
def test_multiple_features(self):
f = self.makeCallable('a, b=2, *f, **g')
self.assertEqualCallArgs(f, '2, 3, 7')
self.assertEqualCallArgs(f, '2, 3, x=8')
self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9')
self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9')
self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
'[2, 3, (4,[5,6])]), **{"y":9, "z":10}')
self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
'(4,[5,6])]), **collections.UserDict('
'y=9, z=10)')
f = self.makeCallable('a, b=2, *f, x, y=99, **g')
self.assertEqualCallArgs(f, '2, 3, x=8')
self.assertEqualCallArgs(f, '2, 3, x=8, *[(4,[5,6]), 7]')
self.assertEqualCallArgs(f, '2, x=8, *[3, (4,[5,6]), 7], y=9, z=10')
self.assertEqualCallArgs(f, 'x=8, *[2, 3, (4,[5,6])], y=9, z=10')
self.assertEqualCallArgs(f, 'x=8, *collections.UserList('
'[2, 3, (4,[5,6])]), q=0, **{"y":9, "z":10}')
self.assertEqualCallArgs(f, '2, x=8, *collections.UserList([3, '
'(4,[5,6])]), q=0, **collections.UserDict('
'y=9, z=10)')
def test_errors(self):
f0 = self.makeCallable('')
f1 = self.makeCallable('a, b')
f2 = self.makeCallable('a, b=1')
# f0 takes no arguments
self.assertEqualException(f0, '1')
self.assertEqualException(f0, 'x=1')
self.assertEqualException(f0, '1,x=1')
# f1 takes exactly 2 arguments
self.assertEqualException(f1, '')
self.assertEqualException(f1, '1')
self.assertEqualException(f1, 'a=2')
self.assertEqualException(f1, 'b=3')
# f2 takes at least 1 argument
self.assertEqualException(f2, '')
self.assertEqualException(f2, 'b=3')
for f in f1, f2:
# f1/f2 takes exactly/at most 2 arguments
self.assertEqualException(f, '2, 3, 4')
self.assertEqualException(f, '1, 2, 3, a=1')
self.assertEqualException(f, '2, 3, 4, c=5')
self.assertEqualException(f, '2, 3, 4, a=1, c=5')
# f got an unexpected keyword argument
self.assertEqualException(f, 'c=2')
self.assertEqualException(f, '2, c=3')
self.assertEqualException(f, '2, 3, c=4')
self.assertEqualException(f, '2, c=4, b=3')
self.assertEqualException(f, '**{u"\u03c0\u03b9": 4}')
# f got multiple values for keyword argument
self.assertEqualException(f, '1, a=2')
self.assertEqualException(f, '1, **{"a":2}')
self.assertEqualException(f, '1, 2, b=3')
self.assertEqualException(f, '1, c=3, a=2')
# issue11256:
f3 = self.makeCallable('**c')
self.assertEqualException(f3, '1, 2')
self.assertEqualException(f3, '1, 2, a=1, b=2')
f4 = self.makeCallable('*, a, b=0')
self.assertEqualException(f4, '1, 2')
self.assertEqualException(f4, '1, 2, a=1, b=2')
self.assertEqualException(f4, 'a=1, a=3')
self.assertEqualException(f4, 'a=1, c=3')
self.assertEqualException(f4, 'a=1, a=3, b=4')
self.assertEqualException(f4, 'a=1, b=2, a=3, b=4')
self.assertEqualException(f4, 'a=1, a=2, a=3, b=4')
# issue #20816: getcallargs() fails to iterate over non-existent
# kwonlydefaults and raises a wrong TypeError
def f5(*, a): pass
with self.assertRaisesRegex(TypeError,
'missing 1 required keyword-only'):
inspect.getcallargs(f5)
# issue20817:
def f6(a, b, c):
pass
with self.assertRaisesRegex(TypeError, "'a', 'b' and 'c'"):
inspect.getcallargs(f6)
# bpo-33197
with self.assertRaisesRegex(ValueError,
'variadic keyword parameters cannot'
' have default values'):
inspect.Parameter("foo", kind=inspect.Parameter.VAR_KEYWORD,
default=42)
with self.assertRaisesRegex(ValueError,
"value 5 is not a valid Parameter.kind"):
inspect.Parameter("bar", kind=5, default=42)
with self.assertRaisesRegex(TypeError,
'name must be a str, not a int'):
inspect.Parameter(123, kind=4)
class TestGetcallargsMethods(TestGetcallargsFunctions):
def setUp(self):
class Foo(object):
pass
self.cls = Foo
self.inst = Foo()
def makeCallable(self, signature):
assert 'self' not in signature
mk = super(TestGetcallargsMethods, self).makeCallable
self.cls.method = mk('self, ' + signature)
return self.inst.method
class TestGetcallargsUnboundMethods(TestGetcallargsMethods):
def makeCallable(self, signature):
super(TestGetcallargsUnboundMethods, self).makeCallable(signature)
return self.cls.method
def assertEqualCallArgs(self, func, call_params_string, locs=None):
return super(TestGetcallargsUnboundMethods, self).assertEqualCallArgs(
*self._getAssertEqualParams(func, call_params_string, locs))
def assertEqualException(self, func, call_params_string, locs=None):
return super(TestGetcallargsUnboundMethods, self).assertEqualException(
*self._getAssertEqualParams(func, call_params_string, locs))
def _getAssertEqualParams(self, func, call_params_string, locs=None):
assert 'inst' not in call_params_string
locs = dict(locs or {}, inst=self.inst)
return (func, 'inst,' + call_params_string, locs)
class TestGetattrStatic(unittest.TestCase):
def test_basic(self):
class Thing(object):
x = object()
thing = Thing()
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
self.assertEqual(inspect.getattr_static(thing, 'x', None), Thing.x)
with self.assertRaises(AttributeError):
inspect.getattr_static(thing, 'y')
self.assertEqual(inspect.getattr_static(thing, 'y', 3), 3)
def test_inherited(self):
class Thing(object):
x = object()
class OtherThing(Thing):
pass
something = OtherThing()
self.assertEqual(inspect.getattr_static(something, 'x'), Thing.x)
def test_instance_attr(self):
class Thing(object):
x = 2
def __init__(self, x):
self.x = x
thing = Thing(3)
self.assertEqual(inspect.getattr_static(thing, 'x'), 3)
del thing.x
self.assertEqual(inspect.getattr_static(thing, 'x'), 2)
def test_property(self):
class Thing(object):
@property
def x(self):
raise AttributeError("I'm pretending not to exist")
thing = Thing()
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
def test_descriptor_raises_AttributeError(self):
class descriptor(object):
def __get__(*_):
raise AttributeError("I'm pretending not to exist")
desc = descriptor()
class Thing(object):
x = desc
thing = Thing()
self.assertEqual(inspect.getattr_static(thing, 'x'), desc)
def test_classAttribute(self):
class Thing(object):
x = object()
self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.x)
def test_classVirtualAttribute(self):
class Thing(object):
@types.DynamicClassAttribute
def x(self):
return self._x
_x = object()
self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.__dict__['x'])
def test_inherited_classattribute(self):
class Thing(object):
x = object()
class OtherThing(Thing):
pass
self.assertEqual(inspect.getattr_static(OtherThing, 'x'), Thing.x)
def test_slots(self):
class Thing(object):
y = 'bar'
__slots__ = ['x']
def __init__(self):
self.x = 'foo'
thing = Thing()
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
self.assertEqual(inspect.getattr_static(thing, 'y'), 'bar')
del thing.x
self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
def test_metaclass(self):
class meta(type):
attr = 'foo'
class Thing(object, metaclass=meta):
pass
self.assertEqual(inspect.getattr_static(Thing, 'attr'), 'foo')
class sub(meta):
pass
class OtherThing(object, metaclass=sub):
x = 3
self.assertEqual(inspect.getattr_static(OtherThing, 'attr'), 'foo')
class OtherOtherThing(OtherThing):
pass
# this test is odd, but it was added as it exposed a bug
self.assertEqual(inspect.getattr_static(OtherOtherThing, 'x'), 3)
def test_no_dict_no_slots(self):
self.assertEqual(inspect.getattr_static(1, 'foo', None), None)
self.assertNotEqual(inspect.getattr_static('foo', 'lower'), None)
def test_no_dict_no_slots_instance_member(self):
# returns descriptor
with open(__file__, encoding='utf-8') as handle:
self.assertEqual(inspect.getattr_static(handle, 'name'), type(handle).name)
def test_inherited_slots(self):
# returns descriptor
class Thing(object):
__slots__ = ['x']
def __init__(self):
self.x = 'foo'
class OtherThing(Thing):
pass
# it would be nice if this worked...
# we get the descriptor instead of the instance attribute
self.assertEqual(inspect.getattr_static(OtherThing(), 'x'), Thing.x)
def test_descriptor(self):
class descriptor(object):
def __get__(self, instance, owner):
return 3
class Foo(object):
d = descriptor()
foo = Foo()
# for a non data descriptor we return the instance attribute
foo.__dict__['d'] = 1
self.assertEqual(inspect.getattr_static(foo, 'd'), 1)
# if the descriptor is a data-descriptor we should return the
# descriptor
descriptor.__set__ = lambda s, i, v: None
self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d'])
del descriptor.__set__
descriptor.__delete__ = lambda s, i, o: None
self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d'])
def test_metaclass_with_descriptor(self):
class descriptor(object):
def __get__(self, instance, owner):
return 3
class meta(type):
d = descriptor()
class Thing(object, metaclass=meta):
pass
self.assertEqual(inspect.getattr_static(Thing, 'd'), meta.__dict__['d'])
def test_class_as_property(self):
class Base(object):
foo = 3
class Something(Base):
executed = False
@property
def __class__(self):
self.executed = True
return object
instance = Something()
self.assertEqual(inspect.getattr_static(instance, 'foo'), 3)
self.assertFalse(instance.executed)
self.assertEqual(inspect.getattr_static(Something, 'foo'), 3)
def test_mro_as_property(self):
class Meta(type):
@property
def __mro__(self):
return (object,)
class Base(object):
foo = 3
class Something(Base, metaclass=Meta):
pass
self.assertEqual(inspect.getattr_static(Something(), 'foo'), 3)
self.assertEqual(inspect.getattr_static(Something, 'foo'), 3)
def test_dict_as_property(self):
test = self
test.called = False
class Foo(dict):
a = 3
@property
def __dict__(self):
test.called = True
return {}
foo = Foo()
foo.a = 4
self.assertEqual(inspect.getattr_static(foo, 'a'), 3)
self.assertFalse(test.called)
class Bar(Foo): pass
bar = Bar()
bar.a = 5
self.assertEqual(inspect.getattr_static(bar, 'a'), 3)
self.assertFalse(test.called)
def test_mutated_mro(self):
test = self
test.called = False
class Foo(dict):
a = 3
@property
def __dict__(self):
test.called = True
return {}
class Bar(dict):
a = 4
class Baz(Bar): pass
baz = Baz()
self.assertEqual(inspect.getattr_static(baz, 'a'), 4)
Baz.__bases__ = (Foo,)
self.assertEqual(inspect.getattr_static(baz, 'a'), 3)
self.assertFalse(test.called)
def test_custom_object_dict(self):
test = self
test.called = False
class Custom(dict):
def get(self, key, default=None):
test.called = True
super().get(key, default)
class Foo(object):
a = 3
foo = Foo()
foo.__dict__ = Custom()
self.assertEqual(inspect.getattr_static(foo, 'a'), 3)
self.assertFalse(test.called)
def test_metaclass_dict_as_property(self):
class Meta(type):
@property
def __dict__(self):
self.executed = True
class Thing(metaclass=Meta):
executed = False
def __init__(self):
self.spam = 42
instance = Thing()
self.assertEqual(inspect.getattr_static(instance, "spam"), 42)
self.assertFalse(Thing.executed)
def test_module(self):
sentinel = object()
self.assertIsNot(inspect.getattr_static(sys, "version", sentinel),
sentinel)
def test_metaclass_with_metaclass_with_dict_as_property(self):
class MetaMeta(type):
@property
def __dict__(self):
self.executed = True
return dict(spam=42)
class Meta(type, metaclass=MetaMeta):
executed = False
class Thing(metaclass=Meta):
pass
with self.assertRaises(AttributeError):
inspect.getattr_static(Thing, "spam")
self.assertFalse(Thing.executed)
def test_custom___getattr__(self):
test = self
test.called = False
class Foo:
def __getattr__(self, attr):
test.called = True
return {}
with self.assertRaises(AttributeError):
inspect.getattr_static(Foo(), 'whatever')
self.assertFalse(test.called)
def test_custom___getattribute__(self):
test = self
test.called = False
class Foo:
def __getattribute__(self, attr):
test.called = True
return {}
with self.assertRaises(AttributeError):
inspect.getattr_static(Foo(), 'really_could_be_anything')
self.assertFalse(test.called)
@suppress_immortalization()
def test_cache_does_not_cause_classes_to_persist(self):
# regression test for gh-118013:
# check that the internal _shadowed_dict cache does not cause
# dynamically created classes to have extended lifetimes even
# when no other strong references to those classes remain.
# Since these classes can themselves hold strong references to
# other objects, this can cause unexpected memory consumption.
class Foo: pass
Foo.instance = Foo()
weakref_to_class = weakref.ref(Foo)
inspect.getattr_static(Foo.instance, 'whatever', 'irrelevant')
del Foo
gc.collect()
self.assertIsNone(weakref_to_class())
class TestGetGeneratorState(unittest.TestCase):
def setUp(self):
def number_generator():
for number in range(5):
yield number
self.generator = number_generator()
def _generatorstate(self):
return inspect.getgeneratorstate(self.generator)
def test_created(self):
self.assertEqual(self._generatorstate(), inspect.GEN_CREATED)
def test_suspended(self):
next(self.generator)
self.assertEqual(self._generatorstate(), inspect.GEN_SUSPENDED)
def test_closed_after_exhaustion(self):
for i in self.generator:
pass
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED)
def test_closed_after_immediate_exception(self):
with self.assertRaises(RuntimeError):
self.generator.throw(RuntimeError)
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED)
def test_closed_after_close(self):
self.generator.close()
self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED)
def test_running(self):
# As mentioned on issue #10220, checking for the RUNNING state only
# makes sense inside the generator itself.
# The following generator checks for this by using the closure's
# reference to self and the generator state checking helper method
def running_check_generator():
for number in range(5):
self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING)
yield number
self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING)
self.generator = running_check_generator()
# Running up to the first yield
next(self.generator)
# Running after the first yield
next(self.generator)
def test_easy_debugging(self):
# repr() and str() of a generator state should contain the state name
names = 'GEN_CREATED GEN_RUNNING GEN_SUSPENDED GEN_CLOSED'.split()
for name in names:
state = getattr(inspect, name)
self.assertIn(name, repr(state))
self.assertIn(name, str(state))
def test_getgeneratorlocals(self):
def each(lst, a=None):
b=(1, 2, 3)
for v in lst:
if v == 3:
c = 12
yield v
numbers = each([1, 2, 3])
self.assertEqual(inspect.getgeneratorlocals(numbers),
{'a': None, 'lst': [1, 2, 3]})
next(numbers)
self.assertEqual(inspect.getgeneratorlocals(numbers),
{'a': None, 'lst': [1, 2, 3], 'v': 1,
'b': (1, 2, 3)})
next(numbers)
self.assertEqual(inspect.getgeneratorlocals(numbers),
{'a': None, 'lst': [1, 2, 3], 'v': 2,
'b': (1, 2, 3)})
next(numbers)
self.assertEqual(inspect.getgeneratorlocals(numbers),
{'a': None, 'lst': [1, 2, 3], 'v': 3,
'b': (1, 2, 3), 'c': 12})
try:
next(numbers)
except StopIteration:
pass
self.assertEqual(inspect.getgeneratorlocals(numbers), {})
def test_getgeneratorlocals_empty(self):
def yield_one():
yield 1
one = yield_one()
self.assertEqual(inspect.getgeneratorlocals(one), {})
try:
next(one)
except StopIteration:
pass
self.assertEqual(inspect.getgeneratorlocals(one), {})
def test_getgeneratorlocals_error(self):
self.assertRaises(TypeError, inspect.getgeneratorlocals, 1)
self.assertRaises(TypeError, inspect.getgeneratorlocals, lambda x: True)
self.assertRaises(TypeError, inspect.getgeneratorlocals, set)
self.assertRaises(TypeError, inspect.getgeneratorlocals, (2,3))
class TestGetCoroutineState(unittest.TestCase):
def setUp(self):
@types.coroutine
def number_coroutine():
for number in range(5):
yield number
async def coroutine():
await number_coroutine()
self.coroutine = coroutine()
def tearDown(self):
self.coroutine.close()
def _coroutinestate(self):
return inspect.getcoroutinestate(self.coroutine)
def test_created(self):
self.assertEqual(self._coroutinestate(), inspect.CORO_CREATED)
def test_suspended(self):
self.coroutine.send(None)
self.assertEqual(self._coroutinestate(), inspect.CORO_SUSPENDED)
def test_closed_after_exhaustion(self):
while True:
try:
self.coroutine.send(None)
except StopIteration:
break
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED)
def test_closed_after_immediate_exception(self):
with self.assertRaises(RuntimeError):
self.coroutine.throw(RuntimeError)
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED)
def test_closed_after_close(self):
self.coroutine.close()
self.assertEqual(self._coroutinestate(), inspect.CORO_CLOSED)
def test_easy_debugging(self):
# repr() and str() of a coroutine state should contain the state name
names = 'CORO_CREATED CORO_RUNNING CORO_SUSPENDED CORO_CLOSED'.split()
for name in names:
state = getattr(inspect, name)
self.assertIn(name, repr(state))
self.assertIn(name, str(state))
def test_getcoroutinelocals(self):
@types.coroutine
def gencoro():
yield
gencoro = gencoro()
async def func(a=None):
b = 'spam'
await gencoro
coro = func()
self.assertEqual(inspect.getcoroutinelocals(coro),
{'a': None, 'gencoro': gencoro})
coro.send(None)
self.assertEqual(inspect.getcoroutinelocals(coro),
{'a': None, 'gencoro': gencoro, 'b': 'spam'})
@support.requires_working_socket()
class TestGetAsyncGenState(unittest.IsolatedAsyncioTestCase):
def setUp(self):
async def number_asyncgen():
for number in range(5):
yield number
self.asyncgen = number_asyncgen()
async def asyncTearDown(self):
await self.asyncgen.aclose()
def _asyncgenstate(self):
return inspect.getasyncgenstate(self.asyncgen)
def test_created(self):
self.assertEqual(self._asyncgenstate(), inspect.AGEN_CREATED)
async def test_suspended(self):
value = await anext(self.asyncgen)
self.assertEqual(self._asyncgenstate(), inspect.AGEN_SUSPENDED)
self.assertEqual(value, 0)
async def test_closed_after_exhaustion(self):
countdown = 7
with self.assertRaises(StopAsyncIteration):
while countdown := countdown - 1:
await anext(self.asyncgen)
self.assertEqual(countdown, 1)
self.assertEqual(self._asyncgenstate(), inspect.AGEN_CLOSED)
async def test_closed_after_immediate_exception(self):
with self.assertRaises(RuntimeError):
await self.asyncgen.athrow(RuntimeError)
self.assertEqual(self._asyncgenstate(), inspect.AGEN_CLOSED)
async def test_running(self):
async def running_check_asyncgen():
for number in range(5):
self.assertEqual(self._asyncgenstate(), inspect.AGEN_RUNNING)
yield number
self.assertEqual(self._asyncgenstate(), inspect.AGEN_RUNNING)
self.asyncgen = running_check_asyncgen()
# Running up to the first yield
await anext(self.asyncgen)
self.assertEqual(self._asyncgenstate(), inspect.AGEN_SUSPENDED)
# Running after the first yield
await anext(self.asyncgen)
self.assertEqual(self._asyncgenstate(), inspect.AGEN_SUSPENDED)
def test_easy_debugging(self):
# repr() and str() of a asyncgen state should contain the state name
names = 'AGEN_CREATED AGEN_RUNNING AGEN_SUSPENDED AGEN_CLOSED'.split()
for name in names:
state = getattr(inspect, name)
self.assertIn(name, repr(state))
self.assertIn(name, str(state))
async def test_getasyncgenlocals(self):
async def each(lst, a=None):
b=(1, 2, 3)
for v in lst:
if v == 3:
c = 12
yield v
numbers = each([1, 2, 3])
self.assertEqual(inspect.getasyncgenlocals(numbers),
{'a': None, 'lst': [1, 2, 3]})
await anext(numbers)
self.assertEqual(inspect.getasyncgenlocals(numbers),
{'a': None, 'lst': [1, 2, 3], 'v': 1,
'b': (1, 2, 3)})
await anext(numbers)
self.assertEqual(inspect.getasyncgenlocals(numbers),
{'a': None, 'lst': [1, 2, 3], 'v': 2,
'b': (1, 2, 3)})
await anext(numbers)
self.assertEqual(inspect.getasyncgenlocals(numbers),
{'a': None, 'lst': [1, 2, 3], 'v': 3,
'b': (1, 2, 3), 'c': 12})
with self.assertRaises(StopAsyncIteration):
await anext(numbers)
self.assertEqual(inspect.getasyncgenlocals(numbers), {})
async def test_getasyncgenlocals_empty(self):
async def yield_one():
yield 1
one = yield_one()
self.assertEqual(inspect.getasyncgenlocals(one), {})
await anext(one)
self.assertEqual(inspect.getasyncgenlocals(one), {})
with self.assertRaises(StopAsyncIteration):
await anext(one)
self.assertEqual(inspect.getasyncgenlocals(one), {})
def test_getasyncgenlocals_error(self):
self.assertRaises(TypeError, inspect.getasyncgenlocals, 1)
self.assertRaises(TypeError, inspect.getasyncgenlocals, lambda x: True)
self.assertRaises(TypeError, inspect.getasyncgenlocals, set)
self.assertRaises(TypeError, inspect.getasyncgenlocals, (2,3))
class MySignature(inspect.Signature):
# Top-level to make it picklable;
# used in test_signature_object_pickle
pass
class MyParameter(inspect.Parameter):
# Top-level to make it picklable;
# used in test_signature_object_pickle
pass
class TestSignatureObject(unittest.TestCase):
@staticmethod
def signature(func, **kw):
sig = inspect.signature(func, **kw)
return (tuple((param.name,
(... if param.default is param.empty else param.default),
(... if param.annotation is param.empty
else param.annotation),
str(param.kind).lower())
for param in sig.parameters.values()),
(... if sig.return_annotation is sig.empty
else sig.return_annotation))
def test_signature_object(self):
S = inspect.Signature
P = inspect.Parameter
self.assertEqual(str(S()), '()')
self.assertEqual(repr(S().parameters), 'mappingproxy(OrderedDict())')
def test(po, /, pk, pkd=100, *args, ko, kod=10, **kwargs):
pass
sig = inspect.signature(test)
self.assertTrue(repr(sig).startswith('<Signature'))
self.assertTrue('(po, /, pk' in repr(sig))
# We need two functions, because it is impossible to represent
# all param kinds in a single one.
def test2(pod=42, /):
pass
sig2 = inspect.signature(test2)
self.assertTrue(repr(sig2).startswith('<Signature'))
self.assertTrue('(pod=42, /)' in repr(sig2))
po = sig.parameters['po']
pod = sig2.parameters['pod']
pk = sig.parameters['pk']
pkd = sig.parameters['pkd']
args = sig.parameters['args']
ko = sig.parameters['ko']
kod = sig.parameters['kod']
kwargs = sig.parameters['kwargs']
S((po, pk, args, ko, kwargs))
S((po, pk, ko, kod))
S((po, pod, ko))
S((po, pod, kod))
S((pod, ko, kod))
S((pod, kod))
S((pod, args, kod, kwargs))
# keyword-only parameters without default values
# can follow keyword-only parameters with default values:
S((kod, ko))
S((kod, ko, kwargs))
S((args, kod, ko))
with self.assertRaisesRegex(ValueError, 'wrong parameter order'):
S((pk, po, args, ko, kwargs))
with self.assertRaisesRegex(ValueError, 'wrong parameter order'):
S((po, args, pk, ko, kwargs))
with self.assertRaisesRegex(ValueError, 'wrong parameter order'):
S((args, po, pk, ko, kwargs))
with self.assertRaisesRegex(ValueError, 'wrong parameter order'):
S((po, pk, args, kwargs, ko))
kwargs2 = kwargs.replace(name='args')
with self.assertRaisesRegex(ValueError, 'duplicate parameter name'):
S((po, pk, args, kwargs2, ko))
with self.assertRaisesRegex(ValueError, 'follows default argument'):
S((pod, po))
with self.assertRaisesRegex(ValueError, 'follows default argument'):
S((pod, pk))
with self.assertRaisesRegex(ValueError, 'follows default argument'):
S((po, pod, pk))
with self.assertRaisesRegex(ValueError, 'follows default argument'):
S((po, pkd, pk))
with self.assertRaisesRegex(ValueError, 'follows default argument'):
S((pkd, pk))
def test_signature_object_pickle(self):
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass
foo_partial = functools.partial(foo, a=1)
sig = inspect.signature(foo_partial)
for ver in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(pickle_ver=ver, subclass=False):
sig_pickled = pickle.loads(pickle.dumps(sig, ver))
self.assertEqual(sig, sig_pickled)
# Test that basic sub-classing works
sig = inspect.signature(foo)
myparam = MyParameter(name='z', kind=inspect.Parameter.POSITIONAL_ONLY)
myparams = collections.OrderedDict(sig.parameters, a=myparam)
mysig = MySignature().replace(parameters=myparams.values(),
return_annotation=sig.return_annotation)
self.assertTrue(isinstance(mysig, MySignature))
self.assertTrue(isinstance(mysig.parameters['z'], MyParameter))
for ver in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(pickle_ver=ver, subclass=True):
sig_pickled = pickle.loads(pickle.dumps(mysig, ver))
self.assertEqual(mysig, sig_pickled)
self.assertTrue(isinstance(sig_pickled, MySignature))
self.assertTrue(isinstance(sig_pickled.parameters['z'],
MyParameter))
def test_signature_immutability(self):
def test(a):
pass
sig = inspect.signature(test)
with self.assertRaises(AttributeError):
sig.foo = 'bar'
with self.assertRaises(TypeError):
sig.parameters['a'] = None
def test_signature_on_noarg(self):
def test():
pass
self.assertEqual(self.signature(test), ((), ...))
def test_signature_on_wargs(self):
def test(a, b:'foo') -> 123:
pass
self.assertEqual(self.signature(test),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., 'foo', "positional_or_keyword")),
123))
def test_signature_on_wkwonly(self):
def test(*, a:float, b:str) -> int:
pass
self.assertEqual(self.signature(test),
((('a', ..., float, "keyword_only"),
('b', ..., str, "keyword_only")),
int))
def test_signature_on_complex_args(self):
def test(a, b:'foo'=10, *args:'bar', spam:'baz', ham=123, **kwargs:int):
pass
self.assertEqual(self.signature(test),
((('a', ..., ..., "positional_or_keyword"),
('b', 10, 'foo', "positional_or_keyword"),
('args', ..., 'bar', "var_positional"),
('spam', ..., 'baz', "keyword_only"),
('ham', 123, ..., "keyword_only"),
('kwargs', ..., int, "var_keyword")),
...))
def test_signature_without_self(self):
def test_args_only(*args): # NOQA
pass
def test_args_kwargs_only(*args, **kwargs): # NOQA
pass
class A:
@classmethod
def test_classmethod(*args): # NOQA
pass
@staticmethod
def test_staticmethod(*args): # NOQA
pass
f1 = functools.partialmethod((test_classmethod), 1)
f2 = functools.partialmethod((test_args_only), 1)
f3 = functools.partialmethod((test_staticmethod), 1)
f4 = functools.partialmethod((test_args_kwargs_only),1)
self.assertEqual(self.signature(test_args_only),
((('args', ..., ..., 'var_positional'),), ...))
self.assertEqual(self.signature(test_args_kwargs_only),
((('args', ..., ..., 'var_positional'),
('kwargs', ..., ..., 'var_keyword')), ...))
self.assertEqual(self.signature(A.f1),
((('args', ..., ..., 'var_positional'),), ...))
self.assertEqual(self.signature(A.f2),
((('args', ..., ..., 'var_positional'),), ...))
self.assertEqual(self.signature(A.f3),
((('args', ..., ..., 'var_positional'),), ...))
self.assertEqual(self.signature(A.f4),
((('args', ..., ..., 'var_positional'),
('kwargs', ..., ..., 'var_keyword')), ...))
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_on_builtins(self):
_testcapi = import_helper.import_module("_testcapi")
def test_unbound_method(o):
"""Use this to test unbound methods (things that should have a self)"""
signature = inspect.signature(o)
self.assertTrue(isinstance(signature, inspect.Signature))
self.assertEqual(list(signature.parameters.values())[0].name, 'self')
return signature
def test_callable(o):
"""Use this to test bound methods or normal callables (things that don't expect self)"""
signature = inspect.signature(o)
self.assertTrue(isinstance(signature, inspect.Signature))
if signature.parameters:
self.assertNotEqual(list(signature.parameters.values())[0].name, 'self')
return signature
signature = test_callable(_testcapi.docstring_with_signature_with_defaults)
def p(name): return signature.parameters[name].default
self.assertEqual(p('s'), 'avocado')
self.assertEqual(p('b'), b'bytes')
self.assertEqual(p('d'), 3.14)
self.assertEqual(p('i'), 35)
self.assertEqual(p('n'), None)
self.assertEqual(p('t'), True)
self.assertEqual(p('f'), False)
self.assertEqual(p('local'), 3)
self.assertEqual(p('sys'), sys.maxsize)
self.assertEqual(p('exp'), sys.maxsize - 1)
test_callable(object)
# normal method
# (PyMethodDescr_Type, "method_descriptor")
test_unbound_method(_pickle.Pickler.dump)
d = _pickle.Pickler(io.StringIO())
test_callable(d.dump)
# static method
test_callable(bytes.maketrans)
test_callable(b'abc'.maketrans)
# class method
test_callable(dict.fromkeys)
test_callable({}.fromkeys)
# wrapper around slot (PyWrapperDescr_Type, "wrapper_descriptor")
test_unbound_method(type.__call__)
test_unbound_method(int.__add__)
test_callable((3).__add__)
# _PyMethodWrapper_Type
# support for 'method-wrapper'
test_callable(min.__call__)
# This doesn't work now.
# (We don't have a valid signature for "type" in 3.4)
class ThisWorksNow:
__call__ = type
# TODO: Support type.
self.assertEqual(ThisWorksNow()(1), int)
self.assertEqual(ThisWorksNow()('A', (), {}).__name__, 'A')
with self.assertRaisesRegex(ValueError, "no signature found"):
test_callable(ThisWorksNow())
# Regression test for issue #20786
test_unbound_method(dict.__delitem__)
test_unbound_method(property.__delete__)
# Regression test for issue #20586
test_callable(_testcapi.docstring_with_signature_but_no_doc)
# Regression test for gh-104955
method = bytearray.__release_buffer__
sig = test_unbound_method(method)
self.assertEqual(list(sig.parameters), ['self', 'buffer'])
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_on_decorated_builtins(self):
_testcapi = import_helper.import_module("_testcapi")
func = _testcapi.docstring_with_signature_with_defaults
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs) -> int:
return func(*args, **kwargs)
return wrapper
decorated_func = decorator(func)
self.assertEqual(inspect.signature(func),
inspect.signature(decorated_func))
def wrapper_like(*args, **kwargs) -> int: pass
self.assertEqual(inspect.signature(decorated_func,
follow_wrapped=False),
inspect.signature(wrapper_like))
@cpython_only
def test_signature_on_builtins_no_signature(self):
_testcapi = import_helper.import_module("_testcapi")
with self.assertRaisesRegex(ValueError,
'no signature found for builtin'):
inspect.signature(_testcapi.docstring_no_signature)
with self.assertRaisesRegex(ValueError,
'no signature found for builtin'):
inspect.signature(str)
cls = _testcapi.DocStringNoSignatureTest
obj = _testcapi.DocStringNoSignatureTest()
tests = [
(_testcapi.docstring_no_signature_noargs, meth_noargs),
(_testcapi.docstring_no_signature_o, meth_o),
(cls.meth_noargs, meth_self_noargs),
(cls.meth_o, meth_self_o),
(obj.meth_noargs, meth_noargs),
(obj.meth_o, meth_o),
(cls.meth_noargs_class, meth_noargs),
(cls.meth_o_class, meth_o),
(cls.meth_noargs_static, meth_noargs),
(cls.meth_o_static, meth_o),
(cls.meth_noargs_coexist, meth_self_noargs),
(cls.meth_o_coexist, meth_self_o),
(time.time, meth_noargs),
(str.lower, meth_self_noargs),
(''.lower, meth_noargs),
(set.add, meth_self_o),
(set().add, meth_o),
(set.__contains__, meth_self_o),
(set().__contains__, meth_o),
(datetime.datetime.__dict__['utcnow'], meth_type_noargs),
(datetime.datetime.utcnow, meth_noargs),
(dict.__dict__['__class_getitem__'], meth_type_o),
(dict.__class_getitem__, meth_o),
]
try:
import _stat
except ImportError:
# if the _stat extension is not available, stat.S_IMODE() is
# implemented in Python, not in C
pass
else:
tests.append((stat.S_IMODE, meth_o))
for builtin, template in tests:
with self.subTest(builtin):
self.assertEqual(inspect.signature(builtin),
inspect.signature(template))
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_parsing_with_defaults(self):
_testcapi = import_helper.import_module("_testcapi")
meth = _testcapi.DocStringUnrepresentableSignatureTest.with_default
self.assertEqual(str(inspect.signature(meth)), '(self, /, x=1)')
def test_signature_on_non_function(self):
with self.assertRaisesRegex(TypeError, 'is not a callable object'):
inspect.signature(42)
def test_signature_from_functionlike_object(self):
def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs):
pass
class funclike:
# Has to be callable, and have correct
# __code__, __annotations__, __defaults__, __name__,
# and __kwdefaults__ attributes
def __init__(self, func):
self.__name__ = func.__name__
self.__code__ = func.__code__
self.__annotations__ = func.__annotations__
self.__defaults__ = func.__defaults__
self.__kwdefaults__ = func.__kwdefaults__
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
sig_func = inspect.Signature.from_callable(func)
sig_funclike = inspect.Signature.from_callable(funclike(func))
self.assertEqual(sig_funclike, sig_func)
sig_funclike = inspect.signature(funclike(func))
self.assertEqual(sig_funclike, sig_func)
# If object is not a duck type of function, then
# signature will try to get a signature for its '__call__'
# method
fl = funclike(func)
del fl.__defaults__
self.assertEqual(self.signature(fl),
((('args', ..., ..., "var_positional"),
('kwargs', ..., ..., "var_keyword")),
...))
# Test with cython-like builtins:
_orig_isdesc = inspect.ismethoddescriptor
def _isdesc(obj):
if hasattr(obj, '_builtinmock'):
return True
return _orig_isdesc(obj)
with unittest.mock.patch('inspect.ismethoddescriptor', _isdesc):
builtin_func = funclike(func)
# Make sure that our mock setup is working
self.assertFalse(inspect.ismethoddescriptor(builtin_func))
builtin_func._builtinmock = True
self.assertTrue(inspect.ismethoddescriptor(builtin_func))
self.assertEqual(inspect.signature(builtin_func), sig_func)
def test_signature_functionlike_class(self):
# We only want to duck type function-like objects,
# not classes.
def func(a,b, *args, kwonly=True, kwonlyreq, **kwargs):
pass
class funclike:
def __init__(self, marker):
pass
__name__ = func.__name__
__code__ = func.__code__
__annotations__ = func.__annotations__
__defaults__ = func.__defaults__
__kwdefaults__ = func.__kwdefaults__
self.assertEqual(str(inspect.signature(funclike)), '(marker)')
def test_signature_on_method(self):
class Test:
def __init__(*args):
pass
def m1(self, arg1, arg2=1) -> int:
pass
def m2(*args):
pass
def __call__(*, a):
pass
self.assertEqual(self.signature(Test().m1),
((('arg1', ..., ..., "positional_or_keyword"),
('arg2', 1, ..., "positional_or_keyword")),
int))
self.assertEqual(self.signature(Test().m2),
((('args', ..., ..., "var_positional"),),
...))
self.assertEqual(self.signature(Test),
((('args', ..., ..., "var_positional"),),
...))
with self.assertRaisesRegex(ValueError, 'invalid method signature'):
self.signature(Test())
def test_signature_wrapped_bound_method(self):
# Issue 24298
class Test:
def m1(self, arg1, arg2=1) -> int:
pass
@functools.wraps(Test().m1)
def m1d(*args, **kwargs):
pass
self.assertEqual(self.signature(m1d),
((('arg1', ..., ..., "positional_or_keyword"),
('arg2', 1, ..., "positional_or_keyword")),
int))
def test_signature_on_classmethod(self):
if not support.MISSING_C_DOCSTRINGS:
self.assertEqual(self.signature(classmethod),
((('function', ..., ..., "positional_only"),),
...))
class Test:
@classmethod
def foo(cls, arg1, *, arg2=1):
pass
meth = Test().foo
self.assertEqual(self.signature(meth),
((('arg1', ..., ..., "positional_or_keyword"),
('arg2', 1, ..., "keyword_only")),
...))
meth = Test.foo
self.assertEqual(self.signature(meth),
((('arg1', ..., ..., "positional_or_keyword"),
('arg2', 1, ..., "keyword_only")),
...))
def test_signature_on_staticmethod(self):
if not support.MISSING_C_DOCSTRINGS:
self.assertEqual(self.signature(staticmethod),
((('function', ..., ..., "positional_only"),),
...))
class Test:
@staticmethod
def foo(cls, *, arg):
pass
meth = Test().foo
self.assertEqual(self.signature(meth),
((('cls', ..., ..., "positional_or_keyword"),
('arg', ..., ..., "keyword_only")),
...))
meth = Test.foo
self.assertEqual(self.signature(meth),
((('cls', ..., ..., "positional_or_keyword"),
('arg', ..., ..., "keyword_only")),
...))
def test_signature_on_partial(self):
from functools import partial
def test():
pass
self.assertEqual(self.signature(partial(test)), ((), ...))
with self.assertRaisesRegex(ValueError, "has incorrect arguments"):
inspect.signature(partial(test, 1))
with self.assertRaisesRegex(ValueError, "has incorrect arguments"):
inspect.signature(partial(test, a=1))
def test(a, b, *, c, d):
pass
self.assertEqual(self.signature(partial(test)),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword"),
('c', ..., ..., "keyword_only"),
('d', ..., ..., "keyword_only")),
...))
self.assertEqual(self.signature(partial(test, 1)),
((('b', ..., ..., "positional_or_keyword"),
('c', ..., ..., "keyword_only"),
('d', ..., ..., "keyword_only")),
...))
self.assertEqual(self.signature(partial(test, 1, c=2)),
((('b', ..., ..., "positional_or_keyword"),
('c', 2, ..., "keyword_only"),
('d', ..., ..., "keyword_only")),
...))
self.assertEqual(self.signature(partial(test, b=1, c=2)),
((('a', ..., ..., "positional_or_keyword"),
('b', 1, ..., "keyword_only"),
('c', 2, ..., "keyword_only"),
('d', ..., ..., "keyword_only")),
...))
self.assertEqual(self.signature(partial(test, 0, b=1, c=2)),
((('b', 1, ..., "keyword_only"),
('c', 2, ..., "keyword_only"),
('d', ..., ..., "keyword_only")),
...))
self.assertEqual(self.signature(partial(test, a=1)),
((('a', 1, ..., "keyword_only"),
('b', ..., ..., "keyword_only"),
('c', ..., ..., "keyword_only"),
('d', ..., ..., "keyword_only")),
...))
def test(a, *args, b, **kwargs):
pass
self.assertEqual(self.signature(partial(test, 1)),
((('args', ..., ..., "var_positional"),
('b', ..., ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
self.assertEqual(self.signature(partial(test, a=1)),
((('a', 1, ..., "keyword_only"),
('b', ..., ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
self.assertEqual(self.signature(partial(test, 1, 2, 3)),
((('args', ..., ..., "var_positional"),
('b', ..., ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
self.assertEqual(self.signature(partial(test, 1, 2, 3, test=True)),
((('args', ..., ..., "var_positional"),
('b', ..., ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
self.assertEqual(self.signature(partial(test, 1, 2, 3, test=1, b=0)),
((('args', ..., ..., "var_positional"),
('b', 0, ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
self.assertEqual(self.signature(partial(test, b=0)),
((('a', ..., ..., "positional_or_keyword"),
('args', ..., ..., "var_positional"),
('b', 0, ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
self.assertEqual(self.signature(partial(test, b=0, test=1)),
((('a', ..., ..., "positional_or_keyword"),
('args', ..., ..., "var_positional"),
('b', 0, ..., "keyword_only"),
('kwargs', ..., ..., "var_keyword")),
...))
def test(a, b, c:int) -> 42:
pass
sig = test.__signature__ = inspect.signature(test)
self.assertEqual(self.signature(partial(partial(test, 1))),
((('b', ..., ..., "positional_or_keyword"),
('c', ..., int, "positional_or_keyword")),
42))
self.assertEqual(self.signature(partial(partial(test, 1), 2)),
((('c', ..., int, "positional_or_keyword"),),
42))
def foo(a):
return a
_foo = partial(partial(foo, a=10), a=20)
self.assertEqual(self.signature(_foo),
((('a', 20, ..., "keyword_only"),),
...))
# check that we don't have any side-effects in signature(),
# and the partial object is still functioning
self.assertEqual(_foo(), 20)
def foo(a, b, c):
return a, b, c
_foo = partial(partial(foo, 1, b=20), b=30)
self.assertEqual(self.signature(_foo),
((('b', 30, ..., "keyword_only"),
('c', ..., ..., "keyword_only")),
...))
self.assertEqual(_foo(c=10), (1, 30, 10))
def foo(a, b, c, *, d):
return a, b, c, d
_foo = partial(partial(foo, d=20, c=20), b=10, d=30)
self.assertEqual(self.signature(_foo),
((('a', ..., ..., "positional_or_keyword"),
('b', 10, ..., "keyword_only"),
('c', 20, ..., "keyword_only"),
('d', 30, ..., "keyword_only"),
),
...))
ba = inspect.signature(_foo).bind(a=200, b=11)
self.assertEqual(_foo(*ba.args, **ba.kwargs), (200, 11, 20, 30))
def foo(a=1, b=2, c=3):
return a, b, c
_foo = partial(foo, c=13) # (a=1, b=2, *, c=13)
ba = inspect.signature(_foo).bind(a=11)
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 2, 13))
ba = inspect.signature(_foo).bind(11, 12)
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13))
ba = inspect.signature(_foo).bind(11, b=12)
self.assertEqual(_foo(*ba.args, **ba.kwargs), (11, 12, 13))
ba = inspect.signature(_foo).bind(b=12)
self.assertEqual(_foo(*ba.args, **ba.kwargs), (1, 12, 13))
_foo = partial(_foo, b=10, c=20)
ba = inspect.signature(_foo).bind(12)
self.assertEqual(_foo(*ba.args, **ba.kwargs), (12, 10, 20))
def foo(a, b, /, c, d, **kwargs):
pass
sig = inspect.signature(foo)
self.assertEqual(str(sig), '(a, b, /, c, d, **kwargs)')
self.assertEqual(self.signature(partial(foo, 1)),
((('b', ..., ..., 'positional_only'),
('c', ..., ..., 'positional_or_keyword'),
('d', ..., ..., 'positional_or_keyword'),
('kwargs', ..., ..., 'var_keyword')),
...))
self.assertEqual(self.signature(partial(foo, 1, 2)),
((('c', ..., ..., 'positional_or_keyword'),
('d', ..., ..., 'positional_or_keyword'),
('kwargs', ..., ..., 'var_keyword')),
...))
self.assertEqual(self.signature(partial(foo, 1, 2, 3)),
((('d', ..., ..., 'positional_or_keyword'),
('kwargs', ..., ..., 'var_keyword')),
...))
self.assertEqual(self.signature(partial(foo, 1, 2, c=3)),
((('c', 3, ..., 'keyword_only'),
('d', ..., ..., 'keyword_only'),
('kwargs', ..., ..., 'var_keyword')),
...))
self.assertEqual(self.signature(partial(foo, 1, c=3)),
((('b', ..., ..., 'positional_only'),
('c', 3, ..., 'keyword_only'),
('d', ..., ..., 'keyword_only'),
('kwargs', ..., ..., 'var_keyword')),
...))
def test_signature_on_partialmethod(self):
from functools import partialmethod
class Spam:
def test():
pass
ham = partialmethod(test)
with self.assertRaisesRegex(ValueError, "has incorrect arguments"):
inspect.signature(Spam.ham)
class Spam:
def test(it, a, *, c) -> 'spam':
pass
ham = partialmethod(test, c=1)
self.assertEqual(self.signature(Spam.ham, eval_str=False),
((('it', ..., ..., 'positional_or_keyword'),
('a', ..., ..., 'positional_or_keyword'),
('c', 1, ..., 'keyword_only')),
'spam'))
self.assertEqual(self.signature(Spam().ham, eval_str=False),
((('a', ..., ..., 'positional_or_keyword'),
('c', 1, ..., 'keyword_only')),
'spam'))
class Spam:
def test(self: 'anno', x):
pass
g = partialmethod(test, 1)
self.assertEqual(self.signature(Spam.g, eval_str=False),
((('self', ..., 'anno', 'positional_or_keyword'),),
...))
def test_signature_on_fake_partialmethod(self):
def foo(a): pass
foo.__partialmethod__ = 'spam'
self.assertEqual(str(inspect.signature(foo)), '(a)')
def test_signature_on_decorated(self):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs) -> int:
return func(*args, **kwargs)
return wrapper
class Foo:
@decorator
def bar(self, a, b):
pass
bar = decorator(Foo().bar)
self.assertEqual(self.signature(Foo.bar),
((('self', ..., ..., "positional_or_keyword"),
('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
self.assertEqual(self.signature(Foo().bar),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
self.assertEqual(self.signature(Foo.bar, follow_wrapped=False),
((('args', ..., ..., "var_positional"),
('kwargs', ..., ..., "var_keyword")),
...)) # functools.wraps will copy __annotations__
# from "func" to "wrapper", hence no
# return_annotation
self.assertEqual(self.signature(bar),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
# Test that we handle method wrappers correctly
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs) -> int:
return func(42, *args, **kwargs)
sig = inspect.signature(func)
new_params = tuple(sig.parameters.values())[1:]
wrapper.__signature__ = sig.replace(parameters=new_params)
return wrapper
class Foo:
@decorator
def __call__(self, a, b):
pass
self.assertEqual(self.signature(Foo.__call__),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
self.assertEqual(self.signature(Foo().__call__),
((('b', ..., ..., "positional_or_keyword"),),
...))
# Test we handle __signature__ partway down the wrapper stack
def wrapped_foo_call():
pass
wrapped_foo_call.__wrapped__ = Foo.__call__
self.assertEqual(self.signature(wrapped_foo_call),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
def test_signature_on_class(self):
class C:
def __init__(self, a):
pass
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
class CM(type):
def __call__(cls, a):
pass
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('classmethod'):
class CM(type):
@classmethod
def __call__(cls, a):
return a
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('staticmethod'):
class CM(type):
@staticmethod
def __call__(a):
return a
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('MethodType'):
class A:
def call(self, a):
return a
class CM(type):
__call__ = A().call
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partial'):
class CM(type):
__call__ = functools.partial(lambda x, a: (x, a), 2)
class C(metaclass=CM):
def __init__(self, b):
pass
with self.assertWarns(FutureWarning):
self.assertEqual(C(1), (2, 1))
with self.assertWarns(FutureWarning):
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partialmethod'):
class CM(type):
__call__ = functools.partialmethod(lambda self, x, a: (x, a), 2)
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(C(1), (2, 1))
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('BuiltinMethodType'):
class CM(type):
__call__ = ':'.join
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(C(['a', 'bc']), 'a:bc')
# BUG: Returns '<Signature (b)>'
with self.assertRaises(AssertionError):
self.assertEqual(self.signature(C), self.signature(''.join))
with self.subTest('MethodWrapperType'):
class CM(type):
__call__ = (2).__pow__
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(C(3), 8)
self.assertEqual(C(3, 7), 1)
if not support.MISSING_C_DOCSTRINGS:
# BUG: Returns '<Signature (b)>'
with self.assertRaises(AssertionError):
self.assertEqual(self.signature(C), self.signature((0).__pow__))
class CM(type):
def __new__(mcls, name, bases, dct, *, foo=1):
return super().__new__(mcls, name, bases, dct)
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(self.signature(C),
((('b', ..., ..., "positional_or_keyword"),),
...))
self.assertEqual(self.signature(CM),
((('name', ..., ..., "positional_or_keyword"),
('bases', ..., ..., "positional_or_keyword"),
('dct', ..., ..., "positional_or_keyword"),
('foo', 1, ..., "keyword_only")),
...))
class CMM(type):
def __new__(mcls, name, bases, dct, *, foo=1):
return super().__new__(mcls, name, bases, dct)
def __call__(cls, nm, bs, dt):
return type(nm, bs, dt)
class CM(type, metaclass=CMM):
def __new__(mcls, name, bases, dct, *, bar=2):
return super().__new__(mcls, name, bases, dct)
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(self.signature(CMM),
((('name', ..., ..., "positional_or_keyword"),
('bases', ..., ..., "positional_or_keyword"),
('dct', ..., ..., "positional_or_keyword"),
('foo', 1, ..., "keyword_only")),
...))
self.assertEqual(self.signature(CM),
((('nm', ..., ..., "positional_or_keyword"),
('bs', ..., ..., "positional_or_keyword"),
('dt', ..., ..., "positional_or_keyword")),
...))
self.assertEqual(self.signature(C),
((('b', ..., ..., "positional_or_keyword"),),
...))
class CM(type):
def __init__(cls, name, bases, dct, *, bar=2):
return super().__init__(name, bases, dct)
class C(metaclass=CM):
def __init__(self, b):
pass
self.assertEqual(self.signature(CM),
((('name', ..., ..., "positional_or_keyword"),
('bases', ..., ..., "positional_or_keyword"),
('dct', ..., ..., "positional_or_keyword"),
('bar', 2, ..., "keyword_only")),
...))
def test_signature_on_class_with_decorated_new(self):
def identity(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
return func(*args, **kwargs)
return wrapped
class Foo:
@identity
def __new__(cls, a, b):
pass
self.assertEqual(self.signature(Foo),
((('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
self.assertEqual(self.signature(Foo.__new__),
((('cls', ..., ..., "positional_or_keyword"),
('a', ..., ..., "positional_or_keyword"),
('b', ..., ..., "positional_or_keyword")),
...))
class Bar:
__new__ = identity(object.__new__)
varargs_signature = (
(('args', ..., ..., 'var_positional'),
('kwargs', ..., ..., 'var_keyword')),
...,
)
self.assertEqual(self.signature(Bar), ((), ...))
self.assertEqual(self.signature(Bar.__new__), varargs_signature)
self.assertEqual(self.signature(Bar, follow_wrapped=False),
varargs_signature)
self.assertEqual(self.signature(Bar.__new__, follow_wrapped=False),
varargs_signature)
def test_signature_on_class_with_init(self):
class C:
def __init__(self, b):
pass
C(1) # does not raise
self.assertEqual(self.signature(C),
((('b', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('classmethod'):
class C:
@classmethod
def __init__(cls, b):
pass
C(1) # does not raise
self.assertEqual(self.signature(C),
((('b', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('staticmethod'):
class C:
@staticmethod
def __init__(b):
pass
C(1) # does not raise
self.assertEqual(self.signature(C),
((('b', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('MethodType'):
class A:
def call(self, a):
pass
class C:
__init__ = A().call
C(1) # does not raise
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partial'):
class C:
__init__ = functools.partial(lambda x, a: None, 2)
with self.assertWarns(FutureWarning):
C(1) # does not raise
with self.assertWarns(FutureWarning):
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partialmethod'):
class C:
def _init(self, x, a):
self.a = (x, a)
__init__ = functools.partialmethod(_init, 2)
self.assertEqual(C(1).a, (2, 1))
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
def test_signature_on_class_with_new(self):
with self.subTest('FunctionType'):
class C:
def __new__(cls, a):
return a
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('classmethod'):
class C:
@classmethod
def __new__(cls, cls2, a):
return a
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('staticmethod'):
class C:
@staticmethod
def __new__(cls, a):
return a
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('MethodType'):
class A:
def call(self, cls, a):
return a
class C:
__new__ = A().call
self.assertEqual(C(1), 1)
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partial'):
class C:
__new__ = functools.partial(lambda x, cls, a: (x, a), 2)
self.assertEqual(C(1), (2, 1))
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partialmethod'):
class C:
__new__ = functools.partialmethod(lambda cls, x, a: (x, a), 2)
self.assertEqual(C(1), (2, 1))
self.assertEqual(self.signature(C),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('BuiltinMethodType'):
class C:
__new__ = str.__subclasscheck__
self.assertEqual(C(), False)
# TODO: Support BuiltinMethodType
# self.assertEqual(self.signature(C), ((), ...))
self.assertRaises(ValueError, self.signature, C)
with self.subTest('MethodWrapperType'):
class C:
__new__ = type.__or__.__get__(int, type)
self.assertEqual(C(), C | int)
# TODO: Support MethodWrapperType
# self.assertEqual(self.signature(C), ((), ...))
self.assertRaises(ValueError, self.signature, C)
# TODO: Test ClassMethodDescriptorType
with self.subTest('MethodDescriptorType'):
class C:
__new__ = type.__dict__['__subclasscheck__']
self.assertEqual(C(C), True)
self.assertEqual(self.signature(C), self.signature(C.__subclasscheck__))
with self.subTest('WrapperDescriptorType'):
class C:
__new__ = type.__or__
self.assertEqual(C(int), C | int)
# TODO: Support WrapperDescriptorType
# self.assertEqual(self.signature(C), self.signature(C.__or__))
self.assertRaises(ValueError, self.signature, C)
def test_signature_on_subclass(self):
class A:
def __new__(cls, a=1, *args, **kwargs):
return object.__new__(cls)
class B(A):
def __init__(self, b):
pass
class C(A):
def __new__(cls, a=1, b=2, *args, **kwargs):
return object.__new__(cls)
class D(A):
pass
self.assertEqual(self.signature(B),
((('b', ..., ..., "positional_or_keyword"),),
...))
self.assertEqual(self.signature(C),
((('a', 1, ..., 'positional_or_keyword'),
('b', 2, ..., 'positional_or_keyword'),
('args', ..., ..., 'var_positional'),
('kwargs', ..., ..., 'var_keyword')),
...))
self.assertEqual(self.signature(D),
((('a', 1, ..., 'positional_or_keyword'),
('args', ..., ..., 'var_positional'),
('kwargs', ..., ..., 'var_keyword')),
...))
def test_signature_on_generic_subclass(self):
from typing import Generic, TypeVar
T = TypeVar('T')
class A(Generic[T]):
def __init__(self, *, a: int) -> None:
pass
self.assertEqual(self.signature(A),
((('a', ..., int, 'keyword_only'),),
None))
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_on_class_without_init(self):
# Test classes without user-defined __init__ or __new__
class C: pass
self.assertEqual(str(inspect.signature(C)), '()')
class D(C): pass
self.assertEqual(str(inspect.signature(D)), '()')
# Test meta-classes without user-defined __init__ or __new__
class C(type): pass
class D(C): pass
self.assertEqual(C('A', (), {}).__name__, 'A')
# TODO: Support type.
with self.assertRaisesRegex(ValueError, "callable.*is not supported"):
self.assertEqual(inspect.signature(C), None)
self.assertEqual(D('A', (), {}).__name__, 'A')
with self.assertRaisesRegex(ValueError, "callable.*is not supported"):
self.assertEqual(inspect.signature(D), None)
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_on_builtin_class(self):
expected = ('(file, protocol=None, fix_imports=True, '
'buffer_callback=None)')
self.assertEqual(str(inspect.signature(_pickle.Pickler)), expected)
class P(_pickle.Pickler): pass
class EmptyTrait: pass
class P2(EmptyTrait, P): pass
self.assertEqual(str(inspect.signature(P)), expected)
self.assertEqual(str(inspect.signature(P2)), expected)
class P3(P2):
def __init__(self, spam):
pass
self.assertEqual(str(inspect.signature(P3)), '(spam)')
class MetaP(type):
def __call__(cls, foo, bar):
pass
class P4(P2, metaclass=MetaP):
pass
self.assertEqual(str(inspect.signature(P4)), '(foo, bar)')
def test_signature_on_callable_objects(self):
class Foo:
def __call__(self, a):
pass
self.assertEqual(self.signature(Foo()),
((('a', ..., ..., "positional_or_keyword"),),
...))
class Spam:
pass
with self.assertRaisesRegex(TypeError, "is not a callable object"):
inspect.signature(Spam())
class Bar(Spam, Foo):
pass
self.assertEqual(self.signature(Bar()),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('classmethod'):
class C:
@classmethod
def __call__(cls, a):
pass
self.assertEqual(self.signature(C()),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('staticmethod'):
class C:
@staticmethod
def __call__(a):
pass
self.assertEqual(self.signature(C()),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('MethodType'):
class A:
def call(self, a):
return a
class C:
__call__ = A().call
self.assertEqual(C()(1), 1)
self.assertEqual(self.signature(C()),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partial'):
class C:
__call__ = functools.partial(lambda x, a: (x, a), 2)
c = C()
with self.assertWarns(FutureWarning):
self.assertEqual(c(1), (2, 1))
with self.assertWarns(FutureWarning):
self.assertEqual(self.signature(c),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('partialmethod'):
class C:
__call__ = functools.partialmethod(lambda self, x, a: (x, a), 2)
self.assertEqual(C()(1), (2, 1))
self.assertEqual(self.signature(C()),
((('a', ..., ..., "positional_or_keyword"),),
...))
with self.subTest('BuiltinMethodType'):
class C:
__call__ = ':'.join
self.assertEqual(C()(['a', 'bc']), 'a:bc')
self.assertEqual(self.signature(C()), self.signature(''.join))
with self.subTest('MethodWrapperType'):
class C:
__call__ = (2).__pow__
self.assertEqual(C()(3), 8)
if not support.MISSING_C_DOCSTRINGS:
self.assertEqual(self.signature(C()), self.signature((0).__pow__))
with self.subTest('ClassMethodDescriptorType'):
class C(dict):
__call__ = dict.__dict__['fromkeys']
res = C()([1, 2], 3)
self.assertEqual(res, {1: 3, 2: 3})
self.assertEqual(type(res), C)
if not support.MISSING_C_DOCSTRINGS:
self.assertEqual(self.signature(C()), self.signature(dict.fromkeys))
with self.subTest('MethodDescriptorType'):
class C(str):
__call__ = str.join
self.assertEqual(C(':')(['a', 'bc']), 'a:bc')
self.assertEqual(self.signature(C()), self.signature(''.join))
with self.subTest('WrapperDescriptorType'):
class C(int):
__call__ = int.__pow__
self.assertEqual(C(2)(3), 8)
if not support.MISSING_C_DOCSTRINGS:
self.assertEqual(self.signature(C()), self.signature((0).__pow__))
with self.subTest('MemberDescriptorType'):
class C:
__slots__ = '__call__'
c = C()
c.__call__ = lambda a: a
self.assertEqual(c(1), 1)
self.assertEqual(self.signature(c),
((('a', ..., ..., "positional_or_keyword"),),
...))
def test_signature_on_callable_objects_with_text_signature_attr(self):
class C:
__text_signature__ = '(a, /, b, c=True)'
def __call__(self, *args, **kwargs):
pass
if not support.MISSING_C_DOCSTRINGS:
self.assertEqual(self.signature(C), ((), ...))
self.assertEqual(self.signature(C()),
((('a', ..., ..., "positional_only"),
('b', ..., ..., "positional_or_keyword"),
('c', True, ..., "positional_or_keyword"),
),
...))
c = C()
c.__text_signature__ = '(x, y)'
self.assertEqual(self.signature(c),
((('x', ..., ..., "positional_or_keyword"),
('y', ..., ..., "positional_or_keyword"),
),
...))
def test_signature_on_wrapper(self):
class Wrapper:
def __call__(self, b):
pass
wrapper = Wrapper()
wrapper.__wrapped__ = lambda a: None
self.assertEqual(self.signature(wrapper),
((('a', ..., ..., "positional_or_keyword"),),
...))
# wrapper loop:
wrapper = Wrapper()
wrapper.__wrapped__ = wrapper
with self.assertRaisesRegex(ValueError, 'wrapper loop'):
self.signature(wrapper)
def test_signature_on_lambdas(self):
self.assertEqual(self.signature((lambda a=10: a)),
((('a', 10, ..., "positional_or_keyword"),),
...))
def test_signature_on_mocks(self):
# https://github.com/python/cpython/issues/96127
for mock in (
unittest.mock.Mock(),
unittest.mock.AsyncMock(),
unittest.mock.MagicMock(),
):
with self.subTest(mock=mock):
self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)')
def test_signature_on_noncallable_mocks(self):
for mock in (
unittest.mock.NonCallableMock(),
unittest.mock.NonCallableMagicMock(),
):
with self.subTest(mock=mock):
with self.assertRaises(TypeError):
inspect.signature(mock)
def test_signature_equality(self):
def foo(a, *, b:int) -> float: pass
self.assertFalse(inspect.signature(foo) == 42)
self.assertTrue(inspect.signature(foo) != 42)
self.assertTrue(inspect.signature(foo) == ALWAYS_EQ)
self.assertFalse(inspect.signature(foo) != ALWAYS_EQ)
def bar(a, *, b:int) -> float: pass
self.assertTrue(inspect.signature(foo) == inspect.signature(bar))
self.assertFalse(inspect.signature(foo) != inspect.signature(bar))
self.assertEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def bar(a, *, b:int) -> int: pass
self.assertFalse(inspect.signature(foo) == inspect.signature(bar))
self.assertTrue(inspect.signature(foo) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def bar(a, *, b:int): pass
self.assertFalse(inspect.signature(foo) == inspect.signature(bar))
self.assertTrue(inspect.signature(foo) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def bar(a, *, b:int=42) -> float: pass
self.assertFalse(inspect.signature(foo) == inspect.signature(bar))
self.assertTrue(inspect.signature(foo) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def bar(a, *, c) -> float: pass
self.assertFalse(inspect.signature(foo) == inspect.signature(bar))
self.assertTrue(inspect.signature(foo) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def bar(a, b:int) -> float: pass
self.assertFalse(inspect.signature(foo) == inspect.signature(bar))
self.assertTrue(inspect.signature(foo) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def spam(b:int, a) -> float: pass
self.assertFalse(inspect.signature(spam) == inspect.signature(bar))
self.assertTrue(inspect.signature(spam) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(spam)), hash(inspect.signature(bar)))
def foo(*, a, b, c): pass
def bar(*, c, b, a): pass
self.assertTrue(inspect.signature(foo) == inspect.signature(bar))
self.assertFalse(inspect.signature(foo) != inspect.signature(bar))
self.assertEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def foo(*, a=1, b, c): pass
def bar(*, c, b, a=1): pass
self.assertTrue(inspect.signature(foo) == inspect.signature(bar))
self.assertFalse(inspect.signature(foo) != inspect.signature(bar))
self.assertEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def foo(pos, *, a=1, b, c): pass
def bar(pos, *, c, b, a=1): pass
self.assertTrue(inspect.signature(foo) == inspect.signature(bar))
self.assertFalse(inspect.signature(foo) != inspect.signature(bar))
self.assertEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def foo(pos, *, a, b, c): pass
def bar(pos, *, c, b, a=1): pass
self.assertFalse(inspect.signature(foo) == inspect.signature(bar))
self.assertTrue(inspect.signature(foo) != inspect.signature(bar))
self.assertNotEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def foo(pos, *args, a=42, b, c, **kwargs:int): pass
def bar(pos, *args, c, b, a=42, **kwargs:int): pass
self.assertTrue(inspect.signature(foo) == inspect.signature(bar))
self.assertFalse(inspect.signature(foo) != inspect.signature(bar))
self.assertEqual(
hash(inspect.signature(foo)), hash(inspect.signature(bar)))
def test_signature_hashable(self):
S = inspect.Signature
P = inspect.Parameter
def foo(a): pass
foo_sig = inspect.signature(foo)
manual_sig = S(parameters=[P('a', P.POSITIONAL_OR_KEYWORD)])
self.assertEqual(hash(foo_sig), hash(manual_sig))
self.assertNotEqual(hash(foo_sig),
hash(manual_sig.replace(return_annotation='spam')))
def bar(a) -> 1: pass
self.assertNotEqual(hash(foo_sig), hash(inspect.signature(bar)))
def foo(a={}): pass
with self.assertRaisesRegex(TypeError, 'unhashable type'):
hash(inspect.signature(foo))
def foo(a) -> {}: pass
with self.assertRaisesRegex(TypeError, 'unhashable type'):
hash(inspect.signature(foo))
def test_signature_str(self):
def foo(a:int=1, *, b, c=None, **kwargs) -> 42:
pass
self.assertEqual(str(inspect.signature(foo)),
'(a: int = 1, *, b, c=None, **kwargs) -> 42')
self.assertEqual(str(inspect.signature(foo)),
inspect.signature(foo).format())
def foo(a:int=1, *args, b, c=None, **kwargs) -> 42:
pass
self.assertEqual(str(inspect.signature(foo)),
'(a: int = 1, *args, b, c=None, **kwargs) -> 42')
self.assertEqual(str(inspect.signature(foo)),
inspect.signature(foo).format())
def foo():
pass
self.assertEqual(str(inspect.signature(foo)), '()')
self.assertEqual(str(inspect.signature(foo)),
inspect.signature(foo).format())
def foo(a: list[str]) -> tuple[str, float]:
pass
self.assertEqual(str(inspect.signature(foo)),
'(a: list[str]) -> tuple[str, float]')
self.assertEqual(str(inspect.signature(foo)),
inspect.signature(foo).format())
from typing import Tuple
def foo(a: list[str]) -> Tuple[str, float]:
pass
self.assertEqual(str(inspect.signature(foo)),
'(a: list[str]) -> Tuple[str, float]')
self.assertEqual(str(inspect.signature(foo)),
inspect.signature(foo).format())
def test_signature_str_positional_only(self):
P = inspect.Parameter
S = inspect.Signature
def test(a_po, /, *, b, **kwargs):
return a_po, kwargs
self.assertEqual(str(inspect.signature(test)),
'(a_po, /, *, b, **kwargs)')
self.assertEqual(str(inspect.signature(test)),
inspect.signature(test).format())
test = S(parameters=[P('foo', P.POSITIONAL_ONLY)])
self.assertEqual(str(test), '(foo, /)')
self.assertEqual(str(test), test.format())
test = S(parameters=[P('foo', P.POSITIONAL_ONLY),
P('bar', P.VAR_KEYWORD)])
self.assertEqual(str(test), '(foo, /, **bar)')
self.assertEqual(str(test), test.format())
test = S(parameters=[P('foo', P.POSITIONAL_ONLY),
P('bar', P.VAR_POSITIONAL)])
self.assertEqual(str(test), '(foo, /, *bar)')
self.assertEqual(str(test), test.format())
def test_signature_format(self):
from typing import Annotated, Literal
def func(x: Annotated[int, 'meta'], y: Literal['a', 'b'], z: 'LiteralString'):
pass
expected_singleline = "(x: Annotated[int, 'meta'], y: Literal['a', 'b'], z: 'LiteralString')"
expected_multiline = """(
x: Annotated[int, 'meta'],
y: Literal['a', 'b'],
z: 'LiteralString'
)"""
self.assertEqual(
inspect.signature(func).format(),
expected_singleline,
)
self.assertEqual(
inspect.signature(func).format(max_width=None),
expected_singleline,
)
self.assertEqual(
inspect.signature(func).format(max_width=len(expected_singleline)),
expected_singleline,
)
self.assertEqual(
inspect.signature(func).format(max_width=len(expected_singleline) - 1),
expected_multiline,
)
self.assertEqual(
inspect.signature(func).format(max_width=0),
expected_multiline,
)
self.assertEqual(
inspect.signature(func).format(max_width=-1),
expected_multiline,
)
def test_signature_format_all_arg_types(self):
from typing import Annotated, Literal
def func(
x: Annotated[int, 'meta'],
/,
y: Literal['a', 'b'],
*,
z: 'LiteralString',
**kwargs: object,
) -> None:
pass
expected_multiline = """(
x: Annotated[int, 'meta'],
/,
y: Literal['a', 'b'],
*,
z: 'LiteralString',
**kwargs: object
) -> None"""
self.assertEqual(
inspect.signature(func).format(max_width=-1),
expected_multiline,
)
def test_signature_replace_parameters(self):
def test(a, b) -> 42:
pass
sig = inspect.signature(test)
parameters = sig.parameters
sig = sig.replace(parameters=list(parameters.values())[1:])
self.assertEqual(list(sig.parameters), ['b'])
self.assertEqual(sig.parameters['b'], parameters['b'])
self.assertEqual(sig.return_annotation, 42)
sig = sig.replace(parameters=())
self.assertEqual(dict(sig.parameters), {})
sig = inspect.signature(test)
parameters = sig.parameters
sig = copy.replace(sig, parameters=list(parameters.values())[1:])
self.assertEqual(list(sig.parameters), ['b'])
self.assertEqual(sig.parameters['b'], parameters['b'])
self.assertEqual(sig.return_annotation, 42)
sig = copy.replace(sig, parameters=())
self.assertEqual(dict(sig.parameters), {})
def test_signature_replace_anno(self):
def test() -> 42:
pass
sig = inspect.signature(test)
sig = sig.replace(return_annotation=None)
self.assertIs(sig.return_annotation, None)
sig = sig.replace(return_annotation=sig.empty)
self.assertIs(sig.return_annotation, sig.empty)
sig = sig.replace(return_annotation=42)
self.assertEqual(sig.return_annotation, 42)
self.assertEqual(sig, inspect.signature(test))
sig = inspect.signature(test)
sig = copy.replace(sig, return_annotation=None)
self.assertIs(sig.return_annotation, None)
sig = copy.replace(sig, return_annotation=sig.empty)
self.assertIs(sig.return_annotation, sig.empty)
sig = copy.replace(sig, return_annotation=42)
self.assertEqual(sig.return_annotation, 42)
self.assertEqual(sig, inspect.signature(test))
def test_signature_replaced(self):
def test():
pass
spam_param = inspect.Parameter('spam', inspect.Parameter.POSITIONAL_ONLY)
sig = test.__signature__ = inspect.Signature(parameters=(spam_param,))
self.assertEqual(sig, inspect.signature(test))
def test_signature_on_mangled_parameters(self):
class Spam:
def foo(self, __p1:1=2, *, __p2:2=3):
pass
class Ham(Spam):
pass
self.assertEqual(self.signature(Spam.foo),
((('self', ..., ..., "positional_or_keyword"),
('_Spam__p1', 2, 1, "positional_or_keyword"),
('_Spam__p2', 3, 2, "keyword_only")),
...))
self.assertEqual(self.signature(Spam.foo),
self.signature(Ham.foo))
def test_signature_from_callable_python_obj(self):
class MySignature(inspect.Signature): pass
def foo(a, *, b:1): pass
foo_sig = MySignature.from_callable(foo)
self.assertIsInstance(foo_sig, MySignature)
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_from_callable_class(self):
# A regression test for a class inheriting its signature from `object`.
class MySignature(inspect.Signature): pass
class foo: pass
foo_sig = MySignature.from_callable(foo)
self.assertIsInstance(foo_sig, MySignature)
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_signature_from_callable_builtin_obj(self):
class MySignature(inspect.Signature): pass
sig = MySignature.from_callable(_pickle.Pickler)
self.assertIsInstance(sig, MySignature)
def test_signature_definition_order_preserved_on_kwonly(self):
for fn in signatures_with_lexicographic_keyword_only_parameters():
signature = inspect.signature(fn)
l = list(signature.parameters)
sorted_l = sorted(l)
self.assertTrue(l)
self.assertEqual(l, sorted_l)
signature = inspect.signature(unsorted_keyword_only_parameters_fn)
l = list(signature.parameters)
self.assertEqual(l, unsorted_keyword_only_parameters)
def test_signater_parameters_is_ordered(self):
p1 = inspect.signature(lambda x, y: None).parameters
p2 = inspect.signature(lambda y, x: None).parameters
self.assertNotEqual(p1, p2)
def test_signature_annotations_with_local_namespaces(self):
class Foo: ...
def func(foo: Foo) -> int: pass
def func2(foo: Foo, bar: 'Bar') -> int: pass
for signature_func in (inspect.signature, inspect.Signature.from_callable):
with self.subTest(signature_func = signature_func):
sig1 = signature_func(func)
self.assertEqual(sig1.return_annotation, int)
self.assertEqual(sig1.parameters['foo'].annotation, Foo)
sig2 = signature_func(func, locals=locals())
self.assertEqual(sig2.return_annotation, int)
self.assertEqual(sig2.parameters['foo'].annotation, Foo)
sig3 = signature_func(func2, globals={'Bar': int}, locals=locals())
self.assertEqual(sig3.return_annotation, int)
self.assertEqual(sig3.parameters['foo'].annotation, Foo)
self.assertEqual(sig3.parameters['bar'].annotation, 'Bar')
def test_signature_eval_str(self):
isa = inspect_stringized_annotations
sig = inspect.Signature
par = inspect.Parameter
PORK = inspect.Parameter.POSITIONAL_OR_KEYWORD
for signature_func in (inspect.signature, inspect.Signature.from_callable):
with self.subTest(signature_func = signature_func):
self.assertEqual(
signature_func(isa.MyClass),
sig(
parameters=(
par('a', PORK),
par('b', PORK),
)))
self.assertEqual(
signature_func(isa.function),
sig(
return_annotation='MyClass',
parameters=(
par('a', PORK, annotation='int'),
par('b', PORK, annotation='str'),
)))
self.assertEqual(
signature_func(isa.function2),
sig(
return_annotation='MyClass',
parameters=(
par('a', PORK, annotation='int'),
par('b', PORK, annotation="'str'"),
par('c', PORK, annotation="MyClass"),
)))
self.assertEqual(
signature_func(isa.function3),
sig(
parameters=(
par('a', PORK, annotation="'int'"),
par('b', PORK, annotation="'str'"),
par('c', PORK, annotation="'MyClass'"),
)))
if not MISSING_C_DOCSTRINGS:
self.assertEqual(signature_func(isa.UnannotatedClass), sig())
self.assertEqual(signature_func(isa.unannotated_function),
sig(
parameters=(
par('a', PORK),
par('b', PORK),
par('c', PORK),
)))
self.assertEqual(
signature_func(isa.MyClass, eval_str=True),
sig(
parameters=(
par('a', PORK),
par('b', PORK),
)))
self.assertEqual(
signature_func(isa.function, eval_str=True),
sig(
return_annotation=isa.MyClass,
parameters=(
par('a', PORK, annotation=int),
par('b', PORK, annotation=str),
)))
self.assertEqual(
signature_func(isa.function2, eval_str=True),
sig(
return_annotation=isa.MyClass,
parameters=(
par('a', PORK, annotation=int),
par('b', PORK, annotation='str'),
par('c', PORK, annotation=isa.MyClass),
)))
self.assertEqual(
signature_func(isa.function3, eval_str=True),
sig(
parameters=(
par('a', PORK, annotation='int'),
par('b', PORK, annotation='str'),
par('c', PORK, annotation='MyClass'),
)))
globalns = {'int': float, 'str': complex}
localns = {'str': tuple, 'MyClass': dict}
with self.assertRaises(NameError):
signature_func(isa.function, eval_str=True, globals=globalns)
self.assertEqual(
signature_func(isa.function, eval_str=True, locals=localns),
sig(
return_annotation=dict,
parameters=(
par('a', PORK, annotation=int),
par('b', PORK, annotation=tuple),
)))
self.assertEqual(
signature_func(isa.function, eval_str=True, globals=globalns, locals=localns),
sig(
return_annotation=dict,
parameters=(
par('a', PORK, annotation=float),
par('b', PORK, annotation=tuple),
)))
def test_signature_none_annotation(self):
class funclike:
# Has to be callable, and have correct
# __code__, __annotations__, __defaults__, __name__,
# and __kwdefaults__ attributes
def __init__(self, func):
self.__name__ = func.__name__
self.__code__ = func.__code__
self.__annotations__ = func.__annotations__
self.__defaults__ = func.__defaults__
self.__kwdefaults__ = func.__kwdefaults__
self.func = func
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def foo(): pass
foo = funclike(foo)
foo.__annotations__ = None
for signature_func in (inspect.signature, inspect.Signature.from_callable):
with self.subTest(signature_func = signature_func):
self.assertEqual(signature_func(foo), inspect.Signature())
self.assertEqual(inspect.get_annotations(foo), {})
def test_signature_as_str(self):
self.maxDiff = None
class S:
__signature__ = '(a, b=2)'
self.assertEqual(self.signature(S),
((('a', ..., ..., 'positional_or_keyword'),
('b', 2, ..., 'positional_or_keyword')),
...))
def test_signature_as_callable(self):
# __signature__ should be either a staticmethod or a bound classmethod
class S:
@classmethod
def __signature__(cls):
return '(a, b=2)'
self.assertEqual(self.signature(S),
((('a', ..., ..., 'positional_or_keyword'),
('b', 2, ..., 'positional_or_keyword')),
...))
class S:
@staticmethod
def __signature__():
return '(a, b=2)'
self.assertEqual(self.signature(S),
((('a', ..., ..., 'positional_or_keyword'),
('b', 2, ..., 'positional_or_keyword')),
...))
def test_signature_on_derived_classes(self):
# gh-105080: Make sure that signatures are consistent on derived classes
class B:
def __new__(self, *args, **kwargs):
return super().__new__(self)
def __init__(self, value):
self.value = value
class D1(B):
def __init__(self, value):
super().__init__(value)
class D2(D1):
pass
self.assertEqual(inspect.signature(D2), inspect.signature(D1))
def test_signature_on_non_comparable(self):
class NoncomparableCallable:
def __call__(self, a):
pass
def __eq__(self, other):
1/0
self.assertEqual(self.signature(NoncomparableCallable()),
((('a', ..., ..., 'positional_or_keyword'),),
...))
class TestParameterObject(unittest.TestCase):
def test_signature_parameter_kinds(self):
P = inspect.Parameter
self.assertTrue(P.POSITIONAL_ONLY < P.POSITIONAL_OR_KEYWORD < \
P.VAR_POSITIONAL < P.KEYWORD_ONLY < P.VAR_KEYWORD)
self.assertEqual(str(P.POSITIONAL_ONLY), 'POSITIONAL_ONLY')
self.assertTrue('POSITIONAL_ONLY' in repr(P.POSITIONAL_ONLY))
def test_signature_parameter_object(self):
p = inspect.Parameter('foo', default=10,
kind=inspect.Parameter.POSITIONAL_ONLY)
self.assertEqual(p.name, 'foo')
self.assertEqual(p.default, 10)
self.assertIs(p.annotation, p.empty)
self.assertEqual(p.kind, inspect.Parameter.POSITIONAL_ONLY)
with self.assertRaisesRegex(ValueError, "value '123' is "
"not a valid Parameter.kind"):
inspect.Parameter('foo', default=10, kind='123')
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'):
inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD)
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'):
inspect.Parameter('from', kind=inspect.Parameter.VAR_KEYWORD)
with self.assertRaisesRegex(TypeError, 'name must be a str'):
inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD)
with self.assertRaisesRegex(ValueError,
'is not a valid parameter name'):
inspect.Parameter('$', kind=inspect.Parameter.VAR_KEYWORD)
with self.assertRaisesRegex(ValueError,
'is not a valid parameter name'):
inspect.Parameter('.a', kind=inspect.Parameter.VAR_KEYWORD)
with self.assertRaisesRegex(ValueError, 'cannot have default values'):
inspect.Parameter('a', default=42,
kind=inspect.Parameter.VAR_KEYWORD)
with self.assertRaisesRegex(ValueError, 'cannot have default values'):
inspect.Parameter('a', default=42,
kind=inspect.Parameter.VAR_POSITIONAL)
p = inspect.Parameter('a', default=42,
kind=inspect.Parameter.POSITIONAL_OR_KEYWORD)
with self.assertRaisesRegex(ValueError, 'cannot have default values'):
p.replace(kind=inspect.Parameter.VAR_POSITIONAL)
self.assertTrue(repr(p).startswith('<Parameter'))
self.assertTrue('"a=42"' in repr(p))
def test_signature_parameter_hashable(self):
P = inspect.Parameter
foo = P('foo', kind=P.POSITIONAL_ONLY)
self.assertEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY)))
self.assertNotEqual(hash(foo), hash(P('foo', kind=P.POSITIONAL_ONLY,
default=42)))
self.assertNotEqual(hash(foo),
hash(foo.replace(kind=P.VAR_POSITIONAL)))
def test_signature_parameter_equality(self):
P = inspect.Parameter
p = P('foo', default=42, kind=inspect.Parameter.KEYWORD_ONLY)
self.assertTrue(p == p)
self.assertFalse(p != p)
self.assertFalse(p == 42)
self.assertTrue(p != 42)
self.assertTrue(p == ALWAYS_EQ)
self.assertFalse(p != ALWAYS_EQ)
self.assertTrue(p == P('foo', default=42,
kind=inspect.Parameter.KEYWORD_ONLY))
self.assertFalse(p != P('foo', default=42,
kind=inspect.Parameter.KEYWORD_ONLY))
def test_signature_parameter_replace(self):
p = inspect.Parameter('foo', default=42,
kind=inspect.Parameter.KEYWORD_ONLY)
self.assertIsNot(p.replace(), p)
self.assertEqual(p.replace(), p)
self.assertIsNot(copy.replace(p), p)
self.assertEqual(copy.replace(p), p)
p2 = p.replace(annotation=1)
self.assertEqual(p2.annotation, 1)
p2 = p2.replace(annotation=p2.empty)
self.assertEqual(p2, p)
p3 = copy.replace(p, annotation=1)
self.assertEqual(p3.annotation, 1)
p3 = copy.replace(p3, annotation=p3.empty)
self.assertEqual(p3, p)
p2 = p2.replace(name='bar')
self.assertEqual(p2.name, 'bar')
self.assertNotEqual(p2, p)
p3 = copy.replace(p3, name='bar')
self.assertEqual(p3.name, 'bar')
self.assertNotEqual(p3, p)
with self.assertRaisesRegex(ValueError,
'name is a required attribute'):
p2 = p2.replace(name=p2.empty)
with self.assertRaisesRegex(ValueError,
'name is a required attribute'):
p3 = copy.replace(p3, name=p3.empty)
p2 = p2.replace(name='foo', default=None)
self.assertIs(p2.default, None)
self.assertNotEqual(p2, p)
p3 = copy.replace(p3, name='foo', default=None)
self.assertIs(p3.default, None)
self.assertNotEqual(p3, p)
p2 = p2.replace(name='foo', default=p2.empty)
self.assertIs(p2.default, p2.empty)
p3 = copy.replace(p3, name='foo', default=p3.empty)
self.assertIs(p3.default, p3.empty)
p2 = p2.replace(default=42, kind=p2.POSITIONAL_OR_KEYWORD)
self.assertEqual(p2.kind, p2.POSITIONAL_OR_KEYWORD)
self.assertNotEqual(p2, p)
p3 = copy.replace(p3, default=42, kind=p3.POSITIONAL_OR_KEYWORD)
self.assertEqual(p3.kind, p3.POSITIONAL_OR_KEYWORD)
self.assertNotEqual(p3, p)
with self.assertRaisesRegex(ValueError,
"value <class 'inspect._empty'> "
"is not a valid Parameter.kind"):
p2 = p2.replace(kind=p2.empty)
with self.assertRaisesRegex(ValueError,
"value <class 'inspect._empty'> "
"is not a valid Parameter.kind"):
p3 = copy.replace(p3, kind=p3.empty)
p2 = p2.replace(kind=p2.KEYWORD_ONLY)
self.assertEqual(p2, p)
p3 = copy.replace(p3, kind=p3.KEYWORD_ONLY)
self.assertEqual(p3, p)
def test_signature_parameter_positional_only(self):
with self.assertRaisesRegex(TypeError, 'name must be a str'):
inspect.Parameter(None, kind=inspect.Parameter.POSITIONAL_ONLY)
@cpython_only
def test_signature_parameter_implicit(self):
with self.assertRaisesRegex(ValueError,
'implicit arguments must be passed as '
'positional or keyword arguments, '
'not positional-only'):
inspect.Parameter('.0', kind=inspect.Parameter.POSITIONAL_ONLY)
param = inspect.Parameter(
'.0', kind=inspect.Parameter.POSITIONAL_OR_KEYWORD)
self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_ONLY)
self.assertEqual(param.name, 'implicit0')
def test_signature_parameter_immutability(self):
p = inspect.Parameter('spam', kind=inspect.Parameter.KEYWORD_ONLY)
with self.assertRaises(AttributeError):
p.foo = 'bar'
with self.assertRaises(AttributeError):
p.kind = 123
class TestSignatureBind(unittest.TestCase):
@staticmethod
def call(func, *args, **kwargs):
sig = inspect.signature(func)
ba = sig.bind(*args, **kwargs)
# Prevent unexpected success of assertRaises(TypeError, ...)
try:
return func(*ba.args, **ba.kwargs)
except TypeError as e:
raise AssertionError from e
def test_signature_bind_empty(self):
def test():
return 42
self.assertEqual(self.call(test), 42)
with self.assertRaisesRegex(TypeError, 'too many positional arguments'):
self.call(test, 1)
with self.assertRaisesRegex(TypeError, 'too many positional arguments'):
self.call(test, 1, spam=10)
with self.assertRaisesRegex(
TypeError, "got an unexpected keyword argument 'spam'"):
self.call(test, spam=1)
def test_signature_bind_var(self):
def test(*args, **kwargs):
return args, kwargs
self.assertEqual(self.call(test), ((), {}))
self.assertEqual(self.call(test, 1), ((1,), {}))
self.assertEqual(self.call(test, 1, 2), ((1, 2), {}))
self.assertEqual(self.call(test, foo='bar'), ((), {'foo': 'bar'}))
self.assertEqual(self.call(test, 1, foo='bar'), ((1,), {'foo': 'bar'}))
self.assertEqual(self.call(test, args=10), ((), {'args': 10}))
self.assertEqual(self.call(test, 1, 2, foo='bar'),
((1, 2), {'foo': 'bar'}))
def test_signature_bind_just_args(self):
def test(a, b, c):
return a, b, c
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3))
with self.assertRaisesRegex(TypeError, 'too many positional arguments'):
self.call(test, 1, 2, 3, 4)
with self.assertRaisesRegex(TypeError,
"missing a required argument: 'b'"):
self.call(test, 1)
with self.assertRaisesRegex(TypeError,
"missing a required argument: 'a'"):
self.call(test)
def test(a, b, c=10):
return a, b, c
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3))
self.assertEqual(self.call(test, 1, 2), (1, 2, 10))
def test(a=1, b=2, c=3):
return a, b, c
self.assertEqual(self.call(test, a=10, c=13), (10, 2, 13))
self.assertEqual(self.call(test, a=10), (10, 2, 3))
self.assertEqual(self.call(test, b=10), (1, 10, 3))
def test_signature_bind_varargs_order(self):
def test(*args):
return args
self.assertEqual(self.call(test), ())
self.assertEqual(self.call(test, 1, 2, 3), (1, 2, 3))
def test_signature_bind_args_and_varargs(self):
def test(a, b, c=3, *args):
return a, b, c, args
self.assertEqual(self.call(test, 1, 2, 3, 4, 5), (1, 2, 3, (4, 5)))
self.assertEqual(self.call(test, 1, 2), (1, 2, 3, ()))
self.assertEqual(self.call(test, b=1, a=2), (2, 1, 3, ()))
self.assertEqual(self.call(test, 1, b=2), (1, 2, 3, ()))
with self.assertRaisesRegex(TypeError,
"multiple values for argument 'c'"):
self.call(test, 1, 2, 3, c=4)
def test_signature_bind_just_kwargs(self):
def test(**kwargs):
return kwargs
self.assertEqual(self.call(test), {})
self.assertEqual(self.call(test, foo='bar', spam='ham'),
{'foo': 'bar', 'spam': 'ham'})
def test_signature_bind_args_and_kwargs(self):
def test(a, b, c=3, **kwargs):
return a, b, c, kwargs
self.assertEqual(self.call(test, 1, 2), (1, 2, 3, {}))
self.assertEqual(self.call(test, 1, 2, foo='bar', spam='ham'),
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'}))
self.assertEqual(self.call(test, b=2, a=1, foo='bar', spam='ham'),
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'}))
self.assertEqual(self.call(test, a=1, b=2, foo='bar', spam='ham'),
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'}))
self.assertEqual(self.call(test, 1, b=2, foo='bar', spam='ham'),
(1, 2, 3, {'foo': 'bar', 'spam': 'ham'}))
self.assertEqual(self.call(test, 1, b=2, c=4, foo='bar', spam='ham'),
(1, 2, 4, {'foo': 'bar', 'spam': 'ham'}))
self.assertEqual(self.call(test, 1, 2, 4, foo='bar'),
(1, 2, 4, {'foo': 'bar'}))
self.assertEqual(self.call(test, c=5, a=4, b=3),
(4, 3, 5, {}))
def test_signature_bind_kwonly(self):
def test(*, foo):
return foo
with self.assertRaisesRegex(TypeError,
'too many positional arguments'):
self.call(test, 1)
self.assertEqual(self.call(test, foo=1), 1)
def test(a, *, foo=1, bar):
return foo
with self.assertRaisesRegex(TypeError,
"missing a required argument: 'bar'"):
self.call(test, 1)
def test(foo, *, bar):
return foo, bar
self.assertEqual(self.call(test, 1, bar=2), (1, 2))
self.assertEqual(self.call(test, bar=2, foo=1), (1, 2))
with self.assertRaisesRegex(
TypeError, "got an unexpected keyword argument 'spam'"):
self.call(test, bar=2, foo=1, spam=10)
with self.assertRaisesRegex(TypeError,
'too many positional arguments'):
self.call(test, 1, 2)
with self.assertRaisesRegex(TypeError,
'too many positional arguments'):
self.call(test, 1, 2, bar=2)
with self.assertRaisesRegex(
TypeError, "got an unexpected keyword argument 'spam'"):
self.call(test, 1, bar=2, spam='ham')
with self.assertRaisesRegex(TypeError,
"missing a required keyword-only "
"argument: 'bar'"):
self.call(test, 1)
def test(foo, *, bar, **bin):
return foo, bar, bin
self.assertEqual(self.call(test, 1, bar=2), (1, 2, {}))
self.assertEqual(self.call(test, foo=1, bar=2), (1, 2, {}))
self.assertEqual(self.call(test, 1, bar=2, spam='ham'),
(1, 2, {'spam': 'ham'}))
self.assertEqual(self.call(test, spam='ham', foo=1, bar=2),
(1, 2, {'spam': 'ham'}))
with self.assertRaisesRegex(TypeError,
"missing a required argument: 'foo'"):
self.call(test, spam='ham', bar=2)
self.assertEqual(self.call(test, 1, bar=2, bin=1, spam=10),
(1, 2, {'bin': 1, 'spam': 10}))
def test_signature_bind_arguments(self):
def test(a, *args, b, z=100, **kwargs):
pass
sig = inspect.signature(test)
ba = sig.bind(10, 20, b=30, c=40, args=50, kwargs=60)
# we won't have 'z' argument in the bound arguments object, as we didn't
# pass it to the 'bind'
self.assertEqual(tuple(ba.arguments.items()),
(('a', 10), ('args', (20,)), ('b', 30),
('kwargs', {'c': 40, 'args': 50, 'kwargs': 60})))
self.assertEqual(ba.kwargs,
{'b': 30, 'c': 40, 'args': 50, 'kwargs': 60})
self.assertEqual(ba.args, (10, 20))
def test_signature_bind_positional_only(self):
def test(a_po, b_po, c_po=3, /, foo=42, *, bar=50, **kwargs):
return a_po, b_po, c_po, foo, bar, kwargs
self.assertEqual(self.call(test, 1, 2, 4, 5, bar=6),
(1, 2, 4, 5, 6, {}))
self.assertEqual(self.call(test, 1, 2),
(1, 2, 3, 42, 50, {}))
self.assertEqual(self.call(test, 1, 2, foo=4, bar=5),
(1, 2, 3, 4, 5, {}))
self.assertEqual(self.call(test, 1, 2, foo=4, bar=5, c_po=10),
(1, 2, 3, 4, 5, {'c_po': 10}))
self.assertEqual(self.call(test, 1, 2, 30, c_po=31, foo=4, bar=5),
(1, 2, 30, 4, 5, {'c_po': 31}))
self.assertEqual(self.call(test, 1, 2, 30, foo=4, bar=5, c_po=31),
(1, 2, 30, 4, 5, {'c_po': 31}))
self.assertEqual(self.call(test, 1, 2, c_po=4),
(1, 2, 3, 42, 50, {'c_po': 4}))
with self.assertRaisesRegex(TypeError, "missing a required positional-only argument: 'a_po'"):
self.call(test, a_po=1, b_po=2)
def without_var_kwargs(c_po=3, d_po=4, /):
return c_po, d_po
with self.assertRaisesRegex(
TypeError,
"positional-only arguments passed as keyword arguments: 'c_po, d_po'",
):
self.call(without_var_kwargs, c_po=33, d_po=44)
def test_signature_bind_with_self_arg(self):
# Issue #17071: one of the parameters is named "self
def test(a, self, b):
pass
sig = inspect.signature(test)
ba = sig.bind(1, 2, 3)
self.assertEqual(ba.args, (1, 2, 3))
ba = sig.bind(1, self=2, b=3)
self.assertEqual(ba.args, (1, 2, 3))
def test_signature_bind_vararg_name(self):
def test(a, *args):
return a, args
sig = inspect.signature(test)
with self.assertRaisesRegex(
TypeError, "got an unexpected keyword argument 'args'"):
sig.bind(a=0, args=1)
def test(*args, **kwargs):
return args, kwargs
self.assertEqual(self.call(test, args=1), ((), {'args': 1}))
sig = inspect.signature(test)
ba = sig.bind(args=1)
self.assertEqual(ba.arguments, {'kwargs': {'args': 1}})
@cpython_only
def test_signature_bind_implicit_arg(self):
# Issue #19611: getcallargs should work with comprehensions
def make_set():
return set(z * z for z in range(5))
gencomp_code = make_set.__code__.co_consts[1]
gencomp_func = types.FunctionType(gencomp_code, {})
iterator = iter(range(5))
self.assertEqual(set(self.call(gencomp_func, iterator)), {0, 1, 4, 9, 16})
def test_signature_bind_posonly_kwargs(self):
def foo(bar, /, **kwargs):
return bar, kwargs.get(bar)
sig = inspect.signature(foo)
result = sig.bind("pos-only", bar="keyword")
self.assertEqual(result.kwargs, {"bar": "keyword"})
self.assertIn(("bar", "pos-only"), result.arguments.items())
class TestBoundArguments(unittest.TestCase):
def test_signature_bound_arguments_unhashable(self):
def foo(a): pass
ba = inspect.signature(foo).bind(1)
with self.assertRaisesRegex(TypeError, 'unhashable type'):
hash(ba)
def test_signature_bound_arguments_equality(self):
def foo(a): pass
ba = inspect.signature(foo).bind(1)
self.assertTrue(ba == ba)
self.assertFalse(ba != ba)
self.assertTrue(ba == ALWAYS_EQ)
self.assertFalse(ba != ALWAYS_EQ)
ba2 = inspect.signature(foo).bind(1)
self.assertTrue(ba == ba2)
self.assertFalse(ba != ba2)
ba3 = inspect.signature(foo).bind(2)
self.assertFalse(ba == ba3)
self.assertTrue(ba != ba3)
ba3.arguments['a'] = 1
self.assertTrue(ba == ba3)
self.assertFalse(ba != ba3)
def bar(b): pass
ba4 = inspect.signature(bar).bind(1)
self.assertFalse(ba == ba4)
self.assertTrue(ba != ba4)
def foo(*, a, b): pass
sig = inspect.signature(foo)
ba1 = sig.bind(a=1, b=2)
ba2 = sig.bind(b=2, a=1)
self.assertTrue(ba1 == ba2)
self.assertFalse(ba1 != ba2)
def test_signature_bound_arguments_pickle(self):
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass
sig = inspect.signature(foo)
ba = sig.bind(20, 30, z={})
for ver in range(pickle.HIGHEST_PROTOCOL + 1):
with self.subTest(pickle_ver=ver):
ba_pickled = pickle.loads(pickle.dumps(ba, ver))
self.assertEqual(ba, ba_pickled)
def test_signature_bound_arguments_repr(self):
def foo(a, b, *, c:1={}, **kw) -> {42:'ham'}: pass
sig = inspect.signature(foo)
ba = sig.bind(20, 30, z={})
self.assertRegex(repr(ba), r'<BoundArguments \(a=20,.*\}\}\)>')
def test_signature_bound_arguments_apply_defaults(self):
def foo(a, b=1, *args, c:1={}, **kw): pass
sig = inspect.signature(foo)
ba = sig.bind(20)
ba.apply_defaults()
self.assertEqual(
list(ba.arguments.items()),
[('a', 20), ('b', 1), ('args', ()), ('c', {}), ('kw', {})])
# Make sure that we preserve the order:
# i.e. 'c' should be *before* 'kw'.
ba = sig.bind(10, 20, 30, d=1)
ba.apply_defaults()
self.assertEqual(
list(ba.arguments.items()),
[('a', 10), ('b', 20), ('args', (30,)), ('c', {}), ('kw', {'d':1})])
# Make sure that BoundArguments produced by bind_partial()
# are supported.
def foo(a, b): pass
sig = inspect.signature(foo)
ba = sig.bind_partial(20)
ba.apply_defaults()
self.assertEqual(
list(ba.arguments.items()),
[('a', 20)])
# Test no args
def foo(): pass
sig = inspect.signature(foo)
ba = sig.bind()
ba.apply_defaults()
self.assertEqual(list(ba.arguments.items()), [])
# Make sure a no-args binding still acquires proper defaults.
def foo(a='spam'): pass
sig = inspect.signature(foo)
ba = sig.bind()
ba.apply_defaults()
self.assertEqual(list(ba.arguments.items()), [('a', 'spam')])
def test_signature_bound_arguments_arguments_type(self):
def foo(a): pass
ba = inspect.signature(foo).bind(1)
self.assertIs(type(ba.arguments), dict)
class TestSignaturePrivateHelpers(unittest.TestCase):
def _strip_non_python_syntax(self, input,
clean_signature, self_parameter):
computed_clean_signature, \
computed_self_parameter = \
inspect._signature_strip_non_python_syntax(input)
self.assertEqual(computed_clean_signature, clean_signature)
self.assertEqual(computed_self_parameter, self_parameter)
def test_signature_strip_non_python_syntax(self):
self._strip_non_python_syntax(
"($module, /, path, mode, *, dir_fd=None, " +
"effective_ids=False,\n follow_symlinks=True)",
"(module, /, path, mode, *, dir_fd=None, " +
"effective_ids=False, follow_symlinks=True)",
0)
self._strip_non_python_syntax(
"($module, word, salt, /)",
"(module, word, salt, /)",
0)
self._strip_non_python_syntax(
"(x, y=None, z=None, /)",
"(x, y=None, z=None, /)",
None)
self._strip_non_python_syntax(
"(x, y=None, z=None)",
"(x, y=None, z=None)",
None)
self._strip_non_python_syntax(
"(x,\n y=None,\n z = None )",
"(x, y=None, z=None)",
None)
self._strip_non_python_syntax(
"",
"",
None)
self._strip_non_python_syntax(
None,
None,
None)
class TestSignatureDefinitions(unittest.TestCase):
# This test case provides a home for checking that particular APIs
# have signatures available for introspection
@staticmethod
def is_public(name):
return not name.startswith('_') or name.startswith('__') and name.endswith('__')
@cpython_only
@unittest.skipIf(MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def _test_module_has_signatures(self, module,
no_signature=(), unsupported_signature=(),
methods_no_signature={}, methods_unsupported_signature={},
good_exceptions=()):
# This checks all builtin callables in CPython have signatures
# A few have signatures Signature can't yet handle, so we skip those
# since they will have to wait until PEP 457 adds the required
# introspection support to the inspect module
# Some others also haven't been converted yet for various other
# reasons, so we also skip those for the time being, but design
# the test to fail in order to indicate when it needs to be
# updated.
no_signature = no_signature or set()
# Check the signatures we expect to be there
ns = vars(module)
try:
names = set(module.__all__)
except AttributeError:
names = set(name for name in ns if self.is_public(name))
for name, obj in sorted(ns.items()):
if name not in names:
continue
if not callable(obj):
continue
if (isinstance(obj, type) and
issubclass(obj, BaseException) and
name not in good_exceptions):
no_signature.add(name)
if name not in no_signature and name not in unsupported_signature:
with self.subTest('supported', builtin=name):
self.assertIsNotNone(inspect.signature(obj))
if isinstance(obj, type):
with self.subTest(type=name):
self._test_builtin_methods_have_signatures(obj,
methods_no_signature.get(name, ()),
methods_unsupported_signature.get(name, ()))
# Check callables that haven't been converted don't claim a signature
# This ensures this test will start failing as more signatures are
# added, so the affected items can be moved into the scope of the
# regression test above
for name in no_signature:
with self.subTest('none', builtin=name):
obj = ns[name]
self.assertIsNone(obj.__text_signature__)
self.assertRaises(ValueError, inspect.signature, obj)
for name in unsupported_signature:
with self.subTest('unsupported', builtin=name):
obj = ns[name]
self.assertIsNotNone(obj.__text_signature__)
self.assertRaises(ValueError, inspect.signature, obj)
def _test_builtin_methods_have_signatures(self, cls, no_signature, unsupported_signature):
ns = vars(cls)
for name in ns:
obj = getattr(cls, name, None)
if not callable(obj) or isinstance(obj, type):
continue
if name not in no_signature and name not in unsupported_signature:
with self.subTest('supported', method=name):
self.assertIsNotNone(inspect.signature(obj))
for name in no_signature:
with self.subTest('none', method=name):
self.assertIsNone(getattr(cls, name).__text_signature__)
self.assertRaises(ValueError, inspect.signature, getattr(cls, name))
for name in unsupported_signature:
with self.subTest('unsupported', method=name):
self.assertIsNotNone(getattr(cls, name).__text_signature__)
self.assertRaises(ValueError, inspect.signature, getattr(cls, name))
def test_builtins_have_signatures(self):
no_signature = {'type', 'super', 'bytearray', 'bytes', 'dict', 'int', 'str'}
# These need PEP 457 groups
needs_groups = {"range", "slice", "dir", "getattr",
"next", "iter", "vars"}
no_signature |= needs_groups
# These have unrepresentable parameter default values of NULL
unsupported_signature = {"anext"}
# These need *args support in Argument Clinic
needs_varargs = {"min", "max", "__build_class__"}
no_signature |= needs_varargs
methods_no_signature = {
'dict': {'update'},
'object': {'__class__'},
}
methods_unsupported_signature = {
'bytearray': {'count', 'endswith', 'find', 'hex', 'index', 'rfind', 'rindex', 'startswith'},
'bytes': {'count', 'endswith', 'find', 'hex', 'index', 'rfind', 'rindex', 'startswith'},
'dict': {'pop'},
'int': {'__round__'},
'memoryview': {'cast', 'hex'},
'str': {'count', 'endswith', 'find', 'index', 'maketrans', 'rfind', 'rindex', 'startswith'},
}
self._test_module_has_signatures(builtins,
no_signature, unsupported_signature,
methods_no_signature, methods_unsupported_signature)
def test_types_module_has_signatures(self):
unsupported_signature = {'CellType'}
methods_no_signature = {
'AsyncGeneratorType': {'athrow'},
'CoroutineType': {'throw'},
'GeneratorType': {'throw'},
}
self._test_module_has_signatures(types,
unsupported_signature=unsupported_signature,
methods_no_signature=methods_no_signature)
def test_sys_module_has_signatures(self):
no_signature = {'getsizeof', 'set_asyncgen_hooks'}
no_signature |= {name for name in ['getobjects']
if hasattr(sys, name)}
self._test_module_has_signatures(sys, no_signature)
def test_abc_module_has_signatures(self):
import abc
self._test_module_has_signatures(abc)
def test_atexit_module_has_signatures(self):
import atexit
self._test_module_has_signatures(atexit)
def test_codecs_module_has_signatures(self):
import codecs
methods_no_signature = {'StreamReader': {'charbuffertype'}}
self._test_module_has_signatures(codecs,
methods_no_signature=methods_no_signature)
def test_collections_module_has_signatures(self):
no_signature = {'OrderedDict', 'defaultdict'}
unsupported_signature = {'deque'}
methods_no_signature = {
'OrderedDict': {'update'},
}
methods_unsupported_signature = {
'deque': {'index'},
'OrderedDict': {'pop'},
'UserString': {'maketrans'},
}
self._test_module_has_signatures(collections,
no_signature, unsupported_signature,
methods_no_signature, methods_unsupported_signature)
def test_collections_abc_module_has_signatures(self):
import collections.abc
self._test_module_has_signatures(collections.abc)
def test_errno_module_has_signatures(self):
import errno
self._test_module_has_signatures(errno)
def test_faulthandler_module_has_signatures(self):
import faulthandler
unsupported_signature = {'dump_traceback', 'dump_traceback_later', 'enable'}
unsupported_signature |= {name for name in ['register']
if hasattr(faulthandler, name)}
self._test_module_has_signatures(faulthandler, unsupported_signature=unsupported_signature)
def test_functools_module_has_signatures(self):
no_signature = {'reduce'}
self._test_module_has_signatures(functools, no_signature)
def test_gc_module_has_signatures(self):
import gc
no_signature = {'set_threshold'}
self._test_module_has_signatures(gc, no_signature)
def test_io_module_has_signatures(self):
methods_no_signature = {
'BufferedRWPair': {'read', 'peek', 'read1', 'readinto', 'readinto1', 'write'},
}
self._test_module_has_signatures(io,
methods_no_signature=methods_no_signature)
def test_itertools_module_has_signatures(self):
import itertools
no_signature = {'islice', 'repeat'}
self._test_module_has_signatures(itertools, no_signature)
def test_locale_module_has_signatures(self):
import locale
self._test_module_has_signatures(locale)
def test_marshal_module_has_signatures(self):
import marshal
self._test_module_has_signatures(marshal)
def test_operator_module_has_signatures(self):
import operator
self._test_module_has_signatures(operator)
def test_os_module_has_signatures(self):
unsupported_signature = {'chmod', 'utime'}
unsupported_signature |= {name for name in
['get_terminal_size', 'posix_spawn', 'posix_spawnp',
'register_at_fork', 'startfile']
if hasattr(os, name)}
self._test_module_has_signatures(os, unsupported_signature=unsupported_signature)
def test_pwd_module_has_signatures(self):
pwd = import_helper.import_module('pwd')
self._test_module_has_signatures(pwd)
def test_re_module_has_signatures(self):
import re
methods_no_signature = {'Match': {'group'}}
self._test_module_has_signatures(re,
methods_no_signature=methods_no_signature,
good_exceptions={'error', 'PatternError'})
def test_signal_module_has_signatures(self):
import signal
self._test_module_has_signatures(signal)
def test_stat_module_has_signatures(self):
import stat
self._test_module_has_signatures(stat)
def test_string_module_has_signatures(self):
import string
self._test_module_has_signatures(string)
def test_symtable_module_has_signatures(self):
import symtable
self._test_module_has_signatures(symtable)
def test_sysconfig_module_has_signatures(self):
import sysconfig
self._test_module_has_signatures(sysconfig)
def test_threading_module_has_signatures(self):
import threading
self._test_module_has_signatures(threading)
self.assertIsNotNone(inspect.signature(threading.__excepthook__))
def test_thread_module_has_signatures(self):
import _thread
no_signature = {'RLock'}
self._test_module_has_signatures(_thread, no_signature)
def test_time_module_has_signatures(self):
no_signature = {
'asctime', 'ctime', 'get_clock_info', 'gmtime', 'localtime',
'strftime', 'strptime'
}
no_signature |= {name for name in
['clock_getres', 'clock_settime', 'clock_settime_ns',
'pthread_getcpuclockid']
if hasattr(time, name)}
self._test_module_has_signatures(time, no_signature)
def test_tokenize_module_has_signatures(self):
import tokenize
self._test_module_has_signatures(tokenize)
def test_tracemalloc_module_has_signatures(self):
import tracemalloc
self._test_module_has_signatures(tracemalloc)
def test_typing_module_has_signatures(self):
import typing
no_signature = {'ParamSpec', 'ParamSpecArgs', 'ParamSpecKwargs',
'Text', 'TypeAliasType', 'TypeVar', 'TypeVarTuple'}
methods_no_signature = {
'Generic': {'__class_getitem__', '__init_subclass__'},
}
methods_unsupported_signature = {
'Text': {'count', 'find', 'index', 'rfind', 'rindex', 'startswith', 'endswith', 'maketrans'},
}
self._test_module_has_signatures(typing, no_signature,
methods_no_signature=methods_no_signature,
methods_unsupported_signature=methods_unsupported_signature)
def test_warnings_module_has_signatures(self):
unsupported_signature = {'warn', 'warn_explicit'}
self._test_module_has_signatures(warnings, unsupported_signature=unsupported_signature)
def test_weakref_module_has_signatures(self):
import weakref
no_signature = {'ReferenceType', 'ref'}
self._test_module_has_signatures(weakref, no_signature)
def test_python_function_override_signature(self):
def func(*args, **kwargs):
pass
func.__text_signature__ = '($self, a, b=1, *args, c, d=2, **kwargs)'
sig = inspect.signature(func)
self.assertIsNotNone(sig)
self.assertEqual(str(sig), '(self, /, a, b=1, *args, c, d=2, **kwargs)')
func.__text_signature__ = '($self, a, b=1, /, *args, c, d=2, **kwargs)'
sig = inspect.signature(func)
self.assertEqual(str(sig), '(self, a, b=1, /, *args, c, d=2, **kwargs)')
func.__text_signature__ = '(self, a=1+2, b=4-3, c=1 | 3 | 16)'
sig = inspect.signature(func)
self.assertEqual(str(sig), '(self, a=3, b=1, c=19)')
func.__text_signature__ = '(self, a=1,\nb=2,\n\n\n c=3)'
sig = inspect.signature(func)
self.assertEqual(str(sig), '(self, a=1, b=2, c=3)')
func.__text_signature__ = '(self, x=does_not_exist)'
with self.assertRaises(ValueError):
inspect.signature(func)
func.__text_signature__ = '(self, x=sys, y=inspect)'
with self.assertRaises(ValueError):
inspect.signature(func)
func.__text_signature__ = '(self, 123)'
with self.assertRaises(ValueError):
inspect.signature(func)
@support.requires_docstrings
def test_base_class_have_text_signature(self):
# see issue 43118
from test.typinganndata.ann_module7 import BufferedReader
class MyBufferedReader(BufferedReader):
"""buffer reader class."""
text_signature = BufferedReader.__text_signature__
self.assertEqual(text_signature, '(raw, buffer_size=DEFAULT_BUFFER_SIZE)')
sig = inspect.signature(MyBufferedReader)
self.assertEqual(str(sig), '(raw, buffer_size=8192)')
class NTimesUnwrappable:
def __init__(self, n):
self.n = n
self._next = None
@property
def __wrapped__(self):
if self.n <= 0:
raise Exception("Unwrapped too many times")
if self._next is None:
self._next = NTimesUnwrappable(self.n - 1)
return self._next
class TestUnwrap(unittest.TestCase):
def test_unwrap_one(self):
def func(a, b):
return a + b
wrapper = functools.lru_cache(maxsize=20)(func)
self.assertIs(inspect.unwrap(wrapper), func)
def test_unwrap_several(self):
def func(a, b):
return a + b
wrapper = func
for __ in range(10):
@functools.wraps(wrapper)
def wrapper():
pass
self.assertIsNot(wrapper.__wrapped__, func)
self.assertIs(inspect.unwrap(wrapper), func)
def test_stop(self):
def func1(a, b):
return a + b
@functools.wraps(func1)
def func2():
pass
@functools.wraps(func2)
def wrapper():
pass
func2.stop_here = 1
unwrapped = inspect.unwrap(wrapper,
stop=(lambda f: hasattr(f, "stop_here")))
self.assertIs(unwrapped, func2)
def test_cycle(self):
def func1(): pass
func1.__wrapped__ = func1
with self.assertRaisesRegex(ValueError, 'wrapper loop'):
inspect.unwrap(func1)
def func2(): pass
func2.__wrapped__ = func1
func1.__wrapped__ = func2
with self.assertRaisesRegex(ValueError, 'wrapper loop'):
inspect.unwrap(func1)
with self.assertRaisesRegex(ValueError, 'wrapper loop'):
inspect.unwrap(func2)
def test_unhashable(self):
def func(): pass
func.__wrapped__ = None
class C:
__hash__ = None
__wrapped__ = func
self.assertIsNone(inspect.unwrap(C()))
def test_recursion_limit(self):
obj = NTimesUnwrappable(sys.getrecursionlimit() + 1)
with self.assertRaisesRegex(ValueError, 'wrapper loop'):
inspect.unwrap(obj)
def test_wrapped_descriptor(self):
self.assertIs(inspect.unwrap(NTimesUnwrappable), NTimesUnwrappable)
self.assertIs(inspect.unwrap(staticmethod), staticmethod)
self.assertIs(inspect.unwrap(classmethod), classmethod)
self.assertIs(inspect.unwrap(staticmethod(classmethod)), classmethod)
self.assertIs(inspect.unwrap(classmethod(staticmethod)), staticmethod)
class TestMain(unittest.TestCase):
def test_only_source(self):
module = importlib.import_module('unittest')
rc, out, err = assert_python_ok('-m', 'inspect',
'unittest')
lines = out.decode().splitlines()
# ignore the final newline
self.assertEqual(lines[:-1], inspect.getsource(module).splitlines())
self.assertEqual(err, b'')
def test_custom_getattr(self):
def foo():
pass
foo.__signature__ = 42
with self.assertRaises(TypeError):
inspect.signature(foo)
@unittest.skipIf(ThreadPoolExecutor is None,
'threads required to test __qualname__ for source files')
def test_qualname_source(self):
rc, out, err = assert_python_ok('-m', 'inspect',
'concurrent.futures:ThreadPoolExecutor')
lines = out.decode().splitlines()
# ignore the final newline
self.assertEqual(lines[:-1],
inspect.getsource(ThreadPoolExecutor).splitlines())
self.assertEqual(err, b'')
def test_builtins(self):
_, out, err = assert_python_failure('-m', 'inspect',
'sys')
lines = err.decode().splitlines()
self.assertEqual(lines, ["Can't get info for builtin modules."])
def test_details(self):
module = importlib.import_module('unittest')
args = support.optim_args_from_interpreter_flags()
rc, out, err = assert_python_ok(*args, '-m', 'inspect',
'unittest', '--details')
output = out.decode()
# Just a quick sanity check on the output
self.assertIn(module.__spec__.name, output)
self.assertIn(module.__name__, output)
self.assertIn(module.__spec__.origin, output)
self.assertIn(module.__file__, output)
self.assertIn(module.__spec__.cached, output)
self.assertIn(module.__cached__, output)
self.assertEqual(err, b'')
class TestReload(unittest.TestCase):
src_before = textwrap.dedent("""\
def foo():
print("Bla")
""")
src_after = textwrap.dedent("""\
def foo():
print("Oh no!")
""")
def assertInspectEqual(self, path, source):
inspected_src = inspect.getsource(source)
with open(path, encoding='utf-8') as src:
self.assertEqual(
src.read().splitlines(True),
inspected_src.splitlines(True)
)
def test_getsource_reload(self):
# see issue 1218234
with ready_to_import('reload_bug', self.src_before) as (name, path):
module = importlib.import_module(name)
self.assertInspectEqual(path, module)
with open(path, 'w', encoding='utf-8') as src:
src.write(self.src_after)
self.assertInspectEqual(path, module)
class TestRepl(unittest.TestCase):
def spawn_repl(self, *args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **kw):
"""Run the Python REPL with the given arguments.
kw is extra keyword args to pass to subprocess.Popen. Returns a Popen
object.
"""
# To run the REPL without using a terminal, spawn python with the command
# line option '-i' and the process name set to '<stdin>'.
# The directory of argv[0] must match the directory of the Python
# executable for the Popen() call to python to succeed as the directory
# path may be used by Py_GetPath() to build the default module search
# path.
stdin_fname = os.path.join(os.path.dirname(sys.executable), "<stdin>")
cmd_line = [stdin_fname, '-E', '-i']
cmd_line.extend(args)
# Set TERM=vt100, for the rationale see the comments in spawn_python() of
# test.support.script_helper.
env = kw.setdefault('env', dict(os.environ))
env['TERM'] = 'vt100'
return subprocess.Popen(cmd_line,
executable=sys.executable,
text=True,
stdin=subprocess.PIPE,
stdout=stdout, stderr=stderr,
**kw)
def run_on_interactive_mode(self, source):
"""Spawn a new Python interpreter, pass the given
input source code from the stdin and return the
result back. If the interpreter exits non-zero, it
raises a ValueError."""
process = self.spawn_repl()
process.stdin.write(source)
output = kill_python(process)
if process.returncode != 0:
raise ValueError("Process didn't exit properly.")
return output
@unittest.skipIf(not has_subprocess_support, "test requires subprocess")
def test_getsource(self):
output = self.run_on_interactive_mode(textwrap.dedent("""\
def f():
print(0)
return 1 + 2
import inspect
print(f"The source is: <<<{inspect.getsource(f)}>>>")
"""))
expected = "The source is: <<<def f():\n print(0)\n return 1 + 2\n>>>"
self.assertIn(expected, output)
if __name__ == "__main__":
unittest.main()
|