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
|
.. _api:
.. cpp:namespace:: nanobind
C++ API Reference (Core)
========================
Macros
------
.. c:macro:: NB_MODULE(name, variable)
This macro creates the entry point that will be invoked when the Python
interpreter imports an extension module. The module name is given as the
first argument and it should not be in quotes. It **must** match the module
name given to the :cmake:command:`nanobind_add_module()` function in the
CMake build system.
The second macro argument defines a variable of type :cpp:class:`module_`.
The body of the declaration typically contains a sequence of operations
that populate the module variable with contents.
.. code-block:: cpp
NB_MODULE(example, m) {
m.doc() = "Example module";
// Add bindings here
m.def("add", []() {
return "Hello, World!";
});
}
.. c:macro:: NB_MAKE_OPAQUE(T)
The macro registers a partial template specialization pattern for the type
`T` that marks it as *opaque*, meaning that nanobind won't try to run its
type casting template machinery on it.
This is useful when trying to register a binding for `T` that is simultaneously
also covered by an existing type caster.
This macro should be used at the top level (outside of namespaces and
program code).
Python object API
-----------------
Nanobind ships with a wide range of Python wrapper classes like
:cpp:class:`object`, :cpp:class:`list`, etc. Besides class-specific operations
(e.g., :cpp:func:`list::append`), these classes also implement core operations
that can be performed on *any* Python object. Since it would be tedious to
implement this functionality over and over again, it is realized by the
following mixin class that lives in the ``nanobind::detail`` namespace.
.. cpp:namespace:: nanobind::detail
.. cpp:class:: template <typename Derived> api
This mixin class adds common functionality to various nanobind types using
the `curiously recurring template pattern
<https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern>`_
(CRTP). The only requirement for the `Derived` template parameter is that it
implements the member function ``PyObject *ptr() const`` that gives access
to the underlying Python object pointer.
.. cpp:function:: Derived &derived()
Obtain a mutable reference to the derived class.
.. cpp:function:: const Derived &derived() const
Obtain a const reference to the derived class.
.. cpp:function:: handle inc_ref() const
Increases the reference count and returns a reference to the Python object.
.. cpp:function:: handle dec_ref() const
Decreases the reference count and returns a reference to the Python object.
.. cpp:function:: iterator begin() const
Return a forward iterator analogous to ``iter()`` in Python. The object
must be a collection that supports the iteration protocol. This interface
provides a generic iterator that works any type of Python object. The
:cpp:class:`tuple`, :cpp:class:`list`, and :cpp:class:`dict` wrappers
provide more efficient specialized alternatives.
.. cpp:function:: iterator end() const
Return a sentinel that ends the iteration.
.. cpp:function:: handle type() const
Return a :cpp:class:`handle` to the underlying Python type object.
.. cpp:function:: operator handle() const
Return a :cpp:class:`handle` wrapping the underlying ``PyObject*`` pointer.
.. cpp:function:: detail::accessor<obj_attr> attr(handle key) const
Analogous to ``self.key`` in Python, where ``key`` is a Python object.
The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so
that it can be read and written.
.. cpp:function:: detail::accessor<str_attr> attr(const char * key) const
Analogous to ``self.key`` in Python, where ``key`` is a C-style string.
The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so
that it can be read and written.
.. cpp:function:: detail::accessor<str_attr> doc() const
Analogous to ``self.__doc__``. The result is wrapped in an
:cpp:class:`accessor <detail::accessor>` so that it can be read and
written.
.. cpp:function:: detail::accessor<obj_item> operator[](handle key) const
Analogous to ``self[key]`` in Python, where ``key`` is a Python object.
The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so that it can be read and
written.
.. cpp:function:: detail::accessor<str_item> operator[](const char * key) const
Analogous to ``self[key]`` in Python, where ``key`` is a C-style string.
The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so that it can be read and
written.
.. cpp:function:: template <typename T, enable_if_t<std::is_arithmetic_v<T>> = 1> detail::accessor<num_item> operator[](T key) const
Analogous to ``self[key]`` in Python, where ``key`` is an arithmetic
type (e.g., an integer). The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so
that it can be read and written.
.. cpp:function:: template <rv_policy policy = rv_policy::automatic_reference, typename... Args> object operator()(Args &&...args) const
Assuming the Python object is a function or implements the ``__call__``
protocol, `operator()` invokes the underlying function, passing an
arbitrary set of parameters, while expanding any detected variable length
argument and keyword argument packs. The result is returned as an
:cpp:class:`object` and may need to be converted back into a Python
object using :cpp:func:`cast()`.
Type conversion is performed using the return value policy `policy`
When type conversion of arguments or return value fails, the function
raises a :cpp:type:`cast_error`. When the Python function call fails, it
instead raises a :cpp:class:`python_error`.
.. cpp:function:: args_proxy operator*() const
Given a a tuple or list, this helper function performs variable argument
list unpacking in function calls resembling the ``*`` operator in Python.
Applying `operator*()` twice yields ``**`` keyword argument
unpacking for dictionaries.
.. cpp:function:: bool is(handle value) const
Analogous to ``self is value`` in Python.
.. cpp:function:: bool is_none() const
Analogous to ``self is None`` in Python.
.. cpp:function:: bool is_type() const
Analogous to ``isinstance(self, type)`` in Python.
.. cpp:function:: bool is_valid() const
Checks if this wrapper contains a valid Python object (in the sense that
the ``PyObject *`` pointer is non-null).
.. cpp:function:: template <typename T> bool equal(const api<T> &other)
Equivalent to ``self == other`` in Python.
.. cpp:function:: template <typename T> bool not_equal(const api<T> &other)
Equivalent to ``self != other`` in Python.
.. cpp:function:: template <typename T> bool operator<(const api<T> &other)
Equivalent to ``self < other`` in Python.
.. cpp:function:: template <typename T> bool operator<=(const api<T> &other)
Equivalent to ``self <= other`` in Python.
.. cpp:function:: template <typename T> bool operator>(const api<T> &other)
Equivalent to ``self > other`` in Python.
.. cpp:function:: template <typename T> bool operator>=(const api<T> &other)
Equivalent to ``self >= other`` in Python.
.. cpp:function:: object operator-()
Equivalent to ``-self`` in Python.
.. cpp:function:: object operator~()
Equivalent to ``~self`` in Python.
.. cpp:function:: template <typename T> object operator+(const api<T> &other)
Equivalent to ``self + other`` in Python.
.. cpp:function:: template <typename T> object operator-(const api<T> &other)
Equivalent to ``self - other`` in Python.
.. cpp:function:: template <typename T> object operator*(const api<T> &other)
Equivalent to ``self * other`` in Python.
.. cpp:function:: template <typename T> object operator/(const api<T> &other)
Equivalent to ``self / other`` in Python.
.. cpp:function:: template <typename T> object floor_div(const api<T> &other)
Equivalent to ``self // other`` in Python.
.. cpp:function:: template <typename T> object operator|(const api<T> &other)
Equivalent to ``self | other`` in Python.
.. cpp:function:: template <typename T> object operator&(const api<T> &other)
Equivalent to ``self & other`` in Python.
.. cpp:function:: template <typename T> object operator^(const api<T> &other)
Equivalent to ``self ^ other`` in Python.
.. cpp:function:: template <typename T> object operator<<(const api<T> &other)
Equivalent to ``self << other`` in Python.
.. cpp:function:: template <typename T> object operator>>(const api<T> &other)
Equivalent to ``self >> other`` in Python.
.. cpp:function:: template <typename T> object operator+=(const api<T> &other)
Equivalent to ``self += other`` in Python. Note that the `api<T>` version
of the in-place operator does not update the ``self`` reference, which
may lead to unexpected results when working with immutable types that
return their result instead of updating ``self``.
The :cpp:class:`object` class and subclasses override the in-place
operators to achieve more intuitive behavior.
.. cpp:function:: template <typename T> object operator-=(const api<T> &other)
Equivalent to ``self -= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator*=(const api<T> &other)
Equivalent to ``self *= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator/=(const api<T> &other)
Equivalent to ``self /= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator|=(const api<T> &other)
Equivalent to ``self |= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator&=(const api<T> &other)
Equivalent to ``self &= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator^=(const api<T> &other)
Equivalent to ``self ^= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator<<=(const api<T> &other)
Equivalent to ``self <<= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:function:: template <typename T> object operator>>=(const api<T> &other)
Equivalent to ``self >>= other`` in Python. See :cpp:func:`operator+=` for limitations.
.. cpp:class:: template <typename Impl> accessor
This helper class facilitates attribute and item access. Casting an
:cpp:class:`accessor` to a :cpp:class:`handle` or :cpp:class:`object`
subclass causes a corresponding call to ``__getitem__`` or ``__getattr__``
depending on the template argument `Impl`. Assigning a
:cpp:class:`handle` or :cpp:class:`object` subclass causes a call to
``__setitem__`` or ``__setattr__``.
.. cpp:namespace:: nanobind
Handles and objects
-------------------
nanobind provides two styles of Python object wrappers: classes without
reference counting deriving from :cpp:class:`handle`, and reference-counted
wrappers deriving from :cpp:class:`object`. Reference counting bugs can be
really tricky to track down, hence it is recommended that you always prefer
:cpp:class:`object`-style wrappers unless there are specific reasons that
warrant the use of raw handles.
Without reference counting
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. cpp:class:: handle: public detail::api<handle>
This class provides a thin wrapper around a raw ``PyObject *`` pointer. Its
main purpose is to intercept various C++ operations and convert them into
Python C API calls. It does *not* do any reference counting and can be
somewhat unsafe to use.
.. cpp:function:: handle() = default
Default constructor. Creates an invalid handle wrapping a null pointer.
(:cpp:func:`detail::api::is_valid()` is ``false``)
.. cpp:function:: handle(const handle &) = default
Default copy constructor.
.. cpp:function:: handle(handle &&) = default
Default move constructor.
.. cpp:function:: handle(const PyObject * o)
Initialize a handle from a Python object pointer. Does not change the reference count of `o`.
.. cpp:function:: handle(const PyTypeObject * o)
Initialize a handle from a Python type object pointer. Does not change the reference count of `o`.
.. cpp:function:: handle &operator=(const handle &) = default
Default copy assignment operator.
.. cpp:function:: handle &operator=(handle &&) = default
Default move assignment operator.
.. cpp:function:: explicit operator bool() const
Check if the handle refers to a valid Python object. Equivalent to
:cpp:func:`detail::api::is_valid()`
.. cpp:function:: handle inc_ref() const noexcept
Increases the reference count and returns a reference to the Python object.
Never raises an exception.
.. cpp:function:: handle dec_ref() const noexcept
Decreases the reference count and returns a reference to the Python object.
Never raises an exception.
.. cpp:function:: PyObject * ptr() const
Return the underlying ``PyObject*`` pointer.
With reference counting
^^^^^^^^^^^^^^^^^^^^^^^
.. cpp:class:: object: public handle
This class provides a convenient `RAII
<https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization>`_
wrapper around a ``PyObject*`` pointer. Like :cpp:class:`handle`, it
intercepts various C++ operations and converts them into Python C API calls.
The main difference to :cpp:class:`handle` is that it uses reference
counting to keep the underlying Python object alive.
Use the :cpp:func:`borrow()` and :cpp:func:`steal()` functions to create an
:cpp:class:`object` from a :cpp:class:`handle` or ``PyObject*`` pointer.
.. cpp:function:: object() = default
Default constructor. Creates an invalid object wrapping a null pointer.
(:cpp:func:`detail::api::is_valid()` is ``false``)
.. cpp:function:: object(object &&o)
Move constructor. Steals the object from `o` without
changing its reference count.
.. cpp:function:: object(const object &o)
Copy constructor. Acquires a new reference to `o` (if valid).
.. cpp:function:: ~object()
Decrease the reference count of the referenced Python object (if valid).
.. cpp:function:: object& operator=(object &&o)
Move assignment operator. Decreases the reference count of the currently
held object (if valid) and steals the object from `o` without
changing its reference count.
.. cpp:function:: object& operator=(const object &o)
Copy assignment operator. Decreases the reference count of the currently
held object (if valid) and acquires a new reference to the object
`o` (if valid).
.. cpp:function:: void reset()
Decreases the reference count of the currently held object (if valid) and
resets the internal pointer to ``nullptr``.
.. cpp:function:: handle release()
Resets the internal pointer to ``nullptr`` and returns its previous
contents as a :cpp:class:`handle`. This operation does not change
the object's reference count and should be used carefully.
.. cpp:function:: template <typename T> object& operator+=(const api<T> &other)
Equivalent to ``self += other`` in Python.
.. cpp:function:: template <typename T> object& operator-=(const api<T> &other)
Equivalent to ``self -= other`` in Python.
.. cpp:function:: template <typename T> object& operator*=(const api<T> &other)
Equivalent to ``self *= other`` in Python.
.. cpp:function:: template <typename T> object& operator/=(const api<T> &other)
Equivalent to ``self /= other`` in Python.
.. cpp:function:: template <typename T> object& operator|=(const api<T> &other)
Equivalent to ``self |= other`` in Python.
.. cpp:function:: template <typename T> object& operator&=(const api<T> &other)
Equivalent to ``self &= other`` in Python.
.. cpp:function:: template <typename T> object& operator^=(const api<T> &other)
Equivalent to ``self ^= other`` in Python.
.. cpp:function:: template <typename T> object& operator<<=(const api<T> &other)
Equivalent to ``self <<= other`` in Python.
.. cpp:function:: template <typename T> object& operator>>=(const api<T> &other)
Equivalent to ``self >>= other`` in Python.
.. cpp:function:: template <typename T = object> T borrow(handle h)
Create a reference-counted Python object wrapper of type `T` from a raw
handle or ``PyObject *`` pointer. The target type `T` must be
:cpp:class:`object` (the default) or one of its derived classes. The
function does not perform any conversions or checks---it is up to the user
to make sure that the target type is correct.
The function *borrows* a reference, which means that it will increase the
reference count while constructing ``T``.
For example, consider the Python C API function `PyList_GetItem()
<https://docs.python.org/3/c-api/list.html#c.PyList_GetItem>`_, whose
documentation states that it returns a borrowed reference. An interface
between this API and nanobind could look as follows:
.. code-block:: cpp
PyObject* list = ...;
Py_ssize_t index = ...;
nb::object o = nb::borrow(PyList_GetItem(list, index));
Using :cpp:func:`steal()` in this setting is incorrect and would lead to a
reference underflow.
.. cpp:function:: template <typename T = object> T steal(handle h)
Create a reference-counted Python object wrapper of type `T` from a raw
handle or ``PyObject *`` pointer. The target type `T` must be
:cpp:class:`object` (the default) or one of its derived classes. The
function does not perform any conversions or checks---it is up to the user
to make sure that the target type is correct.
The function *steals* a reference, which means that constructing ``T``
leaves the object's reference count unchanged.
For example, consider the Python C API function `PyObject_Str()
<https://docs.python.org/3/c-api/object.html#c.PyObject_Str>`_, whose
documentation states that it returns a *new reference*. An interface
between this API and nanobind could look as follows:
.. code-block:: cpp
PyObject* value = ...;
nb::object o = nb::steal(PyObject_Str(value));
Using :cpp:func:`borrow()` in this setting is incorrect and would lead to a
reference leak.
Attribute access
----------------
.. cpp:function:: bool hasattr(handle h, const char * key) noexcept
Check if the given object has an attribute string ``key``. The function never
raises an exception and returns ``false`` in case of an internal error.
Equivalent to ``hasattr(h, key)`` in Python.
.. cpp:function:: bool hasattr(handle h, handle key) noexcept
Check if the given object has a attribute represented by the Python object
``key``. The function never raises an exception and returns ``false`` in
case of an internal error.
Equivalent to ``hasattr(h, key)`` in Python.
.. cpp:function:: object getattr(handle h, const char * key)
Equivalent to ``h.key`` and ``getattr(h, key)`` in Python.
Raises :cpp:class:`python_error` if the operation fails.
.. cpp:function:: object getattr(handle h, handle key)
Equivalent to ``h.key`` and ``getattr(h, key)`` in Python.
Raises :cpp:class:`python_error` if the operation fails.
.. cpp:function:: object getattr(handle h, const char * key, handle def) noexcept
Equivalent to ``getattr(h, key, def)`` in Python. Never raises an
exception and returns ``def`` when the operation fails, or when the desired
attribute could not be found.
.. cpp:function:: object getattr(handle h, handle key, handle def) noexcept
Equivalent to ``getattr(h, key, def)`` in Python. Never raises an
exception and returns ``def`` when the operation fails, or when the desired
attribute could not be found.
.. cpp:function:: void setattr(handle h, const char * key, handle value)
Equivalent to ``h.key = value`` and ``setattr(h, key, value)`` in Python.
Raises :cpp:class:`python_error` if the operation fails.
.. cpp:function:: void setattr(handle h, handle key, handle value)
Equivalent to ``h.key = value`` and ``setattr(h, key, value)`` in Python.
Raises :cpp:class:`python_error` if the operation fails.
.. cpp:function:: void delattr(handle h, const char * key)
Equivalent to ``del h.key`` and ``delattr(h, key)`` in Python.
Raises :cpp:class:`python_error` if the operation fails.
.. cpp:function:: void delattr(handle h, handle key)
Equivalent to ``del h.key`` and ``delattr(h, key)`` in Python.
Raises :cpp:class:`python_error` if the operation fails.
.. cpp:function:: template <typename T> void del(detail::accessor<T> &)
Remove an element from a sequence or mapping. The C++ statement
.. code-block:: cpp
nb::del(o[key]);
is equivalent to ``del o[key]`` in Python.
When the element cannot be removed, the function will raise
:cpp:class:`python_error` wrapping either a Python ``IndexError`` (for
sequence types) or a ``KeyError`` (for mapping types).
.. cpp:function:: template <typename T> void del(detail::accessor<T> &&)
Rvalue equivalent of the above expression.
Size queries
------------
.. cpp:function:: size_t len(handle h)
Equivalent to ``len(h)`` in Python. Raises :cpp:class:`python_error` if the
operation fails.
.. cpp:function:: size_t len(const tuple &t)
Equivalent to ``len(t)`` in Python. Optimized variant for tuples.
.. cpp:function:: size_t len(const list &l)
Equivalent to ``len(l)`` in Python. Optimized variant for lists.
.. cpp:function:: size_t len(const dict &d)
Equivalent to ``len(d)`` in Python. Optimized variant for dictionaries.
.. cpp:function:: size_t len(const set &d)
Equivalent to ``len(d)`` in Python. Optimized variant for sets.
.. cpp:function:: size_t len_hint(handle h)
Equivalent to ``operator.length_hint(h)`` in Python. Raises
:cpp:class:`python_error` if the operation fails.
Type queries
------------
.. cpp:function:: template <typename T> isinstance(handle h)
Checks if the Python object `h` represents a valid instance of the C++ type
`T`. This works for bound C++ classes, basic types (``int``, ``bool``,
etc.), and Python type wrappers ( :cpp:class:`list`, :cpp:class:`dict`,
:cpp:class:`module_`, etc.).
*Note*: the check even works when `T` involves a type caster (e.g., an STL
types like ``std::vector<float>``). However, this involve a wasteful attempt
to convert the object to C++. It may be more efficient to just perform the
conversion using :cpp:func:`cast` and catch potential raised exceptions.
.. cpp:function:: isinstance(handle inst, handle cls)
Checks if the Python object `inst` is an instance of the Python type `cls`.
.. cpp:function:: template <typename T> handle type() noexcept
Returns the Python type object associated with the C++ type `T`. When the
type not been bound via nanobind, the function returns an invalid handle
(:cpp:func:`detail::api::is_valid()` is ``false``).
*Note*: in contrast to the :cpp:func:`isinstance()` function above, builtin
types, type wrappers, and types handled using type casters, are *not*
supported.
Wrapper classes
---------------
.. cpp:class:: tuple: public object
Wrapper class representing Python ``tuple`` instances.
Use the standard ``operator[]`` C++ operator with an integer argument to
read tuple elements.
Once created, the tuple is immutable and its elements cannot be replaced.
Use the :py:func:`make_tuple` function to create new tuples.
.. cpp:function:: tuple()
Create an empty tuple
.. cpp:function:: tuple(handle h)
Attempt to convert a given Python object into a tuple. Analogous to the
expression ``tuple(h)`` in Python.
.. cpp:function:: size_t size() const
Return the number of tuple elements.
.. cpp:function:: bool empty() const
Check whether the tuple is empty.
.. cpp:function:: detail::fast_iterator begin() const
Return a forward iterator analogous to ``iter()`` in Python. The function
overrides a generic version in :cpp:class:`detail::api` and is more
efficient for tuples.
.. cpp:function:: detail::fast_iterator end() const
Return a sentinel that ends the iteration.
.. cpp:function:: template <typename T, enable_if_t<std::is_arithmetic_v<T>> = 1> detail::accessor<num_item_tuple> operator[](T key) const
Analogous to ``self[key]`` in Python, where ``key`` is an arithmetic
type (e.g., an integer). The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so
that it can be read and converted. Write access is not possible.
The function overrides the generic version in :cpp:class:`detail::api`
and is more efficient for tuples.
.. cpp:class:: list : public object
Wrapper class representing Python ``list`` instances.
Use the standard ``operator[]`` C++ operator with an integer argument to
read and write list elements.
Use the :cpp:func:`nb::del <del>` function to remove elements.
.. cpp:function:: list()
Create an empty list
.. cpp:function:: list(handle h)
Attempt to convert a given Python object into a list. Analogous to the
expression ``list(h)`` in Python.
.. cpp:function:: size_t size() const
Return the number of list elements.
.. cpp:function:: bool empty() const
Check whether the list is empty.
.. cpp:function:: template <typename T> void append(T&& value)
Append an element to the list. When `T` does not already represent a
wrapped Python object, the function performs a cast.
.. cpp:function:: template <typename T> void insert(Py_ssize_t index, T&& value)
Insert an element to the list (at index ``index``, which may also be
negative). When `T` does not already represent a wrapped Python object,
the function performs a cast.
.. cpp:function:: void clear()
Clear the list entries.
.. cpp:function:: void extend(handle h)
Analogous to the ``.extend(h)`` method of ``list`` in Python.
.. cpp:function:: void sort()
Analogous to the ``.sort()`` method of ``list`` in Python.
.. cpp:function:: void reverse()
Analogous to the ``.reverse()`` method of ``list`` in Python.
.. cpp:function:: template <typename T, enable_if_t<std::is_arithmetic_v<T>> = 1> detail::accessor<num_item_list> operator[](T key) const
Analogous to ``self[key]`` in Python, where ``key`` is an arithmetic
type (e.g., an integer). The result is wrapped in an :cpp:class:`accessor <detail::accessor>` so
that it can be read and written.
The function overrides the generic version in :cpp:class:`detail::api`
and is more efficient for lists.
.. cpp:function:: detail::fast_iterator begin() const
Return a forward iterator analogous to ``iter()`` in Python. The operator
provided here overrides the generic version in :cpp:class:`detail::api`
and is more efficient for lists.
.. cpp:function:: detail::fast_iterator end() const
Return a sentinel that ends the iteration.
.. cpp:class:: dict: public object
Wrapper class representing Python ``dict`` instances.
Use the standard ``operator[]`` C++ operator to read and write dictionary
elements (the bindings for this operator are provided by the parent class
and not listed here).
Use the :cpp:func:`nb::del <del>` function to remove elements.
.. cpp:function:: dict()
Create an empty dictionary
.. cpp:function:: size_t size() const
Return the number of dictionary elements.
.. cpp:function:: bool empty() const
Check whether the dictionary is empty.
.. cpp:function:: template <typename T> bool contains(T&& key) const
Check whether the dictionary contains a particular key. When `T` does not
already represent a wrapped Python object, the function performs a cast.
.. cpp:function:: detail::dict_iterator begin() const
Return an item iterator that returns ``std::pair<handle, handle>``
key-value pairs analogous to ``iter(dict.items())`` in Python.
In free-threaded Python, the :cpp:class:``detail::dict_iterator`` class
acquires a lock to the underlying dictionary to enable the use of the
efficient but thread-unsafe ``PyDict_Next()`` Python C traversal routine.
.. cpp:function:: detail::dict_iterator end() const
Return a sentinel that ends the iteration.
.. cpp:function:: list keys() const
Return a list containing all dictionary keys.
.. cpp:function:: list values() const
Return a list containing all dictionary values.
.. cpp:function:: list items() const
Return a list containing all dictionary items as ``(key, value)`` pairs.
.. cpp:function:: void clear()
Clear the contents of the dictionary.
.. cpp:function:: void update(handle h)
Analogous to the ``.update(h)`` method of ``dict`` in Python.
.. cpp:function:: object get(handle key, handle def)
Analogous to ``.get(key, def)`` method of ``dict`` in Python with a
fallback value ``def``. This is more efficient than checking the presence
of ``.contains(key)`` first, or using ``operator[]`` and catching a
potential exceptions.
.. cpp:function:: object get(const char * key, handle def)
Overload of the above method that takes a C-string as key.
.. cpp:class:: set: public object
Wrapper class representing Python ``set`` instances.
.. cpp:function:: set()
Create an empty set
.. cpp:function:: set(handle h)
Attempt to convert a given Python object into a set. Analogous to the
expression ``set(h)`` in Python.
.. cpp:function:: size_t size() const
Return the number of set elements.
.. cpp:function:: bool empty() const
Check whether the set is empty.
.. cpp:function:: template <typename T> void add(T&& key)
Add a key to the set. When `T` does not already represent a wrapped
Python object, the function performs a cast.
.. cpp:function:: template <typename T> bool contains(T&& key) const
Check whether the set contains a particular key. When `T` does not
already represent a wrapped Python object, the function performs a cast.
.. cpp:function:: void clear()
Clear the contents of the set.
.. cpp:function:: template <typename T> bool discard(T&& key)
Analogous to the ``.discard(h)`` method of the ``set`` type in Python.
Returns ``true`` if the item was deleted successfully, and ``false`` if
the value was not present. When `T` does not already represent a wrapped
Python object, the function performs a cast.
.. cpp:class:: frozenset: public object
Wrapper class representing Python ``frozenset`` instances.
.. cpp:function:: frozenset()
Create an empty frozenset.
.. cpp:function:: frozenset(handle h)
Attempt to convert a given Python object into a ``frozenset``. Analogous
to the expression ``frozenset(h)`` in Python.
.. cpp:function:: size_t size() const
Return the number of set elements.
.. cpp:function:: bool empty() const
Check whether the set is empty.
.. cpp:function:: template <typename T> bool contains(T&& key) const
Check whether the set contains a particular key. When `T` does not
already represent a wrapped Python object, the function performs a cast.
.. cpp:class:: module_: public object
Wrapper class representing Python ``module`` instances. The underscore at
the end disambiguates the class name from the C++20 ``module`` declaration.
.. cpp:function:: template <typename Func, typename... Extra> module_ &def(const char * name, Func &&f, const Extra &...extra)
Bind the function `f` to the identifier `name` within the module. Returns
a reference to ``*this`` so that longer sequences of binding declarations
can be chained, as in ``m.def(...).def(...);``. The variable length
`extra` parameter can be used to pass docstrings and other :ref:`function
binding annotations <function_binding_annotations>`.
Example syntax:
.. code-block:: cpp
void test() { printf("Hello world!"); }
NB_MODULE(example, m) {
// here, "m" is variable of type 'module_'.
m.def("test", &test, "A test function")
.def(...); // more binding declarations
}
.. cpp:function:: module_ import_(const char * name)
Import the Python module with the specified name and return a reference
to it. The underscore at the end disambiguates the function name from the
C++20 ``import`` statement.
Example usage:
.. code-block:: cpp
nb::module_ np = nb::module_::import_("numpy");
nb::object np_array = np.attr("array");
.. cpp:function:: module_ import_(handle name)
Import the Python module with the specified name and return a reference
to it. In contrast to the version above, this function expects a Python
object as key.
.. cpp:function:: module_ def_submodule(const char * name, const char * doc = nullptr)
Create a Python submodule within an existing module and return a
reference to it. Can be chained recursively.
Example usage:
.. code-block:: cpp
NB_MODULE(example, m) {
nb::module_ m2 = m.def_submodule("sub", "A submodule of 'example'");
nb::module_ m3 = m2.def_submodule("subsub", "A submodule of 'example.sub'");
}
.. cpp:class:: capsule: public object
Capsules are small opaque Python objects that wrap a C or C++ pointer and a cleanup routine.
.. cpp:function:: capsule(const void * ptr, void (* cleanup)(void*) noexcept = nullptr)
Construct an *unnamed* capsule wrapping the pointer `p`. When the
capsule is garbage collected, Python will call the destructor `cleanup`
(if provided) with the value of `p`.
.. cpp:function:: capsule(const void * ptr, const char * name, void (* cleanup)(void*) noexcept = nullptr)
Construct a *named* capsule with name `name` wrapping the pointer `p`.
When the capsule is garbage collected, Python will call the destructor
`cleanup` (if provided) with the value of `p`.
.. cpp:function:: const char * name() const
Return the capsule name (or ``nullptr`` when the capsule is unnamed)
.. cpp:function:: void * data() const
Return the pointer wrapped by the capsule.
.. cpp:function:: void * data(const char *name) const
Return the pointer wrapped by the capsule. Check that the
capsule name matches the specified value, or raise an exception.
.. cpp:class:: bool_: public object
This wrapper class represents Python ``bool`` instances.
.. cpp:function:: bool_(handle h)
Performs a boolean cast within Python. This is equivalent to the Python
expression ``bool(h)``.
.. cpp:function:: explicit bool_(bool value)
Convert an C++ boolean instance into a Python ``bool``.
.. cpp:function:: explicit operator bool() const
Extract the boolean value underlying this object.
.. cpp:class:: int_: public object
This wrapper class represents Python ``int`` instances. It can handle large
numbers requiring more than 64 bits of storage.
.. cpp:function:: int_(handle h)
Performs an integer cast within Python. This is equivalent to the Python
expression ``int(h)``.
.. cpp:function:: template <typename T, detail::enable_if_t<std::is_arithmetic_v<T>> = 0> explicit int_(T value)
Convert an C++ arithmetic type into a Python integer.
.. cpp:function:: template <typename T, detail::enable_if_t<std::is_arithmetic_v<T>> = 0> explicit operator T() const
Convert a Python integer into a C++ arithmetic type.
.. cpp:class:: float_: public object
This wrapper class represents Python ``float`` instances.
.. cpp:function:: float_(handle h)
Performs an floating point cast within Python. This is equivalent to the
Python expression ``float(h)``.
.. cpp:function:: explicit float_(double value)
Convert an C++ double value into a Python float objecct
.. cpp:function:: explicit operator double() const
Convert a Python float object into a C++ double value
.. cpp:class:: str: public object
This wrapper class represents Python unicode ``str`` instances.
.. cpp:function:: str(handle h)
Performs a string cast within Python. This is equivalent equivalent to
the Python expression ``str(h)``.
.. cpp:function:: str(const char * s)
Convert a null-terminated C-style string in UTF-8 encoding into a Python string.
.. cpp:function:: str(const char * s, size_t n)
Convert a C-style string in UTF-8 encoding of length ``n`` bytes into a Python string.
There is a user-defined string literal ``_s`` accessible in the
``nanobind::literals`` namespace::
using namespace nanobind::literals;
auto s = "Hello world!"_s; // equivalent to str("Hello world!")
.. cpp:function:: const char * c_str() const
Convert a Python string into a null-terminated C-style string with UTF-8
encoding.
*Note*: The C string will be deleted when the `str` instance is garbage
collected.
.. cpp:function:: template <typename... Args> str format(Args&&... args) const
C++ analog of the Python routine ``str.format``. Can be called with
positional and keyword arguments.
.. cpp:class:: bytes: public object
This wrapper class represents Python unicode ``bytes`` instances.
.. cpp:function:: bytes(handle h)
Performs a cast within Python. This is equivalent to
the Python expression ``bytes(h)``.
.. cpp:function:: bytes(const char * s)
Convert a null-terminated C-style string encoding into a Python ``bytes`` object.
.. cpp:function:: bytes(const void * buf, size_t n)
Convert a byte buffer ``buf`` of length ``n`` bytes into a Python ``bytes`` object. The buffer can contain embedded null bytes.
.. cpp:function:: const char * c_str() const
Convert a Python bytes object into a null-terminated C-style string.
.. cpp:function:: size_t size() const
Return the size in bytes.
.. cpp:function:: const void * data() const
Convert a Python ``bytes`` object into a byte buffer of length :cpp:func:`bytes::size()` bytes.
.. cpp:class:: bytearray: public object
This wrapper class represents Python ``bytearray`` instances.
.. cpp:function:: bytearray()
Create an empty ``bytearray``.
.. cpp:function:: bytearray(handle h)
Performs a cast within Python. This is equivalent to
the Python expression ``bytearray(h)``.
.. cpp:function:: bytearray(const void * buf, size_t n)
Convert a byte buffer ``buf`` of length ``n`` bytes into a Python ``bytearray`` object. The buffer can contain embedded null bytes.
.. cpp:function:: const char * c_str() const
Convert a Python ``bytearray`` object into a null-terminated C-style string.
.. cpp:function:: size_t size() const
Return the size in bytes.
.. cpp:function:: void * data()
Convert a Python ``bytearray`` object into a byte buffer of length :cpp:func:`bytearray::size()` bytes.
.. cpp:function:: const void * data() const
Convert a Python ``bytearray`` object into a byte buffer of length :cpp:func:`bytearray::size()` bytes.
.. cpp:function:: void resize(size_t n)
Resize the internal buffer of a Python ``bytearray`` object to ``n``. Any
space added by this method, which calls `PyByteArray_Resize`, will not be
initialized and may contain random data.
.. cpp:class:: type_object: public object
Wrapper class representing Python ``type`` instances.
.. cpp:class:: sequence: public object
Wrapper class representing arbitrary Python sequence types.
.. cpp:class:: mapping : public object
Wrapper class representing arbitrary Python mapping types.
.. cpp:function:: template <typename T> bool contains(T&& key) const
Check whether the map contains a particular key. When `T` does not
already represent a wrapped Python object, the function performs a cast.
.. cpp:function:: list keys() const
Return a list containing all of the map's keys.
.. cpp:function:: list values() const
Return a list containing all of the map's values.
.. cpp:function:: list items() const
Return a list containing all of the map's items as ``(key, value)`` pairs.
.. cpp:class:: iterator : public object
Wrapper class representing a Python iterator.
.. cpp:function:: iterator& operator++()
Advance to the next element (pre-increment form).
.. cpp:function:: iterator& operator++(int)
Advance to the next element (post-increment form).
.. cpp:function:: handle operator*() const
Return the item at the current position.
.. cpp:function:: handle operator->() const
Convenience routine for pointer-style access.
.. static iterator sentinel();
Return a sentinel that ends the iteration.
.. cpp:function:: friend bool operator==(const iterator &a, const iterator &b);
Iterator equality comparison operator.
.. cpp:function:: friend bool operator!=(const iterator &a, const iterator &b);
Iterator inequality comparison operator.
.. cpp:class:: iterable : public object
Wrapper class representing an object that can be iterated upon (in the sense
that calling :cpp:func:`iter()` is valid).
.. cpp:class:: slice : public object
Wrapper class representing a Python slice object.
.. cpp:function:: slice(handle start, handle stop, handle step)
Create the slice object given by ``slice(start, stop, step)`` in Python.
.. cpp:function:: template <typename T, detail::enable_if_t<std::is_arithmetic_v<T>> = 0> slice(T stop)
Create the slice object ``slice(stop)``, where `stop` is represented by a
C++ integer type.
.. cpp:function:: template <typename T, detail::enable_if_t<std::is_arithmetic_v<T>> = 0> slice(T start, T stop)
Create the slice object ``slice(start, stop)``, where `start` and `stop`
are represented by a C++ integer type.
.. cpp:function:: template <typename T, detail::enable_if_t<std::is_arithmetic_v<T>> = 0> slice(T start, T stop, T step)
Create the slice object ``slice(start, stop, step)``, where `start`,
`stop`, and `step` are represented by a C++ integer type.
.. cpp:function:: detail::tuple<Py_ssize_t, Py_ssize_t, Py_ssize_t, size_t> compute(size_t size) const
Compute a slice adjusted to the `size` value of a given container.
Returns a tuple containing ``(start, stop, step, slice_length)``.
The elements of the tuple can be obtained using a structured binding or
by using the templated ``get`` member function of ``nb::detail::tuple``.
For example:
.. code-block:: cpp
m.def("func", [](nb::slice slc) {
auto [start, stop, step, slice_length] = slc.compute(17);
// Or, if only the computed slice_length is needed:
auto tpl = slc.compute(42);
std::size_t adjusted_slice_length = tpl.get<3>();
// Now do something ...
});
.. cpp:class:: ellipsis: public object
Wrapper class representing a Python ellipsis (``...``) object.
.. cpp:function:: ellipsis()
Create a wrapper referencing the unique Python ``Ellipsis`` object.
.. cpp:class:: not_implemented: public object
Wrapper class representing a Python ``NotImplemented`` object.
.. cpp:function:: not_implemented()
Create a wrapper referencing the unique Python ``NotImplemented`` object.
.. cpp:class:: callable: public object
Wrapper class representing a callable Python object.
.. cpp:class:: weakref: public object
Wrapper class representing a Python weak reference object.
.. cpp:function:: explicit weakref(handle obj, handle callback = { })
Construct a new weak reference that points to `obj`. If provided,
Python will invoke the callable `callback` when `obj` expires.
.. cpp:class:: args : public tuple
Variable argument keyword list for use in function argument declarations.
.. cpp:class:: kwargs : public dict
Variable keyword argument keyword list for use in function argument declarations.
.. cpp:class:: any : public object
This wrapper class represents Python ``typing.Any``-typed values. On the C++
end, this type is interchangeable with :py:class:`object`. The only
difference is the type signature when used in function arguments and return
values.
.. cpp:class:: fallback : public object
Instances of this wrapper class behave just like :cpp:class:`handle`. When
used to pass arguments in function bindings, the associated arguments
*require* implicit conversion (which, however, adds no runtime cost).
The type is convenient in overload chains where a generic fallback should
accept any Python object, e.g.,
.. code-block:: cpp
m.def("func", [](MyClass &arg) { ... });
m.def("func", [](nb::fallback arg) { ... });
If :cpp:class:`handle` or :cpp:class:`object` were used instead on the
second line, they would always match and prevent potential implicit
conversion of arguments to `MyClass`.
Parameterized wrapper classes
-----------------------------
.. cpp:class:: template <typename T> handle_t : public handle
Wrapper class representing a handle to a subclass of the C++ type `T`. It
can be used to bind functions that take the associated Python object in its
wrapped form, while rejecting objects with a different type (i.e., it is
more discerning than :cpp:class:`handle`, which accepts *any* Python object).
.. code-block:: cpp
// Bind the class A
class A { int value; };
nb::class_<A>(m, "A");
// Bind a function that takes a Python object representing a 'A' instance
m.def("process_a", [](nb::handle_t<A> h) {
PyObject * a_py = h.ptr(); // PyObject* pointer to wrapper
A &a_cpp = nb::cast<A &>(h); // Reference to C++ instance
});
.. cpp:class:: template <typename T> type_object_t : public type_object
Wrapper class representing a Python type object that is a subtype of the C++
type `T`. It can be used to bind functions that only accept type objects
satisfying this criterion (i.e., it is more discerning than
:cpp:class:`type_object`, which accepts *any* Python type object).
Error management
----------------
nanobind provides a range of functionality to convert C++ exceptions into
equivalent Python exceptions and raise captured Python error state in C++. The
:cpp:class:`exception` class is also relevant in this context, but is listed in
the reference section on :ref:`class binding <class_binding>`.
.. cpp:struct:: error_scope
RAII helper class that temporarily stashes any existing Python error status.
This is important when running Python code in the context of an existing
failure that must be processed (e.g., to generate an error message).
.. cpp:function:: error_scope()
Stash the current error status (if any)
.. cpp:function:: ~error_scope()
Restore the stashed error status (if any)
.. cpp:struct:: python_error : public std::exception
Exception that represents a detected Python error status.
.. cpp:function:: python_error()
This constructor may only be called when a Python error has occurred
(``PyErr_Occurred()`` must be ``true``). It creates a C++ exception
object that represents this error and clears the Python error status.
.. cpp:function:: python_error(const python_error &)
Copy constructor
.. cpp:function:: python_error(python_error &&) noexcept
Move constructor
.. cpp:function:: const char * what() noexcept
Return a stringified version of the exception. nanobind internally
normalizes the exception and generates a traceback that is included
as part of this string. This can be a relatively costly operation
and should only be used if all of this detail is actually needed.
.. cpp:function:: bool matches(handle exc) noexcept
Checks whether the exception has the same type as `exc`.
The argument to this function is usually one of the `Standard Exceptions
<https://docs.python.org/3/c-api/exceptions.html#standard-exceptions>`_.
.. cpp:function:: void restore() noexcept
Restore the error status in Python and clear the `python_error`
contents. This may only be called once, and you should not
reraise the `python_error` in C++ afterward.
.. cpp:function:: void discard_as_unraisable(handle context) noexcept
Pass the error to Python's :py:func:`sys.unraisablehook`, which
prints a traceback to :py:data:`sys.stderr` by default but may
be overridden. Like :cpp:func:`restore`, this consumes the
error and you should not reraise the exception in C++ afterward.
The *context* argument should be some object whose ``repr()``
helps identify the location of the error. The default
:py:func:`sys.unraisablehook` prints a traceback that begins
with the text ``Exception ignored in:`` followed by
the result of ``repr(context)``.
Example use case: handling a Python error that occurs in a C++
destructor where you cannot raise a C++ exception.
.. cpp:function:: void discard_as_unraisable(const char * context) noexcept
Convenience wrapper around the above function, which takes a C-style
string for the ``context`` argument.
.. cpp:function:: handle type() const
Returns a handle to the exception type
.. cpp:function:: handle value() const
Returns a handle to the exception value
.. cpp:function:: object traceback() const
Returns a handle to the exception's traceback object
.. cpp:class:: cast_error
The function :cpp:func:`cast` raises this exception to indicate that a cast
was unsuccessful.
.. cpp:function:: cast_error()
Constructor
.. cpp:class:: next_overload
Raising this special exception from a bound function informs nanobind that
the function overload detected incompatible inputs. nanobind will then try
other overloads before reporting a ``TypeError``.
This feature is useful when a multiple overloads of a function accept
overlapping or identical input types (e.g. :cpp:class:`object`) and must run
code at runtime to select the right overload.
You should probably write a thorough docstring that explicitly mentions the
expected inputs in this case, since the behavior won't be obvious from the
auto-generated function signature. It can be frustrating when a function
call fails with an error message stating that the provided arguments aren't
compatible with any overload, when the associated error message suggests
otherwise.
.. cpp:function:: next_overload()
Constructor
.. cpp:class:: builtin_exception : public std::runtime_error
General-purpose class to propagate builtin Python exceptions from C++. A
number of convenience functions (see below) instantiate it.
.. cpp:function:: builtin_exception stop_iteration(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``StopIteration`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception index_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``IndexError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception key_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``KeyError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception value_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``ValueError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception type_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``TypeError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception buffer_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``BufferError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception import_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``ImportError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: builtin_exception attribute_error(const char * what = nullptr)
Convenience wrapper to create a :cpp:class:`builtin_exception` C++ exception
instance that nanobind will re-raise as a Python ``AttributeError`` exception
when it crosses the C++ ↔ Python interface.
.. cpp:function:: void register_exception_translator(void (* exception_translator)(const std::exception_ptr &, void*), void * payload = nullptr)
Install an exception translator callback that will be invoked whenever
nanobind's function call dispatcher catches a previously unknown C++
exception. This exception translator should follow a standard structure of
re-throwing an exception, catching a specific type, and converting this into
a Python error status upon "success".
Here is an example for a hypothetical ``ZeroDivisionException``.
.. code-block:: cpp
register_exception_translator(
[](const std::exception_ptr &p, void * /*payload*/) {
try {
std::rethrow_exception(p);
} catch (const ZeroDivisionException &e) {
PyErr_SetString(PyExc_ZeroDivisionError, e.what());
}
}, nullptr /*payload*/);
Generally, you will want to use the more convenient exception binding
interface provided by :cpp:class:`exception` class. This function provides
an escape hatch for more specialized use cases.
.. cpp:function:: void chain_error(handle type, const char * fmt, ...) noexcept
Raise a Python error of type ``type`` using the format string ``fmt``
interpreted by ``PyErr_FormatV``.
If a Python error state was already set prior to calling this method, then
the new error is *chained* on top of the existing one. Otherwise, the
function creates a new error without initializing its ``__cause__`` field.
.. cpp:function:: void raise_from(python_error &e, handle type, const char * fmt, ...)
Convenience wrapper around :cpp:func:`chain_error <chain_error>`. It takes
an existing Python error (e.g. caught in a ``catch`` block) and creates an
additional Python exception with the current error as cause. It then
re-raises :cpp:class:`python_error`. The argument ``fmt`` is a
``printf``-style format string interpreted by ``PyErr_FormatV``.
Usage of this function is explained in the documentation section on
:ref:`exception chaining <exception_chaining>`.
.. cpp:function:: void raise(const char * fmt, ...)
This function takes a ``printf``-style format string with arguments and then
raises a ``std::runtime_error`` with the formatted string. The function has
no dependence on Python, and nanobind merely includes it for convenience.
.. cpp:function:: void raise_type_error(const char * fmt, ...)
This function is analogous to :cpp:func:`raise`, except that it raises a
:cpp:class:`builtin_exception` that will convert into a Python ``TypeError``
when crossing the language interface.
.. cpp:function:: void raise_python_error()
This function should only be called if a Python error status was set by a
prior operation, which should now be raised as a C++ exception. The function
is analogous to the statement ``throw python_error();`` but compiles into
more compact code.
Casting
-------
.. cpp:function:: template <typename T, typename Derived> T cast(const detail::api<Derived> &value, bool convert = true)
Convert the Python object `value` (typically a :cpp:class:`handle` or a
:cpp:class:`object` subclass) into a C++ object of type `T`.
When the `convert` argument is set to ``true`` (the default), the
implementation may also attempt *implicit conversions* to perform the cast.
The function raises an exception when the conversion fails.
If the type caster uses the CPython error API (e.g., ``PyErr_SetString()``
or ``PyErr_Format()``) to report a failure, then :cpp:class:`python_error`
is raised. Otherwise, :cpp:type:`cast_error` is raised.
See :cpp:func:`try_cast()` for an alternative that never raises.
.. cpp:function:: template <typename T, typename Derived> bool try_cast(const detail::api<Derived> &value, T &out, bool convert = true) noexcept
Convert the Python object `value` (typically a :cpp:class:`handle` or a
:cpp:class:`object` subclass) into a C++ object of type `T`, and store it
in the output parameter `out`.
When the `convert` argument is set to ``true`` (the default), the
implementation may also attempt *implicit conversions* to perform the cast.
The function returns ``false`` when the conversion fails. In this case, the
`out` parameter is left untouched. See :cpp:func:`cast()` for an alternative
that instead raises an exception in this case.
.. cpp:function:: template <typename T> object cast(T &&value, rv_policy policy = rv_policy::automatic_reference)
Convert the C++ object ``value`` into a Python object. The return value
policy `policy` is used to handle ownership-related questions when a new
Python object must be created.
The function raises an exception when the conversion fails.
If the type caster uses the CPython error API (e.g., ``PyErr_SetString()``
or ``PyErr_Format()``) to report a failure, then :cpp:class:`python_error`
is raised. Otherwise, :cpp:type:`cast_error` is raised.
.. cpp:function:: template <typename T> object cast(T &&value, rv_policy policy, handle parent)
Convert the C++ object ``value`` into a Python object. The return value
policy `policy` is used to handle ownership-related questions when a new
Python object must be created. A valid `parent` object is required when
specifying a `reference_internal` return value policy.
The function raises an exception when the conversion fails.
If the type caster uses the CPython error API (e.g., ``PyErr_SetString()``
or ``PyErr_Format()``) to report a failure, then :cpp:class:`python_error`
is raised. Otherwise, :cpp:type:`cast_error` is raised.
.. cpp:function:: template <typename T> object find(const T &value) noexcept
Return the Python object associated with the C++ instance `value`. When no
such object can be found, the function it returns an invalid object
(:cpp:func:`detail::api::is_valid()` is ``false``).
.. cpp:function:: template <rv_policy policy = rv_policy::automatic, typename... Args> tuple make_tuple(Args&&... args)
Create a Python tuple from a sequence of C++ objects ``args...``. The return
value policy `policy` is used to handle ownership-related questions when a
new Python objects must be created.
The function raises an exception when the conversion fails.
If the type caster uses the CPython error API (e.g., ``PyErr_SetString()``
or ``PyErr_Format()``) to report a failure, then :cpp:class:`python_error`
is raised. Otherwise, :cpp:type:`cast_error` is raised.
Common binding annotations
--------------------------
The following annotations can be specified in both function and class bindings.
.. cpp:struct:: scope
.. cpp:function:: scope(handle value)
Captures the Python scope (e.g., a :cpp:class:`module_` or
:cpp:class:`type_object`) in which the function or class should be
registered.
.. _function_binding_annotations:
Function binding annotations
----------------------------
The following annotations can be specified using the variable-length ``Extra``
parameter of :cpp:func:`module_::def`, :cpp:func:`class_::def`,
:cpp:func:`cpp_function`, etc.
.. cpp:struct:: name
.. cpp:function:: name(const char * value)
Specify this annotation to override the name of the function.
nanobind will internally copy the string when creating a function
binding, hence dynamically generated arguments with a limited lifetime
are legal.
.. cpp:struct:: arg
Function argument annotation to enable keyword-based calling, default
arguments, passing ``None``, and implicit conversion hints. Note that when a
function argument should be annotated, you *must* specify annotations for all
arguments of that function.
Example use:
.. code-block:: cpp
m.def("add", [](int a, int b) { return a + b; }, nb::arg("a"), nb::arg("b"));
It is usually convenient to add the following ``using`` declaration to your binding code.
.. code-block:: cpp
using namespace nb::literals;
In this case, the argument annotations can be shortened:
.. code-block:: cpp
m.def("add", [](int a, int b) { return a + b; }, "a"_a, "b"_a);
.. cpp:function:: explicit arg(const char * name = nullptr)
Create a function argument annotation. The name is optional.
.. cpp:function:: template <typename T> arg_v operator=(T &&value) const
Return an argument annotation that is like this one but also assigns a
default value to the argument. The default will be converted into a Python
object immediately, so its bindings must have already been defined.
.. cpp:function:: arg &none(bool value = true)
Set a flag noting that the function argument accepts ``None``. Can only
be used for python wrapper types (e.g. :cpp:class:`handle`,
:cpp:class:`int_`) and types that have been bound using
:cpp:class:`class_`. You cannot use this to implement functions that
accept null pointers to builtin C++ types like ``int *i = nullptr``.
.. cpp:function:: arg &noconvert(bool value = true)
Set a flag noting that implicit conversion should never be performed for
this function argument.
.. cpp:function:: arg &sig(const char * sig)
Override the signature of the default argument value. This is useful when
the argument value is unusually complex so that the default method to
explain it in docstrings and stubs (``str(value)``) does not produce
acceptable output.
.. cpp:function:: arg_locked lock()
Return an argument annotation that is like this one but also requests that
this argument be locked when dispatching a function call in free-threaded
Python extensions. It does nothing in regular GIL-protected extensions.
.. cpp:struct:: is_method
Indicate that the bound function is a method.
.. cpp:struct:: is_operator
Indicate that the bound operator represents a special double underscore
method (``__add__``, ``__radd__``, etc.) that implements an arithmetic
operation.
When a bound functions with this annotation is called with incompatible
arguments, it will return ``NotImplemented`` rather than raising a
``TypeError``.
.. cpp:struct:: is_implicit
Indicate that the bound constructor can be used to perform implicit conversions.
.. cpp:struct:: lock_self
Indicate that the implicit ``self`` argument of a method should be locked
when dispatching a call in a free-threaded extension. This annotation does
nothing in regular GIL-protected extensions.
.. cpp:struct:: template <typename... Ts> call_guard
Invoke the call guard(s) `Ts` when the bound function executes. The RAII
helper :cpp:struct:`gil_scoped_release` is often combined with this feature.
.. cpp:struct:: template <size_t Nurse, size_t Patient> keep_alive
Following evaluation of the bound function, keep the object referenced by
index ``Patient`` alive *as long as* the object with index ``Nurse`` exists.
This uses the following indexing convention:
- Index ``0`` refers to the return value of methods. It should not be used
in constructors or functions that do not return a result.
- Index ``1`` refers to the first argument. In methods and constructors,
index ``1`` refers to the implicit ``this`` pointer, while regular
arguments begin at index ``2``.
The annotation has the following runtime characteristics:
- It does nothing when the nurse or patient object are ``None``.
- It raises an exception when the nurse object is neither
weak-referenceable nor an instance of a binding created via
:cpp:class:`nb::class_\<..\> <class_>`.
Two additional caveats regarding :cpp:class:`keep_alive <keep_alive>` are
noteworthy:
- It *usually* doesn't make sense to specify a ``Nurse`` or ``Patient`` for an
argument or return value handled by a :ref:`type caster <type_casters>`
(e.g., a STL vector handled via the include directive ``#include
<nanobind/stl/vector.h>``). That's because type casters copy-convert the
Python object into an equivalent C++ object, whose lifetime is decoupled
from the original Python object. However, the :cpp:class:`keep_alive
<keep_alive>` annotation *only* affects the lifetime of Python objects
*and not their C++ copy*.
- Dispatching a Python → C++ function call may require the :ref:`implicit
conversion <noconvert>` of function arguments. In this case, the objects
passed to the C++ function differ from the originally specified arguments.
The ``Nurse`` and ``Patient`` annotation always refer to the *final* object
following implicit conversion.
.. cpp:struct:: sig
.. cpp:function:: sig(const char * value)
This is *both* a class and a function binding annotation.
1. When used in functions bindings, it provides complete control over
the function's type signature by replacing the automatically generated
version with ``value``. You can use it to add or change arguments and
return values, tweak how default values are rendered, and add custom
decorators.
Here is an example:
.. code-block:: cpp
nb::def("function_name", &function_name,
nb::sig(
"@decorator(decorator_args..)\n
"def function_name(arg_1: type_1 = def_1, ...) -> ret"
));
2. When used in class bindings, the annotation enables complete control
over how the class is rendered by nanobind's ``stubgen`` program. You
can use it add decorators, specify ``typing.TypeVar``-parameterized
base classes, metaclasses, etc.
Here is an example:
.. code-block:: cpp
nb::class_<Class>(m, "Class",
nb::sig(
"@decorator(decorator_args..)\n"
"class Class(Base1[T], Base2, meta=Meta)"
));
Deviating significantly from the nanobind-generated signature likely
means that the class or function declaration is a *lie*, but such lies
can be useful to type-check complex binding projects.
Specifying decorators isn't required---the above are just examples to
show that this is possible.
nanobind will internally copy the signature during function/type
creation, hence dynamically generated strings with a limited lifetime are
legal.
The provided string should be valid Python signature, but *without* a
trailing colon (``":"``) or trailing newline. Furthermore, nanobind
analyzes the string and expects to find the name of the function or class
on the *last line* between the ``"def"`` / ``"class"`` prefix and the
opening parenthesis.
For function bindings, this name must match the specified function name
in ``.def("name", ..)``-style binding declarations, and for class
bindings, the specified name must match the ``name`` argument of
:cpp:class:`nb::class_ <class_>`.
.. cpp:enum-class:: rv_policy
A return value policy determines the question of *ownership* when a bound
function returns a previously unknown C++ instance that must now be
converted into a Python object.
Return value policies apply to functions that return values handled using
:ref:`class bindings <bindings>`, which means that their Python equivalent
was registered using :cpp:class:`class_\<...\> <class_>`. They are ignored
in most other cases. One exception are STL types handled using :ref:`type
casters <type_casters>` (e.g. ``std::vector<T>``), which contain a nested
type ``T`` handled using class bindings. In this case, the return value
policy also applies recursively.
A return value policy is unnecessary when the type itself clarifies
ownership (e.g., ``std::unique_ptr<T>``, ``std::shared_ptr<T>``, a type with
:ref:`intrusive reference counting <intrusive>`).
The following policies are available (where `automatic` is the default).
Please refer to the :ref:`return value policy section <rvp>` of the main
documentation, which clarifies the list below using concrete examples.
.. cpp:enumerator:: take_ownership
Create a Python object that wraps the existing C++ instance and takes
full ownership of it. No copies are made. Python will call the C++
destructor and ``delete`` operator when the Python wrapper is garbage
collected at some later point. The C++ side *must* relinquish ownership
and is not allowed to destruct the instance, or undefined behavior will
ensue.
.. cpp:enumerator:: copy
Copy-construct a new Python object from the C++ instance. The new copy
will be owned by Python, while C++ retains ownership of the original.
.. cpp:enumerator:: move
Move-construct a new Python object from the C++ instance. The new object
will be owned by Python, while C++ retains ownership of the original
(whose contents were likely invalidated by the move operation).
.. cpp:enumerator:: reference
Create a Python object that wraps the existing C++ instance *without
taking ownership* of it. No copies are made. Python will never call the
destructor or ``delete`` operator, even when the Python wrapper is
garbage collected.
.. cpp:enumerator:: reference_internal
A safe extension of the `reference` policy for methods that implement
some form of attribute access. It creates a Python object that wraps the
existing C++ instance *without taking ownership* of it. Additionally, it
adjusts reference counts to keeps the method's implicit ``self`` argument
alive until the newly created object has been garbage collected.
.. cpp:enumerator:: none
This is the most conservative policy: it simply refuses the cast unless
the C++ instance already has a corresponding Python object, in which case
the question of ownership becomes moot.
.. cpp:enumerator:: automatic
This is the default return value policy, which falls back to
`take_ownership` when the return value is a pointer, `move` when it is a
rvalue reference, and `copy` when it is a lvalue reference.
.. cpp:enumerator:: automatic_reference
This policy matches `automatic` but falls back to `reference` when the
return value is a pointer.
.. cpp:struct:: kw_only
Indicate that all following function parameters are keyword-only. This
may only be used if you supply an :cpp:struct:`arg` annotation for each
parameters, because keyword-only parameters are useless if they don't have
names. For example, if you write
.. code-block:: cpp
int some_func(int one, const char* two);
m.def("some_func", &some_func,
nb::arg("one"), nb::kw_only(), nb::arg("two"));
then in Python you can write ``some_func(42, two="hi")``, or
``some_func(one=42, two="hi")``, but not ``some_func(42, "hi")``.
Just like in Python, any parameters appearing after variadic
:cpp:class:`*args <args>` are implicitly keyword-only. You don't
need to include the :cpp:struct:`kw_only` annotation in this case,
but if you do include it, it must be in the correct position:
immediately after the :cpp:struct:`arg` annotation for the variadic
:cpp:class:`*args <args>` parameter.
.. cpp:struct:: template <typename T> for_getter
When defining a property with a getter and a setter, you can use this to
only pass a function binding attribute to the getter part. An example is
shown below.
.. code-block:: cpp
nb::class_<MyClass>(m, "MyClass")
.def_prop_rw("value", &MyClass::value,
nb::for_getter(nb::sig("def value(self, /) -> int")),
nb::for_setter(nb::sig("def value(self, value: int, /) -> None")),
nb::for_getter("docstring for getter"),
nb::for_setter("docstring for setter"));
.. cpp:struct:: template <typename T> for_setter
Analogous to :cpp:struct:`for_getter`, but for setters.
.. cpp:struct:: template <typename Policy> call_policy
Request that custom logic be inserted around each call to the
bound function, by calling ``Policy::precall(args, nargs, cleanup)`` before
Python-to-C++ argument conversion, and ``Policy::postcall(args, nargs, ret)``
after C++-to-Python return value conversion.
If multiple call policy annotations are provided for the same function, then
their precall and postcall hooks will both execute left-to-right according
to the order in which the annotations were specified when binding the
function.
The :cpp:struct:`nb::call_guard\<T\>() <call_guard>` annotation
should be preferred over ``call_policy`` unless the wrapper logic
depends on the function arguments or return value.
If both annotations are combined, then
:cpp:struct:`nb::call_guard\<T\>() <call_guard>` always executes on
the "inside" (closest to the bound function, after argument
conversions and before return value conversion) regardless of its
position in the function annotations list.
Your ``Policy`` class must define two static member functions:
.. cpp:function:: static void precall(PyObject **args, size_t nargs, detail::cleanup_list *cleanup);
A hook that will be invoked before calling the bound function. More
precisely, it is called after any :ref:`argument locks <argument-locks>`
have been obtained, but before the Python arguments are converted to C++
objects for the function call.
This hook may access or modify the function arguments using the
*args* array, which holds borrowed references in one-to-one
correspondence with the C++ arguments of the bound function. If
the bound function is a method, then ``args[0]`` is its *self*
argument. *nargs* is the number of function arguments. It is actually
passed as ``std::integral_constant<size_t, N>()``, so you can
match on that type if you want to do compile-time checks with it.
The *cleanup* list may be used as it is used in type casters,
to cause some Python object references to be released at some point
after the bound function completes. (If the bound function is part
of an overload set, the cleanup list isn't released until all overloads
have been tried.)
``precall()`` may choose to throw a C++ exception. If it does,
it will preempt execution of the bound function, and the
exception will be treated as if the bound function had thrown it.
.. cpp:function:: static void postcall(PyObject **args, size_t nargs, handle ret);
A hook that will be invoked after calling the bound function and
converting its return value to a Python object, but only if the
bound function returned normally.
*args* stores the Python object arguments, with the same semantics
as in ``precall()``, except that arguments that participated in
implicit conversions will have had their ``args[i]`` pointer updated
to reflect the new Python object that the implicit conversion produced.
*nargs* is the number of arguments, passed as a ``std::integral_constant``
in the same way as for ``precall()``.
*ret* is the bound function's return value. If the bound function returned
normally but its C++ return value could not be converted to a Python
object, then ``postcall()`` will execute with *ret* set to null,
and the Python error indicator might or might not be set to explain why.
If the bound function did not return normally -- either because its
Python object arguments couldn't be converted to the appropriate C++
types, or because the C++ function threw an exception -- then
``postcall()`` **will not execute**. If you need some cleanup logic to
run even in such cases, your ``precall()`` can add a capsule object to the
cleanup list; its destructor will run eventually, but with no promises
as to when. A :cpp:struct:`nb::call_guard <call_guard>` might be a
better choice.
``postcall()`` may choose to throw a C++ exception. If it does,
the result of the wrapped function will be destroyed,
and the exception will be raised in its place, as if the bound function
had thrown it just before returning.
Here is an example policy to demonstrate.
``nb::call_policy<returns_references_to<I>>()`` behaves like
:cpp:class:`nb::keep_alive\<0, I\>() <keep_alive>`, except that the
return value is a treated as a list of objects rather than a single one.
.. code-block:: cpp
template <size_t I>
struct returns_references_to {
static void precall(PyObject **, size_t, nb::detail::cleanup_list *) {}
template <size_t N>
static void postcall(PyObject **args,
std::integral_constant<size_t, N>,
nb::handle ret) {
static_assert(I > 0 && I <= N,
"I in returns_references_to<I> must be in the "
"range [1, number of C++ function arguments]");
if (!nb::isinstance<nb::sequence>(ret)) {
throw std::runtime_error("return value should be a sequence");
}
for (nb::handle nurse : ret) {
nb::detail::keep_alive(nurse.ptr(), args[I - 1]);
}
}
};
For a more complex example (binding an object that uses trivially-copyable
callbacks), see ``tests/test_callbacks.cpp`` in the nanobind source
distribution.
.. _class_binding_annotations:
Class binding annotations
-------------------------
The following annotations can be specified using the variable-length ``Extra``
parameter of the constructor :cpp:func:`class_::class_`.
Besides the below options, also refer to the :cpp:class:`sig` which is
usable in both function and class bindings. It can be used to override class
declarations in generated :ref:`stubs <stubs>`,
.. cpp:struct:: is_final
Indicate that a type cannot be subclassed.
.. cpp:struct:: dynamic_attr
Indicate that instances of a type require a Python dictionary to support the dynamic addition of attributes.
.. cpp:struct:: is_weak_referenceable
Indicate that instances of a type require a weak reference list so that they
can be referenced by the Python ``weakref.*`` types.
.. cpp:struct:: is_generic
If present, nanobind will add a ``__class_getitem__`` function to the newly
created type that permits constructing *parameterized* versions (e.g.,
``MyType[int]``). The implementation of this function is equivalent to
.. code-block:: python
def __class_getitem__(cls, value):
import types
return types.GenericAlias(cls, value)
See the section on :ref:`creating generic types <typing_generics_creating>`
for an example.
This feature is only supported on Python 3.9+. Nanobind will ignore
the attribute in Python 3.8 builds.
.. cpp:struct:: template <typename T> supplement
Indicate that ``sizeof(T)`` bytes of memory should be set aside to
store supplemental data in the type object. See :ref:`Supplemental
type data <supplement>` for more information.
.. cpp:struct:: type_slots
.. cpp:function:: type_slots(PyType_Slot * value)
nanobind uses the ``PyType_FromSpec`` Python C API interface to construct
types. In certain advanced use cases, it may be helpful to append additional
type slots during type construction. This class binding annotation can be
used to accomplish this. The provided list should be followed by a
zero-initialized ``PyType_Slot`` element. See :ref:`Customizing type creation
<typeslots>` for more information about this feature.
.. cpp:struct:: template <typename T> intrusive_ptr
nanobind provides a custom interface for intrusive reference-counted C++
types that nicely integrate with Python reference counting. See the
:ref:`separate section <intrusive>` on this topic. This annotation
marks a type as compatible with this interface.
.. cpp:function:: intrusive_ptr(void (* set_self_py)(T*, PyObject*) noexcept)
Declares a callback that will be invoked when a C++ instance is first
cast into a Python object.
.. _enum_binding_annotations:
Enum binding annotations
------------------------
The following annotations can be specified using the variable-length
``Extra`` parameter of the constructor :cpp:func:`enum_::enum_`.
.. cpp:struct:: is_arithmetic
Indicate that the enumeration supports arithmetic operations. This enables
both unary (``-``, ``~``, ``abs()``) and binary (``+``, ``-``, ``*``,
``//``, ``&``, ``|``, ``^``, ``<<``, ``>>``) operations with operands of
either enumeration or numeric types.
The result will be as if the operands were first converted to integers. (So
``Shape(2) + Shape(1) == 3`` and ``Shape(2) * 1.5 == 3.0``.) It is
unspecified whether operations on mixed enum types (such as ``Shape.Circle +
Color.Red``) are permissible.
Passing this annotation changes the Python enumeration parent class to
either :py:class:`enum.IntEnum` or :py:class:`enum.IntFlag`, depending on
whether or not the flag enumeration attribute is also specified (see
:cpp:class:`is_flag`).
.. cpp:struct:: is_flag
Indicate that the enumeration supports bit-wise operations. This enables the
operators (``|``, ``&``, ``^``, and ``~``) with two enumerators as operands.
The result has the same type as the operands, i.e., ``Shape(2) | Shape(1)``
will be equivalent to ``Shape(3)``.
Passing this annotation changes the Python enumeration parent class to
either :py:class:`enum.IntFlag` or :py:class:`enum.Flag`, depending on
whether or not the enumeration is also marked to support arithmetic
operations (see :cpp:class:`is_arithmetic`).
Function binding
----------------
.. cpp:function:: object cpp_function(Func &&f, const Extra&... extra)
Convert the function `f` into a Python callable. This function has
a few overloads (not shown here) to separately deal with function/method
pointers and lambda functions.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
.. _class_binding:
Class binding
-------------
.. cpp:class:: template <typename T, typename... Ts> class_ : public object
Binding helper class to expose a custom C++ type `T` (declared using either
the ``class`` or ``struct`` keyword) in Python.
The variable length parameter `Ts` is optional and can be used to specify
the base class of `T` and/or an alias needed to realize :ref:`trampoline
classes <trampolines>`.
When the type ``T`` was previously already registered (either within the
same extension or another extension), the ``class_<..>`` declaration is
redundant. nanobind will print a warning message in this case:
.. code-block:: text
RuntimeWarning: nanobind: type 'MyType' was already registered!
The ``class_<..>`` instance will subsequently wrap the original type object
instead of creating a new one.
.. cpp:function:: template <typename... Extra> class_(handle scope, const char * name, const Extra &... extra)
Bind the type `T` to the identifier `name` within the scope `scope`. The
variable length `extra` parameter can be used to pass a docstring and
other :ref:`class binding annotations <class_binding_annotations>`.
.. cpp:function:: template <typename Func, typename... Extra> class_ &def(const char * name, Func &&f, const Extra &... extra)
Bind the function `f` and assign it to the class member `name`.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
This function has two overloads (listed just below) to handle constructor
binding declarations.
**Example**:
.. code-block:: cpp
struct A {
void f() { /*...*/ }
};
nb::class_<A>(m, "A")
.def(nb::init<>()) // Bind the default constructor
.def("f", &A::f); // Bind the method A::f
.. cpp:function:: template <typename... Args, typename... Extra> class_ &def(init<Args...> arg, const Extra &... extra)
Bind a constructor. The variable length `extra` parameter can be used to
pass a docstring and other :ref:`function binding annotations
<function_binding_annotations>`.
.. cpp:function:: template <typename Arg, typename... Extra> class_ &def(init_implicit<Arg> arg, const Extra &... extra)
Bind a constructor that may be used for implicit type conversions. The
constructor must take a single argument of an unspecified type `Arg`.
When nanobind later tries to dispatch a function call requiring an
argument of type `T` while `Arg` was actually provided, it will run this
constructor to perform the necessary conversion.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
This constructor generates more compact code than a separate call to
:cpp:func:`implicitly_convertible`, but is otherwise equivalent.
.. cpp:function:: template <typename Func, typename... Extra> class_ &def(new_<Func> arg, const Extra &... extra)
Bind a C++ factory function as a Python object constructor (``__new__``).
This is an advanced feature; prefer :cpp:struct:`nb::init\<..\> <init>`
where possible. See the discussion of :ref:`customizing object creation
<custom_new>` for more details.
.. cpp:function:: template <typename Visitor, typename... Extra> class_ &def(def_visitor<Visitor> arg, const Extra &... extra)
Dispatch to custom user-provided binding logic implemented by the type
``Visitor``, passing it the binding annotations ``extra...``.
See the documentation of :cpp:struct:`nb::def_visitor\<..\> <def_visitor>`
for details.
.. cpp:function:: template <typename C, typename D, typename... Extra> class_ &def_rw(const char * name, D C::* p, const Extra &...extra)
Bind the field `p` and assign it to the class member `name`. nanobind
constructs a ``property`` object with *read-write* access (hence the
``rw`` suffix) to do so.
Every access from Python will read from or write to the C++ field while
performing a suitable conversion (using :ref:`type casters
<type_casters>`, :ref:`bindings <bindings>`, or :ref:`wrappers
<wrappers>`) as determined by its type.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`
that are forwarded to the anonymous functions used to construct the
property.
Use the :cpp:struct:`nb::for_getter <for_getter>` and
:cpp:struct:`nb::for_setter <for_setter>` to pass annotations
specifically to the setter or getter part.
**Example**:
.. code-block:: cpp
struct A { int value; };
nb::class_<A>(m, "A")
.def_rw("value", &A::value); // Enable mutable access to the field A::value
.. cpp:function:: template <typename C, typename D, typename... Extra> class_ &def_ro(const char * name, D C::* p, const Extra &...extra)
Bind the field `p` and assign it to the class member `name`. nanobind
constructs a ``property`` object with *read only* access (hence the
``ro`` suffix) to do so.
Every access from Python will read the C++ field while performing a
suitable conversion (using :ref:`type casters <type_casters>`,
:ref:`bindings <bindings>`, or :ref:`wrappers <wrappers>`) as determined
by its type.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`
that are forwarded to the anonymous functions used to construct the
property.
**Example**:
.. code-block:: cpp
struct A { int value; };
nb::class_<A>(m, "A")
.def_ro("value", &A::value); // Enable read-only access to the field A::value
.. cpp:function:: template <typename Getter, typename Setter, typename... Extra> class_ &def_prop_rw(const char * name, Getter &&getter, Setter &&setter, const Extra &...extra)
Construct a *mutable* (hence the ``rw`` suffix) Python ``property`` and
assign it to the class member `name`. Every read access will call the
function ``getter`` with the `T` instance, and every write access will
call the ``setter`` with the `T` instance and value to be assigned.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
Use the :cpp:struct:`nb::for_getter <for_getter>` and
:cpp:struct:`nb::for_setter <for_setter>` to pass annotations
specifically to the setter or getter part.
Note that this function implicitly assigns the
:cpp:enumerator:`rv_policy::reference_internal` return value policy to
`getter` (as opposed to the usual
:cpp:enumerator:`rv_policy::automatic`). Provide an explicit return value
policy as part of the `extra` argument to override this.
**Example**: the example below uses `def_prop_rw` to expose a C++
setter/getter pair as a more "Pythonic" property:
.. code-block:: cpp
class A {
public:
A(int value) : m_value(value) { }
void set_value(int value) { m_value = value; }
int value() const { return m_value; }
private:
int m_value;
};
nb::class_<A>(m, "A")
.def(nb::init<int>())
.def_prop_rw("value",
[](A &t) { return t.value() ; },
[](A &t, int value) { t.set_value(value); });
.. cpp:function:: template <typename Getter, typename... Extra> class_ &def_prop_ro(const char * name, Getter &&getter, const Extra &...extra)
Construct a *read-only* (hence the ``ro`` suffix) Python ``property`` and
assign it to the class member `name`. Every read access will call the
function ``getter`` with the `T` instance.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
Note that this function implicitly assigns the
:cpp:enumerator:`rv_policy::reference_internal` return value policy to
`getter` (as opposed to the usual
:cpp:enumerator:`rv_policy::automatic`). Provide an explicit return value
policy as part of the `extra` argument to override this.
**Example**: the example below uses `def_prop_ro` to expose a C++ getter
as a more "Pythonic" property:
.. code-block:: cpp
class A {
public:
A(int value) : m_value(value) { }
int value() const { return m_value; }
private:
int m_value;
};
nb::class_<A>(m, "A")
.def(nb::init<int>())
.def_prop_ro("value",
[](A &t) { return t.value() ; });
.. cpp:function:: template <typename Func, typename... Extra> class_ &def_static(const char * name, Func &&f, const Extra &... extra)
Bind the *static* function `f` and assign it to the class member `name`.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
**Example**:
.. code-block:: cpp
struct A {
static void f() { /*...*/ }
};
nb::class_<A>(m, "A")
.def_static("f", &A::f); // Bind the static method A::f
.. cpp:function:: template <typename D, typename... Extra> class_ &def_rw_static(const char * name, D* p, const Extra &...extra)
Bind the *static* field `p` and assign it to the class member `name`. nanobind
constructs a class ``property`` object with *read-write* access (hence the
``rw`` suffix) to do so.
Every access from Python will read from or write to the static C++ field
while performing a suitable conversion (using :ref:`type casters
<type_casters>`, :ref:`bindings <bindings>`, or :ref:`wrappers
<wrappers>`) as determined by its type.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`
that are forwarded to the anonymous functions used to construct the
property
Use the :cpp:struct:`nb::for_getter <for_getter>` and
:cpp:struct:`nb::for_setter <for_setter>` to pass annotations
specifically to the setter or getter part.
**Example**:
.. code-block:: cpp
struct A { inline static int value = 5; };
nb::class_<A>(m, "A")
// Enable mutable access to the static field A::value
.def_rw_static("value", &A::value);
.. cpp:function:: template <typename D, typename... Extra> class_ &def_ro_static(const char * name, D* p, const Extra &...extra)
Bind the *static* field `p` and assign it to the class member `name`.
nanobind constructs a class ``property`` object with *read-only* access
(hence the ``ro`` suffix) to do so.
Every access from Python will read the static C++ field while performing
a suitable conversion (using :ref:`type casters <type_casters>`,
:ref:`bindings <bindings>`, or :ref:`wrappers <wrappers>`) as determined
by its type.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`
that are forwarded to the anonymous functions used to construct the
property
**Example**:
.. code-block:: cpp
struct A { inline static int value = 5; };
nb::class_<A>(m, "A")
// Enable read-only access to the static field A::value
.def_ro_static("value", &A::value);
.. cpp:function:: template <typename Getter, typename Setter, typename... Extra> class_ &def_prop_rw_static(const char * name, Getter &&getter, Setter &&setter, const Extra &...extra)
Construct a *mutable* (hence the ``rw`` suffix) Python ``property`` and
assign it to the class member `name`. Every read access will call the
function ``getter`` with `T`'s Python type object, and every write access will
call the ``setter`` with `T`'s Python type object and value to be assigned.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
Use the :cpp:struct:`nb::for_getter <for_getter>` and
:cpp:struct:`nb::for_setter <for_setter>` to pass annotations
specifically to the setter or getter part.
Note that this function implicitly assigns the
:cpp:enumerator:`rv_policy::reference` return value policy to
`getter` (as opposed to the usual
:cpp:enumerator:`rv_policy::automatic`). Provide an explicit return value
policy as part of the `extra` argument to override this.
**Example**: the example below uses `def_prop_rw_static` to expose a
static C++ setter/getter pair as a more "Pythonic" property:
.. code-block:: cpp
class A {
public:
static void set_value(int value) { s_value = value; }
static int value() { return s_value; }
private:
inline static int s_value = 5;
};
nb::class_<A>(m, "A")
.def_prop_rw_static("value",
[](nb::handle /*unused*/) { return A::value() ; },
[](nb::handle /*unused*/, int value) { A::set_value(value); });
.. cpp:function:: template <typename Getter, typename... Extra> class_ &def_prop_ro_static(const char * name, Getter &&getter, const Extra &...extra)
Construct a *read-only* (hence the ``ro`` suffix) Python ``property`` and
assign it to the class member `name`. Every read access will call the
function ``getter`` with `T`'s Python type object.
The variable length `extra` parameter can be used to pass a docstring and
other :ref:`function binding annotations <function_binding_annotations>`.
Note that this function implicitly assigns the
:cpp:enumerator:`rv_policy::reference` return value policy to
`getter` (as opposed to the usual
:cpp:enumerator:`rv_policy::automatic`). Provide an explicit return value
policy as part of the `extra` argument to override this.
**Example**: the example below uses `def_prop_ro_static` to expose a
static C++ getter as a more "Pythonic" property:
.. code-block:: cpp
class A {
public:
static int value() { return s_value; }
private:
inline static int s_value = 5;
};
nb::class_<A>(m, "A")
.def_prop_ro_static("value",
[](nb::handle /*unused*/) { return A::value() ; });
.. cpp:function:: template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra> class_ &def(const detail::op_<id, ot, L, R> &op, const Extra&... extra)
This interface provides convenient syntax sugar to replace relatively
lengthy method bindings with shorter operator bindings. To use it, you
will need an extra include directive:
.. code-block:: cpp
#include <nanobind/operators.h>
Below is an example type with three arithmetic operators in C++ (unary
negation and 2 binary subtraction overloads) along with corresponding
bindings.
**Example**:
.. code-block:: cpp
struct A {
float value;
A operator-() const { return { -value }; }
A operator-(const A &o) const { return { value - o.value }; }
A operator-(float o) const { return { value - o }; }
};
nb::class_<A>(m, "A")
.def(nb::init<float>())
.def(-nb::self)
.def(nb::self - nb::self)
.def(nb::self - float());
Bind an arithmetic or comparison operator expressed in short-hand form (e.g., ``.def(nb::self + nb::self)``).
.. cpp:function:: template <detail::op_id id, detail::op_type ot, typename L, typename R, typename... Extra> class_ &def_cast(const detail::op_<id, ot, L, R> &op, const Extra&... extra)
Like the above ``.def()`` variant, but furthermore cast the result of the operation back to `T`.
.. cpp:class:: template <typename T> enum_ : public class_<T>
Class binding helper for scoped and unscoped C++ enumerations.
.. cpp:function:: template <typename... Extra> NB_INLINE enum_(handle scope, const char * name, const Extra &...extra)
Bind the enumeration of type `T` to the identifier `name` within the
scope `scope`. The variable length `extra` parameter can be used to pass
a docstring and other :ref:`enum binding annotations
<enum_binding_annotations>` (currently, only :cpp:class:`is_arithmetic` is supported).
.. cpp:function:: enum_ &value(const char * name, T value, const char * doc = nullptr)
Add the entry `value` to the enumeration using the identifier `name`,
potentially with a docstring provided via `doc` (optional).
.. cpp:function:: enum_ &export_values()
Export all entries of the enumeration into the parent scope.
.. cpp:class:: template <typename T> exception : public object
Class binding helper for declaring new Python exception types
.. cpp:function:: exception(handle scope, const char * name, handle base = PyExc_Exception)
Create a new exception type identified by `name` that derives from
`base`, and install it in `scope`. The constructor also calls
:cpp:func:`register_exception_translator()` to register a new exception
translator that converts caught C++ exceptions of type `T` into the
newly created Python equivalent.
.. cpp:struct:: template <typename... Args> init
nanobind uses this simple helper class to capture the signature of a
constructor. It is only meant to be used in binding declarations done via
:cpp:func:`class_::def()`.
Sometimes, it is necessary to bind constructors that don't exist in the
underlying C++ type (meaning that they are specific to the Python bindings).
Because `init` only works for existing C++ constructors, this requires
a manual workaround noting that
.. code-block:: cpp
nb::class_<MyType>(m, "MyType")
.def(nb::init<const char*, int>());
is syntax sugar for the following lower-level implementation using
"`placement new <https://en.wikipedia.org/wiki/Placement_syntax>`_":
.. code-block:: cpp
nb::class_<MyType>(m, "MyType")
.def("__init__",
[](MyType* t, const char* arg0, int arg1) {
new (t) MyType(arg0, arg1);
});
The provided lambda function will be called with a pointer to uninitialized
memory that has already been allocated (this memory region is co-located
with the Python object for reasons of efficiency). The lambda function can
then either run an in-place constructor and return normally (in which case
the instance is assumed to be correctly constructed) or fail by raising an
exception.
.. cpp:struct:: template <typename Arg> init_implicit
See :cpp:class:`init` for detail on binding constructors. The main
difference between :cpp:class:`init` and `init_implicit` is that the latter
only supports constructors taking a single argument `Arg`, and that it marks
the constructor as usable for implicit conversions from `Arg`.
Sometimes, it is necessary to bind implicit conversion-capable constructors
that don't exist in the underlying C++ type (meaning that they are specific
to the Python bindings). This can be done manually noting that
.. code-block:: cpp
nb::class_<MyType>(m, "MyType")
.def(nb::init_implicit<const char*>());
can be replaced by the lower-level code
.. code-block:: cpp
nb::class_<MyType>(m, "MyType")
.def("__init__",
[](MyType* t, const char* arg0) {
new (t) MyType(arg0);
});
nb::implicitly_convertible<const char*, MyType>();
.. cpp:struct:: template <typename Func> new_
This is a small helper class that indicates to :cpp:func:`class_::def()`
that a particular lambda or static method provides a Python object
constructor (``__new__``) for the class being bound. Normally, you would
use :cpp:class:`init` instead if possible, in order to cooperate with
nanobind's usual object creation process. Using :cpp:class:`new_`
replaces that process entirely. This is principally useful when some
C++ type of interest can only provide pointers to its instances,
rather than allowing them to be constructed directly.
Like :cpp:class:`init`, the only use of a :cpp:class:`new_` object is
as an argument to :cpp:func:`class_::def()`.
Example use:
.. code-block:: cpp
class MyType {
private:
MyType();
public:
static std::shared_ptr<MyType> create();
int value = 0;
};
nb::class_<MyType>(m, "MyType")
.def(nb::new_(&MyType::create));
Given this example code, writing ``MyType()`` in Python would
produce a Python object wrapping the result of ``MyType::create()``
in C++. If multiple calls to ``create()`` return pointers to the
same C++ object, these will turn into references to the same Python
object as well.
See the discussion of :ref:`customizing Python object creation <custom_new>`
for more information.
.. cpp:struct:: template <typename Visitor> def_visitor
An empty base object which serves as a tag to allow :cpp:func:`class_::def()`
to dispatch to custom logic implemented by the type ``Visitor``. This is the
same mechanism used by :cpp:class:`init`, :cpp:class:`init_implicit`, and
:cpp:class:`new_`; it's exposed publicly so that you can create your own
reusable abstractions for binding logic.
To define a ``def_visitor``, you would write something like:
.. code-block:: cpp
struct my_ops : nb::def_visitor<my_ops> {
template <typename Class, typename... Extra>
void execute(Class &cl, const Extra&... extra) {
/* series of def() statements on `cl`, which is a nb::class_ */
}
};
Then use it like:
.. code-block:: cpp
nb::class_<MyType>(m, "MyType")
.def("some_method", &MyType::some_method)
.def(my_ops())
... ;
Any arguments to :cpp:func:`class_::def()` after the ``def_visitor`` object
get passed through as the ``Extra...`` parameters to ``execute()``.
As with any other C++ object, data needed by the ``def_visitor`` can be passed
through template arguments or ordinary constructor arguments.
The ``execute()`` method may be static if it doesn't need to access anything
in ``*this``.
GIL Management
--------------
These two `RAII
<https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization>`_ helper
classes acquire and release the *Global Interpreter Lock* (GIL) in a given
scope. The :cpp:struct:`gil_scoped_release` helper is often combined with the
:cpp:struct:`call_guard`, as in
.. code-block:: cpp
m.def("expensive", &expensive, nb::call_guard<nb::gil_scoped_release>());
This releases the interpreter lock while `expensive` is running, which permits
running it in parallel from multiple Python threads.
.. cpp:struct:: gil_scoped_acquire
.. cpp:function:: gil_scoped_acquire()
Acquire the GIL
.. cpp:function:: ~gil_scoped_acquire()
Release the GIL
.. cpp:struct:: gil_scoped_release
.. cpp:function:: gil_scoped_release()
Release the GIL (**must** be currently held)
In :ref:`free-threaded extensions <free-threaded>`, this operation also
temporarily releases all :ref:`argument locks <argument-locks>` held by
the current thread.
.. cpp:function:: ~gil_scoped_release()
Reacquire the GIL
Free-threading
--------------
Nanobind provides abstractions to implement *additional* locking that is
needed to ensure the correctness of free-threaded Python extensions.
.. cpp:struct:: ft_mutex
Object-oriented wrapper representing a `PyMutex
<https://docs.python.org/3.13/c-api/init.html#c.PyMutex>`__. It can be
slightly more efficient than OS/language-provided primitives (e.g.,
``std::thread``, ``pthread_mutex_t``) and should generally be preferred when
adding critical sections to Python bindings.
In Python builds *without* free-threading, this class does nothing. It has
no attributes and the :cpp:func:`lock` and :cpp:func:`unlock` functions
return immediately.
.. cpp:function:: ft_mutex()
Create a new (unlocked) mutex.
.. cpp:function:: void lock()
Acquire the mutex.
.. cpp:function:: void unlock()
Release the mutex.
.. cpp:struct:: ft_lock_guard
This class provides a RAII lock guard analogous to ``std::lock_guard`` and
``std::unique_lock``.
.. cpp:function:: ft_lock_guard(ft_mutex &mutex)
Call :cpp:func:`mutex.lock() <ft_mutex::lock>` (no-op in non-free-threaded builds).
.. cpp:function:: ~ft_lock_guard()
Call :cpp:func:`mutex.unlock() <ft_mutex::unlock>` (no-op in non-free-threaded builds).
.. cpp:struct:: ft_object_guard
This class provides a RAII guard that locks a single Python object within a
local scope (in contrast to :cpp:class:`ft_lock_guard`, which locks a
mutex).
It is a thin wrapper around the Python `critical section API
<https://docs.python.org/3.13/c-api/init.html#c.Py_BEGIN_CRITICAL_SECTION>`__.
Please refer to the Python documentation for details on the semantics of
this relaxed form of critical section (in particular, Python critical sections
may release previously held locks).
In Python builds *without* free-threading, this class does nothing---the
constructor and destructor return immediately.
.. cpp:function:: ft_object_guard(handle h)
Lock the object ``h`` (no-op in non-free-threaded builds)
.. cpp:function:: ~ft_object_guard()
Unlock the object ``h`` (no-op in non-free-threaded builds)
.. cpp:struct:: ft_object2_guard
This class provides a RAII guard that locks *two* Python object within a
local scope (in contrast to :cpp:class:`ft_lock_guard`, which locks a
mutex).
It is a thin wrapper around the Python `critical section API
<https://docs.python.org/3.13/c-api/init.html#c.Py_BEGIN_CRITICAL_SECTION2>`__.
Please refer to the Python documentation for details on the semantics of
this relaxed form of critical section (in particular, Python critical sections
may release previously held locks).
In Python builds *without* free-threading, this class does nothing---the
constructor and destructor return immediately.
.. cpp:function:: ft_object2_guard(handle h1, handle h2)
Lock the objects ``h1`` and ``h2`` (no-op in non-free-threaded builds)
.. cpp:function:: ~ft_object2_guard()
Unlock the objects ``h1`` and ``h2`` (no-op in non-free-threaded builds)
Low-level type and instance access
----------------------------------
nanobind exposes a low-level interface to provide fine-grained control over
the sequence of steps that instantiates a Python object wrapping a C++
instance. A thorough explanation of these features is provided in a
:ref:`separate section <lowlevel>`.
Type objects
^^^^^^^^^^^^
.. cpp:function:: bool type_check(handle h)
Returns ``true`` if ``h`` is a type that was previously bound via
:cpp:class:`class_`.
.. cpp:function:: size_t type_size(handle h)
Assuming that `h` represents a bound type (see :cpp:func:`type_check`),
return its size in bytes.
.. cpp:function:: size_t type_align(handle h)
Assuming that `h` represents a bound type (see :cpp:func:`type_check`),
return its alignment in bytes.
.. cpp:function:: const std::type_info& type_info(handle h)
Assuming that `h` represents a bound type (see :cpp:func:`type_check`),
return its C++ RTTI record.
.. cpp:function:: template <typename T> T &type_supplement(handle h)
Return a reference to supplemental data stashed in a type object.
The type ``T`` must exactly match the type specified in the
:cpp:class:`nb::supplement\<T\> <supplement>` annotation used when
creating the type; no type check is performed, and invalid supplement
accesses may crash the interpreter. Also refer to
:cpp:class:`nb::supplement\<T\> <supplement>`.
.. cpp:function:: str type_name(handle h)
Return the full (module-qualified) name of a type object as a Python string.
.. cpp:function:: void * type_get_slot(handle h, int slot_id)
On Python 3.10+, this function is a simple wrapper around the Python C API
function ``PyType_GetSlot`` that provides stable API-compatible access to
type object members. On Python 3.9 and earlier, the official function did
not work on non-heap types. The nanobind version consistently works on heap
and non-heap types across Python versions.
Instances
^^^^^^^^^
The documentation below refers to two per-instance flags with the following meaning:
- *ready*: is the instance fully constructed? nanobind will not permit passing
the instance to a bound C++ function when this flag is unset.
- *destruct*: should nanobind call the C++ destructor when the instance is
garbage-collected?
.. cpp:function:: bool inst_check(handle h)
Returns ``true`` if `h` represents an instance of a type that was
previously bound via :cpp:class:`class_`.
.. cpp:function:: template <typename T> T * inst_ptr(handle h)
Assuming that `h` represents an instance of a type that was previously bound
via :cpp:class:`class_`, return a pointer to the underlying C++ instance.
The function *does not check* that `h` actually contains an instance with
C++ type `T`.
.. cpp:function:: object inst_alloc(handle h)
Assuming that `h` represents a type object that was previously created via
:cpp:class:`class_` (see :cpp:func:`type_check`), allocate an unitialized
object of type `h` and return it. The *ready* and *destruct* flags of the
returned instance are both set to ``false``.
.. cpp:function:: object inst_alloc_zero(handle h)
Assuming that `h` represents a type object that was previously created via
:cpp:class:`class_` (see :cpp:func:`type_check`), allocate a zero-initialized
object of type `h` and return it. The *ready* and *destruct* flags of the
returned instance are both set to ``true``.
This operation is equivalent to calling :cpp:func:`inst_alloc` followed by
:cpp:func:`inst_zero`.
.. cpp:function:: object inst_reference(handle h, void * p, handle parent = handle())
Assuming that `h` represents a type object that was previously created via
:cpp:class:`class_` (see :cpp:func:`type_check`) create an object of type
`h` that wraps an existing C++ instance `p`.
The *ready* and *destruct* flags of the returned instance are respectively
set to ``true`` and ``false``.
This is analogous to casting a C++ object with return value policy
:cpp:enumerator:`rv_policy::reference`.
If a `parent` object is specified, the instance keeps this parent alive
while the newly created object exists. This is analogous to casting a C++
object with return value policy
:cpp:enumerator:`rv_policy::reference_internal`.
.. cpp:function:: object inst_take_ownership(handle h, void * p)
Assuming that `h` represents a type object that was previously created via
:cpp:class:`class_` (see :cpp:func:`type_check`) create an object of type
`h` that wraps an existing C++ instance `p`.
The *ready* and *destruct* flags of the returned instance are both set to
``true``.
This is analogous to casting a C++ object with return value policy
:cpp:enumerator:`rv_policy::take_ownership`.
.. cpp:function:: void inst_zero(handle h)
Zero-initialize the contents of `h`. Sets the *ready* and *destruct* flags
to ``true``.
.. cpp:function:: bool inst_ready(handle h)
Query the *ready* flag of the instance `h`.
.. cpp:function:: std::pair<bool, bool> inst_state(handle h)
Separately query the *ready* and *destruct* flags of the instance `h`.
.. cpp:function:: void inst_mark_ready(handle h)
Simultaneously set the *ready* and *destruct* flags of the instance `h` to ``true``.
.. cpp:function:: void inst_set_state(handle h, bool ready, bool destruct)
Separately set the *ready* and *destruct* flags of the instance `h`.
.. cpp:function:: void inst_destruct(handle h)
Destruct the instance `h`. This entails calling the C++ destructor if the
*destruct* flag is set and then setting the *ready* and *destruct* fields to
``false``.
.. cpp:function:: void inst_copy(handle dst, handle src)
Copy-construct the contents of `src` into `dst` and set the *ready* and
*destruct* flags of `dst` to ``true``.
`dst` should be an uninitialized instance of the same type. Note that
setting the *destruct* flag may be problematic if `dst` is an offset into an
existing object created using :cpp:func:`inst_reference` (the destructor
will be called multiple times in this case). If so, you must use
:cpp:func:`inst_set_state` to disable the flag following the call to
:cpp:func:`inst_copy`.
*New in nanobind v2.0.0*: The function is a no-op when ``src`` and ``dst``
refer to the same object.
.. cpp:function:: void inst_move(handle dst, handle src)
Analogous to :cpp:func:`inst_copy`, except that the move constructor
is used instead of the copy constructor.
.. cpp:function:: void inst_replace_copy(handle dst, handle src)
Destruct the contents of `dst` (even if the *destruct* flag is ``false``).
Next, copy-construct the contents of `src` into `dst` and set the *ready*
flag of ``dst``. The value of the *destruct* flag is subsequently set to its
value prior to the call.
This operation is useful to replace the contents of one instance with that
of another regardless of whether `dst` has been created using
:cpp:func:`inst_alloc`, :cpp:func:`inst_reference`, or
:cpp:func:`inst_take_ownership`.
*New in nanobind v2.0.0*: The function is a no-op when ``src`` and ``dst``
refer to the same object.
.. cpp:function:: void inst_replace_move(handle dst, handle src)
Analogous to :cpp:func:`inst_replace_copy`, except that the move constructor
is used instead of the copy constructor.
.. cpp:function:: str inst_name(handle h)
Return the full (module-qualified) name of the instance's type object as a
Python string.
Global flags
------------
.. cpp:function:: bool leak_warnings() noexcept
Returns whether nanobind warns if any nanobind instances, types, or
functions are still alive when the Python interpreter shuts down.
.. cpp:function:: bool implicit_cast_warnings() noexcept
Returns whether nanobind warns if an implicit conversion was not successful.
.. cpp:function:: void set_leak_warnings(bool value) noexcept
By default, nanobind loudly complains when any nanobind instances, types, or
functions are still alive when the Python interpreter shuts down. Call this
function to disable or re-enable leak warnings.
.. cpp:function:: void set_implicit_cast_warnings(bool value) noexcept
By default, nanobind loudly complains when it attempts to perform an
implicit conversion, and when that conversion is not successful. Call this
function to disable or re-enable the warnings.
.. cpp:function:: inline bool is_alive() noexcept
The function returns ``true`` when nanobind is initialized and ready for
use. It returns ``false`` when the Python interpreter has shut down, causing
the destruction various nanobind-internal data structures. Having access to
this liveness status can be useful to avoid operations that are illegal in
the latter context.
Miscellaneous
-------------
.. cpp:function:: str repr(handle h)
Return a stringified version of the provided Python object.
Equivalent to ``repr(h)`` in Python.
.. cpp:function:: void print(handle value, handle end = handle(), handle file = handle())
Invoke the Python ``print()`` function to print the object `value`. If desired,
a line ending `end` and file handle `file` can be specified.
.. cpp:function:: void print(const char * str, handle end = handle(), handle file = handle())
Invoke the Python ``print()`` function to print the null-terminated C-style
string `str` that is encoded using UTF-8 encoding. If desired, a line
ending `end` and file handle `file` can be specified.
.. cpp:function:: iterator iter(handle h)
Equivalent to ``iter(h)`` in Python.
.. cpp:function:: object none()
Return an object representing the value ``None``.
.. cpp:function:: dict builtins()
Return the ``__builtins__`` dictionary.
.. cpp:function:: dict globals()
Return the ``globals()`` dictionary.
.. cpp:function:: Py_hash_t hash(handle h)
Hash the given argument like ``hash()`` in pure Python. The type of the
return value (``Py_hash_t``) is an implementation-specific signed integer
type.
.. cpp:function:: template <typename Source, typename Target> void implicitly_convertible()
Indicate that the type `Source` is implicitly convertible into `Target`
(which must refer to a type that was previously bound via
:cpp:class:`class_`).
*Note*: the :cpp:struct:`init_implicit` interface generates more compact
code and should be preferred, i.e., use
.. code-block:: cpp
nb::class_<Target>(m, "Target")
.def(nb::init_implicit<Source>());
instead of
.. code-block:: cpp
nb::class_<Target>(m, "Target")
.def(nb::init<Source>());
nb::implicitly_convertible<Source, Target>();
The function is provided for reasons of compatibility with pybind11, and as
an escape hatch to enable use cases where :cpp:struct:`init_implicit`
is not available (e.g., for custom binding-specific constructors that don't
exist in `Target` type).
.. cpp:class:: template <typename T, typename... Ts> typed
This helper class provides an interface to parameterize generic types to
improve generated Python function signatures (e.g., to turn ``list`` into
``list[MyType]``).
Consider the following binding that iterates over a Python list.
.. code-block:: cpp
m.def("f", [](nb::list l) {
for (handle h : l) {
// ...
}
});
Suppose that ``f`` expects a list of ``MyType`` objects, which is not clear
from the signature. To make this explicit, use the ``nb::typed<T, Ts...>``
wrapper to pass additional type parameters. This has no effect besides
clarifying the signature---in particular, nanobind does *not* insert
additional runtime checks! At runtime, a ``nb::typed<T, Ts...>`` behaves
exactly like a ``T``.
.. code-block:: cpp
m.def("f", [](nb::typed<nb::list, MyType> l) {
for (nb::handle h : l) {
// ...
}
});
``nb::typed<nb::object, T>`` and ``nb::typed<nb::handle, T>`` are
treated specially: they generate a signature that refers just to ``T``,
rather than to the nonsensical ``object[T]`` that would otherwise
be produced. This can be useful if you want to replace the type of
a parameter instead of augmenting it. Note that at runtime these
perform no checks at all, since ``nb::object`` and ``nb::handle``
can refer to any Python object.
To support callable types, you can specify a C++ function signature in
``nb::typed<nb::callable, Sig>`` and nanobind will attempt to convert
it to a Python callable signature.
``nb::typed<nb::callable, int(float, std::string)>`` becomes
``Callable[[float, str], int]``, while
``nb::typed<nb::callable, int(...)>`` becomes ``Callable[..., int]``.
Type checkers will verify that any callable passed for such an argument
has a compatible signature. (At runtime, any sort of callable object
will be accepted.)
|