### Project Setup with CMake Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Initializes a C++ project and warns against direct CMake invocation, suggesting scikit-build-core for proper installation. It also demonstrates how to find Python and nanobind packages, including optional support for stable ABI builds. ```cmake project(my_ext LANGUAGES CXX) # Warn if the user invokes CMake directly if (NOT SKBUILD) message(WARNING "\n This CMake file is meant to be executed using 'scikit-build-core'. Running it directly will almost certainly not produce the desired result. If you are a user trying to install this package, use the command below, which will install all necessary build dependencies, compile the package in an isolated environment, and then install it. ===================================================================== $ pip install . ===================================================================== If you are a software developer, and this is your own package, then it is usually much more efficient to install the build dependencies in your environment once and use the following command that avoids a costly creation of a new virtual environment at every compilation: ===================================================================== $ pip install nanobind scikit-build-core[pyproject] $ pip install --no-build-isolation -ve . ===================================================================== You may optionally add -Ceditable.rebuild=true to auto-rebuild when the package is imported. Otherwise, you need to rerun the above after editing C++ files.") endif() # Try to import all Python components potentially needed by nanobind find_package(Python 3.9 REQUIRED COMPONENTS Interpreter Development.Module OPTIONAL_COMPONENTS Development.SABIModule) # Import nanobind through CMake's find_package mechanism find_package(nanobind CONFIG REQUIRED) ``` -------------------------------- ### Install extension, stub, and marker file Source: https://nanobind.readthedocs.io/en/latest/typing.html Installs the compiled extension, its stub file, and the py.typed marker file to the destination directory. ```cmake install(TARGETS my_ext DESTINATION ".") install(FILES py.typed my_ext.pyi DESTINATION ".") ``` -------------------------------- ### Accessing the Extension Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Demonstrates how to import and use the installed Python extension. This verifies that the packaging and installation process was successful. ```python import my_ext my_ext.hello() ``` -------------------------------- ### Verify Package Installation Source: https://nanobind.readthedocs.io/en/latest/packaging.html After installation, import your extension and call a function to verify it works correctly. This assumes your package is named 'my_ext'. ```python import my_ext my_ext.hello() ``` -------------------------------- ### Tag-Based Polymorphism Setup Source: https://nanobind.readthedocs.io/en/latest/_sources/classes.rst.txt Set up tag-based polymorphism by defining a class hierarchy and an enum for type identification. This example includes the initial nanobind module definition. ```cpp #include namespace nb = nanobind; enum class PetKind { Cat, Dog }; struct Pet { const PetKind kind; }; struct Dog : Pet { Dog() : Pet{PetKind::Dog} { } }; struct Cat : Pet { Cat() : Pet{PetKind::Cat} { } }; namespace nb = nanobind; NB_MODULE(my_ext, m) { nb::class_(m, "Pet"); nb::class_(m, "Dog"); nb::class_(m, "Cat"); nb::enum_(m, "PetKind") .value("Cat", PetKind::Cat) .value("Dog", PetKind::Dog); m.def("make_pet", [](PetKind kind) -> Pet* { switch (kind) { case PetKind::Dog: return new Dog(); case PetKind::Cat: return new Cat(); } }); } ``` -------------------------------- ### Install stub and marker files with CMake Source: https://nanobind.readthedocs.io/en/latest/_sources/typing.rst.txt After generating stub and marker files, use `install()` directives to place them in the destination directory. ```cmake install(TARGETS my_ext DESTINATION ".") install(FILES py.typed my_ext.pyi DESTINATION ".") ``` -------------------------------- ### Example of using slice.compute Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Demonstrates how to use the `compute` method of a slice object to get adjusted slice parameters and the computed slice length. ```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 ... }); ``` -------------------------------- ### Install nanobind and robin-map with Meson WrapDB Source: https://nanobind.readthedocs.io/en/latest/_sources/meson.rst.txt Create a 'subprojects' directory and use 'meson wrap install' to add nanobind and robin-map as project dependencies. ```sh mkdir -p subprojects meson wrap install robin-map meson wrap install nanobind ``` -------------------------------- ### Install nanobind via Pip Source: https://nanobind.readthedocs.io/en/latest/_sources/installing.rst.txt Use this command to install the nanobind package, which includes C++ and CMake source code for compiling extension modules. This is the recommended installation method. ```bash python -m pip install nanobind ``` -------------------------------- ### Installing Build Dependencies Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Installs the necessary build tools and libraries for the project. This is a prerequisite for enabling incremental builds. ```bash pip install nanobind scikit-build-core[pyproject] ``` -------------------------------- ### Install Build Dependencies Source: https://nanobind.readthedocs.io/en/latest/packaging.html Before enabling incremental builds, install the necessary build dependencies. This command includes nanobind and scikit-build-core. ```bash pip install nanobind scikit-build-core[pyproject] ``` -------------------------------- ### Editable Install with Pip Source: https://nanobind.readthedocs.io/en/latest/meson.html Installs the nanobind extension as an editable package using pip. ```bash python -m pip install -e . ``` -------------------------------- ### Editable install with pip Source: https://nanobind.readthedocs.io/en/latest/_sources/meson.rst.txt Install the package as an editable install using pip, useful when local build folders are not desired. ```sh python -m pip install -e . ``` -------------------------------- ### Example Project Directory Structure Source: https://nanobind.readthedocs.io/en/latest/packaging.html Illustrates the typical file and directory layout for a nanobind project. ```text ├── README.md ├── CMakeLists.txt ├── pyproject.toml └── src/ ├── my_ext.cpp └── my_ext/ └── __init__.py ``` -------------------------------- ### Pattern File DSL Example Source: https://nanobind.readthedocs.io/en/latest/_sources/typing.rst.txt This example demonstrates the domain-specific language (DSL) used in pattern files for nanobind.stubgen. It shows how to define patterns with queries and indented replacement blocks to modify generated stub entries, such as adding typed overloads to a function. ```text # This is the first pattern query 1: replacement 1 # And this is the second one query 2: replacement 2 ``` -------------------------------- ### Example Project Directory Structure Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Illustrates the typical file and directory layout for a nanobind project intended for packaging. ```text ├── README.md ├── CMakeLists.txt ├── pyproject.toml └── src/ ├── my_ext.cpp └── my_ext/ └── __init__.py ``` -------------------------------- ### Local Package Installation Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Installs the Python package locally using pip. This command parses pyproject.toml, installs dependencies, and builds the extension in a fresh environment. ```bash cd pip install . ``` -------------------------------- ### Install Package Locally with Pip Source: https://nanobind.readthedocs.io/en/latest/packaging.html Use this command to install your package locally after navigating to the project directory. Pip will parse pyproject.toml and install dependencies. ```bash cd pip install . ``` -------------------------------- ### Generate stub at install time with CMake Source: https://nanobind.readthedocs.io/en/latest/_sources/typing.rst.txt Delay stub generation to the installation phase using the `INSTALL_TIME` parameter. Adjust `PYTHON_PATH` and `OUTPUT` accordingly, and ensure preceding `install()` commands place necessary files. ```cmake install(TARGETS my_ext DESTINATION ".") nanobind_add_stub( my_ext_stub INSTALL_TIME MODULE my_ext OUTPUT my_ext.pyi PYTHON_PATH "." ) ``` -------------------------------- ### Install-time stub generation Source: https://nanobind.readthedocs.io/en/latest/typing.html Delays stub generation to the installation phase using the INSTALL_TIME parameter. Adjust PYTHON_PATH and ensure install() directives precede nanobind_add_stub(). Dependencies are not needed for install-time generation. ```cmake install(TARGETS my_ext DESTINATION ".") nanobind_add_stub( my_ext_stub INSTALL_TIME MODULE my_ext OUTPUT my_ext.pyi PYTHON_PATH "." ) ``` -------------------------------- ### Install nanobind via Conda Source: https://nanobind.readthedocs.io/en/latest/_sources/installing.rst.txt Install nanobind using Conda, suitable for users developing Conda-based extensions with a build-time dependency on nanobind. This method is an alternative when the PyPI package cannot be used. ```bash conda install -c conda-forge nanobind ``` -------------------------------- ### Python Keyword-Only Parameters Example Source: https://nanobind.readthedocs.io/en/latest/functions.html This Python code illustrates the concept of keyword-only parameters, showing how they enforce clarity and can be used with variadic arguments. It includes examples of correct and incorrect usage. ```python def example(val: int, *, check: bool) -> None: # val can be passed either way; check must be given as a keyword arg pass example(val=42, check=True) # good example(check=False, val=5) # good example(100, check=True) # good example(200, False) # TypeError: # example() takes 1 positional argument but 2 were given def munge(*args: int, invert: bool = False) -> int: return sum(args) * (-1 if invert else 1) munge(1, 2, 3) # 6 munge(4, 5, 6, invert=True) # -15 ``` -------------------------------- ### Meson Project Configuration Source: https://nanobind.readthedocs.io/en/latest/meson.html Basic meson.build file for a nanobind extension. Ensure 'meson-python' is installed and nanobind is available as a dependency. ```meson project( 'my_project_name', 'cpp', version: '0.0.1', meson_version: '>=1.0.0', default_options: ['cpp_std=c++17', 'b_ndebug=if-release'], ) python = import('python').find_installation() nanobind_dep = dependency('nanobind') mod = python.extension_module( 'my_module_name', sources: ['path_to_module.cpp'], dependencies: [nanobind_dep], install: true, ) ``` -------------------------------- ### Get typing.Any Source: https://nanobind.readthedocs.io/en/latest/_sources/api_extra.rst.txt Obtain an instance of typing.Any using a convenience wrapper. ```cpp nb::any_type() ``` -------------------------------- ### Get Device ID for Array Source: https://nanobind.readthedocs.io/en/latest/api_extra.html Retrieves the ID of the device hosting the array, useful in multi-device setups. Matches `device::cpu::value` or `device::cuda::value`. ```cpp int device_id() const ``` -------------------------------- ### Parallel Array Loop with View Source: https://nanobind.readthedocs.io/en/latest/_sources/ndarray.rst.txt Example of using OpenMP to parallelize an array loop, passing the `ndarray` view using `firstprivate` to ensure each thread gets a register copy. ```cpp auto v = arg.view(); #pragma omp parallel for schedule(static) firstprivate(v) for (...) { /* parallel loop */ } ``` -------------------------------- ### Working Example with Trampoline Source: https://nanobind.readthedocs.io/en/latest/_sources/classes.rst.txt Shows the expected output when the alarm function correctly calls the Python-overridden bark method via the trampoline. ```pycon >>> my_ext.alarm(dog) Mr. Fluffles: yip! Mr. Fluffles: yip! Mr. Fluffles: yip! ``` -------------------------------- ### Compute Slice Details Source: https://nanobind.readthedocs.io/en/latest/api_core.html Computes slice details adjusted to a container size. Returns a tuple of (start, stop, step, slice_length). Demonstrates using structured bindings and the `get` member function to access tuple elements. ```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 ... }); ``` -------------------------------- ### Meson Build Commands Source: https://nanobind.readthedocs.io/en/latest/meson.html Commands to set up and compile a nanobind extension using Meson. ```bash meson setup --buildtype release builddir meson compile -C builddir ``` -------------------------------- ### Navigate to build directory and run Python Source: https://nanobind.readthedocs.io/en/latest/_sources/basics.rst.txt After successful compilation, change into the build directory and start an interactive Python session to test your extension. The exact path might differ on Windows. ```bash cd build python3 ``` -------------------------------- ### Find Installed nanobind Package Source: https://nanobind.readthedocs.io/en/latest/_sources/building.rst.txt Detects the installation path of a nanobind package installed via pip or Conda and imports it into CMake. This is used when nanobind is not a Git submodule. ```cmake # Detect the installed nanobind package and import it into CMake execute_process( COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT) find_package(nanobind CONFIG REQUIRED) ``` -------------------------------- ### Compile nanobind extension with Meson Source: https://nanobind.readthedocs.io/en/latest/_sources/meson.rst.txt Use 'meson setup' to configure the build and 'meson compile' to build the extension module. Specify build type and output directory. ```sh meson setup --buildtype release builddir meson compile -C builddir ``` -------------------------------- ### Partitioning Binding Projects Source: https://nanobind.readthedocs.io/en/latest/_sources/faq.rst.txt Organize large binding projects into multiple files by defining initialization functions for each part. This improves build times and manageability. ```cpp void init_ex1(nb::module_ &); void init_ex2(nb::module_ &); /* ... */ NB_MODULE(my_ext, m) { init_ex1(m); init_ex2(m); /* ... */ } ``` ```cpp void init_ex1(nb::module_ &m) { m.def("add", [](int a, int b) { return a + b; }); } ``` ```cpp void init_ex2(nb::module_ &m) { m.def("sub", [](int a, int b) { return a - b; }); } ``` -------------------------------- ### Import and use the extension in Python Source: https://nanobind.readthedocs.io/en/latest/basics.html Navigate to the build directory and launch an interactive Python session to import and test your newly compiled extension. ```python >>> import my_ext >>> my_ext.add(1, 2) 3 ``` -------------------------------- ### Configure build with CMake Source: https://nanobind.readthedocs.io/en/latest/_sources/basics.rst.txt Use this CMake command to set up the build system for your nanobind extension. It creates a 'build' directory for all output files. ```bash cmake -S . -B build ``` -------------------------------- ### Configure cibuildwheel Architectures Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Specify target architectures using the 'archs' option to limit the build matrix. This example targets only 64-bit architectures. ```toml archs = ["auto64"] # Only target 64 bit architectures ``` -------------------------------- ### Python Package Initialization Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt The __init__.py file for a nanobind extension, importing the compiled C++ module. ```python from ._my_ext_impl import hello ``` -------------------------------- ### Install Trampoline with NB_TRAMPOLINE Source: https://nanobind.readthedocs.io/en/latest/api_extra.html Use NB_TRAMPOLINE to install a trampoline in an alias class, enabling C++ virtual function calls to be dispatched to a Python implementation. ```cpp NB_TRAMPOLINE(base, size) ``` -------------------------------- ### Example: Removing Stub Entries Source: https://nanobind.readthedocs.io/en/latest/typing.html A pattern with an empty replacement block removes any stub entry matching the query. This example removes entries containing 'secret'. ```plaintext secret: ``` -------------------------------- ### inst_ready Source: https://nanobind.readthedocs.io/en/latest/api_core.html Queries the _ready_ flag of a nanobind instance. ```APIDOC ## inst_ready ### Description Query the _ready_ flag of the instance `h`. ### Signature ```cpp bool inst_ready(handle h) ``` ``` -------------------------------- ### Python Exception Chaining Example Source: https://nanobind.readthedocs.io/en/latest/_sources/exceptions.rst.txt A Python code example demonstrating the 'raise from' syntax for chaining exceptions, where a new exception is raised with the original exception as its cause. ```py try: print(1 / 0) except Exception as exc: raise RuntimeError("could not divide by zero") from exc ``` -------------------------------- ### Zero-initialize and mark POD instance as ready Source: https://nanobind.readthedocs.io/en/latest/_sources/lowlevel.rst.txt For POD types, this function zero-initializes the instance memory and marks the nanobind instance as ready for use. ```cpp nb::inst_zero(py_inst); assert(nb::inst_ready(py_inst)); ``` -------------------------------- ### Install Package with No Build Isolation Source: https://nanobind.readthedocs.io/en/latest/packaging.html Install the project without build isolation to enable incremental builds. This command should be run after every source file change during development. ```bash pip install --no-build-isolation -ve . ``` -------------------------------- ### Adjust build and install rpath for nanobind extension Source: https://nanobind.readthedocs.io/en/latest/_sources/faq.rst.txt These CMake commands can be used to adjust the build and install rpath of the extension, helping it find the nanobind shared library. ```cmake set_property(TARGET my_ext APPEND PROPERTY BUILD_RPATH "$") set_property(TARGET my_ext APPEND PROPERTY INSTALL_RPATH ".. ?? ..") ``` -------------------------------- ### Basic Meson.build configuration for nanobind extension Source: https://nanobind.readthedocs.io/en/latest/_sources/meson.rst.txt Define project settings, find Python, and configure the extension module using nanobind dependency. Ensure C++17 standard and release build type. ```meson project( 'my_project_name', 'cpp', version: '0.0.1', meson_version: '>=1.0.0', default_options: ['cpp_std=c++17', 'b_ndebug=if-release'], ) python = import('python').find_installation() nanobind_dep = dependency('nanobind') mod = python.extension_module( 'my_module_name', sources: ['path_to_module.cpp'], dependencies: [nanobind_dep], install: true, ) ``` -------------------------------- ### Install Python development headers (Ubuntu) Source: https://nanobind.readthedocs.io/en/latest/_sources/basics.rst.txt If CMake fails to find Python, you may need to install the Python 3 development package. This command is for Ubuntu systems. ```bash apt install libpython3-dev ``` -------------------------------- ### Compile Project Code and Extension Module with nanobind Source: https://nanobind.readthedocs.io/en/latest/api_cmake.html This example demonstrates compiling separate project code into a static library and then linking it with a nanobind extension module. It highlights the use of `POSITION_INDEPENDENT_CODE` for the static library and `nanobind_add_module` for the extension. ```cmake add_library(example_lib STATIC source_1.cpp source_2.cpp) set_target_properties(example_lib PROPERTIES POSITION_INDEPENDENT_CODE ON) nanobind_add_module(example_ext common.h source_1.cpp source_2.cpp) target_link_libraries(example_ext PRIVATE example_lib) ``` -------------------------------- ### Example nanobind Leak Warning Output Source: https://nanobind.readthedocs.io/en/latest/_sources/refleaks.rst.txt Example output of a nanobind reference leak warning, indicating leaked instances, types, and functions during Python interpreter shutdown. ```text nanobind: leaked 1 instances! - leaked instance 0x102123728 of type "my_ext.MyClass" nanobind: leaked 1 types! - leaked type "my_ext.MyClass" nanobind: leaked 1 functions! - leaked function "__init__" nanobind: this is likely caused by a reference counting issue in the binding code. See https://nanobind.readthedocs.io/en/latest/refleaks.html ``` -------------------------------- ### Python dynamic attribute assignment example Source: https://nanobind.readthedocs.io/en/latest/_sources/classes.rst.txt Demonstrates how Python classes can have attributes added or modified dynamically. This example shows overwriting an existing attribute and adding a new one. ```pycon >>> class Pet: ... name = "Molly" ... >>> p = Pet() >>> p.name = "Charly" # overwrite existing >>> p.age = 2 # dynamically add a new attribute ``` -------------------------------- ### Python Package Initialization Source: https://nanobind.readthedocs.io/en/latest/packaging.html The __init__.py file imports the compiled extension module. ```python from ._my_ext_impl import hello ``` -------------------------------- ### Equivalent CMake commands for nanobind_add_module Source: https://nanobind.readthedocs.io/en/latest/api_cmake.html This demonstrates the equivalent CMake commands for a single nanobind_add_module call, showing the granular control available. ```cmake nanobind_add_module(my_ext NB_SHARED LTO my_ext.cpp) ``` ```cmake # Build the core parts of nanobind once nanobind_build_library(nanobind SHARED) # Compile an extension library add_library(my_ext MODULE my_ext.cpp) # .. and link it against the nanobind parts target_link_libraries(my_ext PRIVATE nanobind) # .. enable size optimizations nanobind_opt_size(my_ext) # .. enable link time optimization nanobind_lto(my_ext) # .. set the default symbol visibility to 'hidden' nanobind_set_visibility(my_ext) # .. strip unneeded symbols and debug info from the binary (only active in release builds) nanobind_strip(my_ext) # .. disable the stack protector nanobind_disable_stack_protector(my_ext) # .. set the Python extension suffix nanobind_extension(my_ext) # .. set important compilation flags nanobind_compile_options(my_ext) # .. set important linker flags nanobind_link_options(my_ext) # Statically link against libstdc++/libgcc when targeting musllinux nanobind_musl_static_libcpp(my_ext) ``` -------------------------------- ### Configure CMake Build System Source: https://nanobind.readthedocs.io/en/latest/packaging.html Sets up the CMake build system, project name, and warns users against direct invocation. It provides installation instructions for both users and developers. ```cmake cmake_minimum_required(VERSION 3.15...3.27) project(my_ext LANGUAGES CXX) if (NOT SKBUILD) message(WARNING "\ This CMake file is meant to be executed using 'scikit-build-core'. Running it directly will almost certainly not produce the desired result. If you are a user trying to install this package, use the command below, which will install all necessary build dependencies, compile the package in an isolated environment, and then install it. ===================================================================== $ pip install . ===================================================================== If you are a software developer, and this is your own package, then it is usually much more efficient to install the build dependencies in your environment once and use the following command that avoids a costly creation of a new virtual environment at every compilation: ===================================================================== $ pip install nanobind scikit-build-core[pyproject] $ pip install --no-build-isolation -ve . ===================================================================== You may optionally add -Ceditable.rebuild=true to auto-rebuild when the package is imported. Otherwise, you need to rerun the above after editing C++ files.") endif() ``` -------------------------------- ### Python Usage Example for Bound Pet Class Source: https://nanobind.readthedocs.io/en/latest/classes.html Shows how to instantiate and interact with the bound 'Pet' class and its 'Kind' enumeration in Python. This verifies the binding works as expected. ```python >>> from my_ext import Pet >>> p = Pet("Lucy", Pet.Cat) >>> p.attr.age = 3 >>> p.type my_ext.Kind.Cat >>> p.type.__name__ 'Cat' ``` -------------------------------- ### Installing Custom Type Slots Source: https://nanobind.readthedocs.io/en/latest/_sources/lowlevel.rst.txt Use `nb::type_slots()` to install custom type slots (PyType_Slot) into newly constructed types. This allows for advanced customization, such as overriding CPython object protocol methods. ```cpp nb::class_(m, "MyClass", nb::type_slots(slots)); ``` -------------------------------- ### Create Nanobind Module Entry Point Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Use NB_MODULE to define the entry point for a Python extension module. The first argument is the module name, and the second defines a variable of type nanobind::module_ to populate the module's contents. ```cpp NB_MODULE(example, m) { m.doc() = "Example module"; // Add bindings here m.def("add", []() { return "Hello, World!"; }); } ``` -------------------------------- ### Example of Using nb::typed for Callable Signatures Source: https://nanobind.readthedocs.io/en/latest/api_core.html This example shows how `nb::typed` can be used with `nb::callable` to specify a C++ function signature, which nanobind converts to a Python callable signature for type checking. ```cpp nb::typed ``` ```cpp nb::typed ``` -------------------------------- ### Python Usage of Exposed C++ Function Source: https://nanobind.readthedocs.io/en/latest/exchanging.html These Python examples show how to call the `double_it` function exposed via nanobind. The first example demonstrates a successful call with valid integer inputs, while the second shows a TypeError when incompatible types are provided. ```python >>> import my_ext >>> my_ext.double_it([1, 2, 3]) [2, 4, 6] >>> my_ext.double_it([1, 2, 'foo']) TypeError: double_it(): incompatible function arguments. The following argument types are supported: 1. double_it(arg: list[int], /) -> list[int] ``` -------------------------------- ### Stubgen Command Line Options Source: https://nanobind.readthedocs.io/en/latest/typing.html Displays the available command-line options for the nanobind stubgen utility, including output file/directory specification, module inclusion, and exclusion options. ```bash usage: python -m nanobind.stubgen [-h] [-o FILE] [-O PATH] [-i PATH] [-m MODULE] [-r] [-M FILE] [-P] [-D] [--exclude-values] [-q] Generate stubs for nanobind-based extensions. options: -h, --help show this help message and exit -o FILE, --output-file FILE write generated stubs to the specified file -O PATH, --output-dir PATH write generated stubs to the specified directory -i PATH, --import PATH add the directory to the Python import path (can specify multiple times) -m MODULE, --module MODULE generate a stub for the specified module (can specify multiple times) -r, --recursive recursively process submodules -M FILE, --marker-file FILE generate a marker file (usually named 'py.typed') -p FILE, --pattern-file FILE apply the given patterns to the generated stub (see the docs for syntax) -P, --include-private include private members (with single leading or trailing underscore) -D, --exclude-docstrings exclude docstrings from the generated stub --exclude-values force the use of ... for values -q, --quiet do not generate any output in the absence of failures ``` -------------------------------- ### Get Python Globals Dictionary Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Return the `globals()` dictionary. ```cpp dict globals() ``` -------------------------------- ### Initial Output of make_pet Function Source: https://nanobind.readthedocs.io/en/latest/classes.html Shows the initial behavior of the 'make_pet' function binding, where it incorrectly returns base 'Pet' class instances. ```python >>> my_ext.make_pet(my_ext.PetKind.Cat) >>> my_ext.make_pet(my_ext.PetKind.Dog) ``` -------------------------------- ### Get Python Builtins Dictionary Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Return the `__builtins__` dictionary. ```cpp dict builtins() ``` -------------------------------- ### Get Python Iterator Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Equivalent to `iter(h)` in Python. ```cpp iterator iter(handle h) ``` -------------------------------- ### Create an unnamed capsule with a cleanup routine Source: https://nanobind.readthedocs.io/en/latest/api_core.html This example shows how to construct an unnamed nanobind capsule that wraps a C/C++ pointer and specifies a cleanup function to be called when the capsule is garbage collected. ```cpp capsule(const void *ptr, void (*cleanup)(void*) noexcept = nullptr) ``` -------------------------------- ### Get Tuple Size Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Returns the number of elements in the tuple. ```cpp size_t size() const ``` -------------------------------- ### Get iterator item Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Returns the item at the current position of an iterator. ```cpp handle operator*() const; ``` -------------------------------- ### Low-Level CMake Interface for Nanobind Module Source: https://nanobind.readthedocs.io/en/latest/_sources/api_cmake.rst.txt Demonstrates the equivalent low-level CMake commands for building a nanobind module with various optimizations enabled. ```cmake nanobind_add_module(my_ext NB_SHARED LTO my_ext.cpp) ``` ```cmake nanobind_build_library(nanobind SHARED) ``` ```cmake add_library(my_ext MODULE my_ext.cpp) ``` ```cmake target_link_libraries(my_ext PRIVATE nanobind) ``` ```cmake nanobind_opt_size(my_ext) ``` ```cmake nanobind_lto(my_ext) ``` ```cmake nanobind_set_visibility(my_ext) ``` ```cmake nanobind_strip(my_ext) ``` ```cmake nanobind_disable_stack_protector(my_ext) ``` ```cmake nanobind_extension(my_ext) ``` ```cmake nanobind_compile_options(my_ext) ``` -------------------------------- ### Get Python None Object Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Return an object representing the value `None`. ```cpp object none() ``` -------------------------------- ### Get bytearray size Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Returns the size in bytes of a Python bytearray object. ```cpp size_t size() const; ``` -------------------------------- ### Pickling Support for Classes Source: https://nanobind.readthedocs.io/en/latest/_sources/classes.rst.txt Shows how to implement pickling support for a C++ class by exposing `__getstate__` and `__setstate__` methods. ```APIDOC ## Class: Pet (Pickling) ### Description Binds a C++ class `Pet` with pickling support. The `__getstate__` method serializes the object's state into a tuple, and `__setstate__` reconstructs the object from this tuple. ### Methods - **`__getstate__(self)`** - Description: Returns the state of the `Pet` object as a tuple `(name, age)` for pickling. - Returns: - `tuple`: A tuple containing the pet's name and age. - **`__setstate__(self, state: tuple)`** - Description: Reconstructs the `Pet` object from a pickled state tuple `(name, age)`. - Parameters: - **state** (tuple) - Required - A tuple containing the pet's name and age. ### Example Usage ```python import pickle pet = Pet("Buddy", 5) # Pickle the object pickled_pet = pickle.dumps(pet) # Unpickle the object unpickled_pet = pickle.loads(pickled_pet) print(unpickled_pet.name) # Output: Buddy print(unpickled_pet.age) # Output: 5 ``` ``` -------------------------------- ### Get Length of Set Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Equivalent to `len(d)` in Python. Optimized variant for sets. ```cpp size_t len(const set &d) ``` -------------------------------- ### Constructor Binding with `init` Source: https://nanobind.readthedocs.io/en/latest/api_core.html Helper class `init` to capture constructor signatures for binding. Supports custom constructors not present in C++. ```APIDOC template struct 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 `class_::def()`. Example: ```cpp bnb::class_(m, "MyType") .def(nb::init()); ``` This is syntax sugar for: ```cpp bnb::class_(m, "MyType") .def("__init__", [](MyType* t, const char* arg0, int arg1) { new (t) MyType(arg0, arg1); }); ``` ``` -------------------------------- ### Python Example of Expanding Args/Kwargs Source: https://nanobind.readthedocs.io/en/latest/_sources/functions.rst.txt Demonstrates how a Python function receiving *args and **kwargs would be called by the C++ my_call function. ```pycon >>> def x(*args, **kwargs): ... print(args) ... print(kwargs) ... >>> import my_ext >>> my_ext.my_call(x) (1, 'positional') {'keyword': 'value'} ``` -------------------------------- ### Get Length of Dictionary Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Equivalent to `len(d)` in Python. Optimized variant for dictionaries. ```cpp size_t len(const dict &d) ``` -------------------------------- ### Install nanobind as a Git submodule Source: https://nanobind.readthedocs.io/en/latest/installing.html Integrate nanobind directly into your project by adding it as a Git submodule. This method is suitable if you prefer not to use external package managers and your project uses Git. ```bash git submodule add https://github.com/wjakob/nanobind ext/nanobind ``` ```bash git submodule update --init --recursive ``` -------------------------------- ### Get Length of Tuple Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Equivalent to `len(t)` in Python. Optimized variant for tuples. ```cpp size_t len(const tuple &t) ``` -------------------------------- ### Python Function Definition Source: https://nanobind.readthedocs.io/en/latest/typing.html An example of a standard Python function with type hints and a docstring. ```python def square(x: int) -> int: '''Return the square of the input''' return x*x ``` -------------------------------- ### Constructor Binding (init) Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Explains how to bind C++ constructors to Python, including direct binding and manual workarounds for custom constructors. ```APIDOC ## Constructor Binding (`init`) ### Description This section explains how to bind C++ constructors to Python using the `nb::init` helper. It also covers manual workarounds for binding constructors not present in the C++ type. ### Struct `nb::init<...Args>` ### Usage - `nb::init()`: Binds a constructor taking a float argument. ### Manual Workaround Example For constructors not directly available in C++, a manual workaround using placement new can be employed: ```cpp nb::class_(m, "MyType") .def("__init__", [](MyType* t, const char* arg0, int arg1) { new (t) MyType(arg0, arg1); }); ``` ``` -------------------------------- ### Enabling Incremental Builds Source: https://nanobind.readthedocs.io/en/latest/_sources/packaging.rst.txt Installs the project without build isolation, allowing for faster rebuilds during development. This command should be run after changes to source files. ```bash pip install --no-build-isolation -ve . ``` -------------------------------- ### Get mapping values Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Returns a Python list containing all values from a mapping object. ```cpp list values() const; ``` -------------------------------- ### Get mapping keys Source: https://nanobind.readthedocs.io/en/latest/_sources/api_core.rst.txt Returns a Python list containing all keys from a mapping object. ```cpp list keys() const; ``` -------------------------------- ### Compile the extension using CMake Source: https://nanobind.readthedocs.io/en/latest/_sources/basics.rst.txt After CMake has configured the build, use this command to compile your nanobind extension. This command should be run from your project's root directory. ```bash cmake --build build ```