### Enable C++ standard auto-detection for pybind11 extensions Source: https://pybind11.readthedocs.io/en/stable/compiling This `setup.py` example illustrates how to enable automatic detection of the highest supported C++ standard for `Pybind11Extensions`. It achieves this by importing `build_ext` from `pybind11.setup_helpers` and registering it as a command class override for "build_ext" in the `setup()` function. ```python from glob import glob from setuptools import setup from pybind11.setup_helpers import Pybind11Extension, build_ext ext_modules = [ Pybind11Extension( "python_example", sorted(glob("src/*.cpp")), ), ] setup(..., cmdclass={"build_ext": build_ext}, ext_modules=ext_modules) ``` -------------------------------- ### Install pybind11 System-Wide Using CMake Build Commands Source: https://pybind11.readthedocs.io/en/stable/compiling Shows both classic and modern CMake workflows for building and installing pybind11 from source. The classic method uses separate mkdir/cd commands, while CMake 3.15+ uses out-of-tree build commands with -S/-B flags and parallel building support. Both methods result in system-wide pybind11 installation for use with find_package. ```bash # Classic CMake cd pybind11 mkdir build cd build cmake .. make install # CMake 3.15+ cd pybind11 cmake -S . -B build cmake --build build -j 2 # Build on 2 cores cmake --install build ``` -------------------------------- ### Compile pybind11 Tests on Linux/macOS with CMake Source: https://pybind11.readthedocs.io/en/stable/basics This sequence of shell commands outlines the process to set up a build directory, configure the pybind11 project using CMake, and then compile and run its test suite on Linux or macOS. Prerequisites include installing `python-dev` (or `python3-dev`) and `cmake`. ```shell mkdir build cd build cmake .. make check -j 4 ``` -------------------------------- ### Build Python Extension Module with Meson and pybind11 Source: https://pybind11.readthedocs.io/en/stable/compiling A meson.build configuration file for creating a Python extension module using pybind11 and meson-python. This setup imports Python installation, declares pybind11 as a dependency, and configures the extension module with C++11 standard. It provides an alternative to CMake-based builds. ```meson project( 'example', 'cpp', version: '0.1.0', default_options: [ 'cpp_std=c++11', ], ) py = import('python').find_installation(pure: false) pybind11_dep = dependency('pybind11') py.extension_module('example', 'example.cpp', install: true, dependencies : [pybind11_dep], ) ``` -------------------------------- ### Bind C++ Function to Python Module using PYBIND11_MODULE Macro Source: https://pybind11.readthedocs.io/en/stable/basics Complete example showing how to use the PYBIND11_MODULE macro to create Python bindings for a C++ function. The macro creates a module named 'example' and uses module_::def() to expose the add function. This header-only approach requires no special linking or intermediate translation steps. ```cpp #include int add(int i, int j) { return i + j; } PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { m.doc() = "pybind11 example plugin"; // optional module docstring m.def("add", &add, "A function that adds two numbers"); } ``` -------------------------------- ### Create pybind11 Module Using find_package in CMake Source: https://pybind11.readthedocs.io/en/stable/compiling Minimal CMake configuration for building a pybind11 extension module using an externally installed pybind11 package. Requires CMake 3.15 or higher, locates pybind11 via find_package, and creates a Python module from example.cpp. This approach assumes pybind11 is already installed on the system. ```cmake cmake_minimum_required(VERSION 3.15...4.0) project(example LANGUAGES CXX) find_package(pybind11 REQUIRED) pybind11_add_module(example example.cpp) ``` -------------------------------- ### Register Custom C++ Constructors with pybind11 Source: https://pybind11.readthedocs.io/en/stable/changelog This C++ code demonstrates how to bind both existing and custom constructors for a C++ class `Example` to Python using pybind11. It utilizes `py::init()` for a standard constructor and `py::init()` with a lambda expression to define a custom constructor that takes an integer and creates an `Example` object, returning a `std::unique_ptr`. ```cpp struct Example { Example(std::string); }; py::class_(m, "Example") .def(py::init()) // existing constructor .def(py::init([](int n) { // custom constructor return std::make_unique(std::to_string(n)); })); ``` -------------------------------- ### Python Usage of pybind11 Split Module Source: https://pybind11.readthedocs.io/en/stable/faq Demonstrates how to import and use the `example` module created with pybind11 from Python. It shows calls to the `add` and `sub` functions, verifying the successful binding and functionality of the C++ code structured across multiple files. ```python >>> import example >>> example.add(1, 2) 3 >>> example.sub(1, 1) 0 ``` -------------------------------- ### Bind C++ static factory method as Python constructor with pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/classes This example demonstrates how to expose a private C++ constructor via a static factory function (`create`) and bind this factory as a constructor in Python. The `py::init(&Example::create)` call tells pybind11 to use the `create` method to construct new `Example` objects from Python. ```cpp class Example { private: Example(int); // private constructor public: // Factory function: static Example create(int a) { return Example(a); } }; py::class_(m, "Example") .def(py::init(&Example::create)); ``` -------------------------------- ### Call Python Class Constructor via pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object This C++ example shows how to instantiate a Python object (e.g., `Decimal`) by calling its constructor through a `py::object` that represents the class itself, passing necessary arguments. ```C++ // Construct a Python object of class Decimal py::object pi = Decimal("3.14159"); ``` -------------------------------- ### Instantiate pybind11 Tuple Source: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object This example shows how to create a Python tuple (`py::tuple`) in C++ using `py::make_tuple()`, converting various C++ values to supported Python types within the tuple. ```C++ py::tuple tup = py::make_tuple(42, py::none(), "spam"); ``` -------------------------------- ### Create Python Extension Module with CMake and pybind11 Source: https://pybind11.readthedocs.io/en/stable/compiling A minimal CMakeLists.txt configuration for building a Python extension module using pybind11. This setup uses find_package to locate pybind11 and pybind11_add_module to configure the extension module. The configuration handles all platform-specific details automatically. ```cmake cmake_minimum_required(VERSION 3.15...4.0) project(example LANGUAGES CXX) set(PYBIND11_FINDPYTHON ON) find_package(pybind11 CONFIG REQUIRED) pybind11_add_module(example example.cpp) install(TARGETS example DESTINATION .) ``` -------------------------------- ### Create Basic C++ Function for Python Binding with pybind11 Source: https://pybind11.readthedocs.io/en/stable/basics A simple C++ function that adds two integers and returns their sum. This serves as the foundation example for demonstrating pybind11 binding capabilities. The function is intentionally simple to focus on the binding mechanism rather than complex logic. ```cpp int add(int i, int j) { return i + j; } ``` -------------------------------- ### Bind C++ Function with Default Arguments using Shorthand (pybind11) Source: https://pybind11.readthedocs.io/en/stable/basics This example illustrates two ways to bind a C++ function with default arguments in pybind11. It shows the regular `py::arg` notation and a more concise shorthand `"_a"` for specifying argument names and default values. ```cpp // regular notation m.def("add1", &add, py::arg("i") = 1, py::arg("j") = 2); ``` ```cpp // shorthand m.def("add2", &add, "i"_a=1, "j"_a=2); ``` -------------------------------- ### Bind C++ Class and Methods with pybind11 Source: https://pybind11.readthedocs.io/en/stable/benchmark This example demonstrates how to define a C++ class with several methods and then expose this class and its methods to Python using the pybind11 library. It uses `PYBIND11_MODULE` to define the Python module and `py::class_` to create the Python-facing class, mapping C++ methods using `.def()`. ```cpp ... class cl034 { public: cl279 *fn_000(cl084 *, cl057 *, cl065 *, cl042 *); cl025 *fn_001(cl098 *, cl262 *, cl414 *, cl121 *); cl085 *fn_002(cl445 *, cl297 *, cl145 *, cl421 *); cl470 *fn_003(cl200 *, cl323 *, cl332 *, cl492 *); }; ... PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { ... py::class_(m, "cl034") .def("fn_000", &cl034::fn_000) .def("fn_001", &cl034::fn_001) .def("fn_002", &cl034::fn_002) .def("fn_003", &cl034::fn_003) ... } ``` -------------------------------- ### Find pybind11 Package with Version Info using CMake Source: https://pybind11.readthedocs.io/en/stable/cmake/index This snippet demonstrates how to use `find_package` to locate the pybind11 configuration. It shows examples of finding the package generally and finding a specific, exact version, which is recommended for production builds to ensure compatibility and stability. ```cmake find_package(pybind11 CONFIG) find_package(pybind11 2.9 EXACT CONFIG REQUIRED) ``` -------------------------------- ### Demonstrate Correct Binding Syntax Against Actual Class Source: https://pybind11.readthedocs.io/en/stable/advanced/classes Illustrates the proper way to define bindings using the actual class (Animal) rather than the trampoline class (PyAnimal) for method definitions. This example emphasizes that &Animal::go should be used instead of &PyAnimal::go when binding methods. ```cpp py::class_(m, "Animal"); .def(py::init<>()) .def("go", &Animal::go); /* <--- DO NOT USE &PyAnimal::go HERE */ ``` -------------------------------- ### View pybind11 Function Documentation with help() in Python Source: https://pybind11.readthedocs.io/en/stable/basics Demonstrates the auto-generated documentation for pybind11-bound functions when using named arguments. The help system shows function signatures with parameter types and names, along with docstrings. This automatic documentation generation is a key benefit of pybind11's metadata approach. ```python >>> help(example) .... FUNCTIONS add(...) Signature : (i: int, j: int) -> int A function which adds two numbers ``` -------------------------------- ### Interactive Python Session for Basic Pet Usage Source: https://pybind11.readthedocs.io/en/stable/classes This interactive Python session illustrates how to use the `example.Pet` class after it has been bound using pybind11. It shows the creation of a Pet object, its default string representation, and the invocation of its `getName` and `setName` methods, demonstrating basic interaction between Python and the C++ object. ```python % python >>> import example >>> p = example.Pet("Molly") >>> print(p) >>> p.getName() 'Molly' >>> p.setName("Charly") >>> p.getName() 'Charly' ``` -------------------------------- ### Compile pybind11 Tests on Windows with CMake and Visual Studio Source: https://pybind11.readthedocs.io/en/stable/basics This set of commands describes how to prepare a build environment, configure pybind11 with CMake for Visual Studio 2017 or newer, and then build and execute the 'check' target. It highlights the importance of the `/permissive-` flag for C++17 conformance and matching processor architectures (e.g., `x64`). ```shell mkdir build cd build cmake .. cmake --build . --config Release --target check ``` -------------------------------- ### Specialize type_caster and visit_helper for boost::variant with pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/cast/stl This C++ code illustrates how to enable automatic conversion for `boost::variant` types with pybind11. It involves specializing `pybind11::detail::type_caster` for `boost::variant` and `pybind11::detail::visit_helper` to define how to visit the variant (using `boost::apply_visitor` in this example). This setup allows pybind11 to convert `boost::variant` to Python objects, but users must be aware that the order of types within the variant is crucial for correct conversion due to pybind11's overload resolution rules. ```cpp // `boost::variant` as an example -- can be any `std::variant`-like container namespace PYBIND11_NAMESPACE { namespace detail { template struct type_caster> : variant_caster> {}; // Specifies the function used to visit the variant -- `apply_visitor` instead of `visit` template <> struct visit_helper { template static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) { return boost::apply_visitor(args...); } }; }} // namespace PYBIND11_NAMESPACE::detail ``` -------------------------------- ### Configure pybind11 extension in setup.py with setuptools Source: https://pybind11.readthedocs.io/en/stable/compiling This Python code demonstrates how to define a C++ extension module using `pybind11.setup_helpers.Pybind11Extension` within a `setup.py` file. It uses `glob` to find source files and sorts them for consistent builds, then passes the `Pybind11Extension` object to `setuptools.setup`. ```python from glob import glob from setuptools import setup from pybind11.setup_helpers import Pybind11Extension ext_modules = [ Pybind11Extension( "python_example", sorted(glob("src/*.cpp")), # Sort source files for reproducibility ), ] setup(..., ext_modules=ext_modules) ``` -------------------------------- ### pybind11 Module Entry Point with Delegated Initialization Source: https://pybind11.readthedocs.io/en/stable/faq Illustrates how to structure a pybind11 module by delegating initialization to separate functions (`init_ex1`, `init_ex2`). This approach, defined within `PYBIND11_MODULE`, helps reduce build times and memory requirements by allowing independent compilation of binding code segments. ```cpp void init_ex1(py::module_ &); void init_ex2(py::module_ &); /* ... */ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) { init_ex1(m); init_ex2(m); /* ... */ } ``` -------------------------------- ### Create and Activate Pybind11 Sub-interpreters in C++ Source: https://pybind11.readthedocs.io/en/stable/advanced/embedding This C++ example demonstrates how to create, activate, and deactivate Python sub-interpreters using pybind11. It shows how a pybind11-embedded module can report the currently active interpreter ID and handles `error_already_set` exceptions during interpreter activation. The example highlights the scope-based activation (`subinterpreter_scoped_activate`) and interaction between the main and sub-interpreters, including GIL management. ```cpp #include #include #include namespace py = pybind11; PYBIND11_EMBEDDED_MODULE(printer, m, py::multiple_interpreters::per_interpreter_gil()) { m.def("which", [](const std::string& when) { std::cout << when << "; Current Interpreter is " << py::subinterpreter::current().id() << std::endl; }); } int main() { py::scoped_interpreter main_interp; py::module_::import("printer").attr("which")("First init"); { py::subinterpreter sub = py::subinterpreter::create(); py::module_::import("printer").attr("which")("Created sub"); { py::subinterpreter_scoped_activate guard(sub); try { py::module_::import("printer").attr("which")("Activated sub"); } catch (py::error_already_set &e) { std::cerr << "EXCEPTION " << e.what() << std::endl; return 1; } } py::module_::import("printer").attr("which")("Deactivated sub"); { py::gil_scoped_release nogil; { py::subinterpreter_scoped_activate guard(sub); try { { py::subinterpreter_scoped_activate main_guard(py::subinterpreter::main()); try { py::module_::import("printer").attr("which")("Main within sub"); } catch (py::error_already_set &e) { std::cerr << "EXCEPTION " << e.what() << std::endl; return 1; } } py::module_::import("printer").attr("which")("After Main, still within sub"); } catch (py::error_already_set &e) { std::cerr << "EXCEPTION " << e.what() << std::endl; return 1; } } } } py::module_::import("printer").attr("which")("At end"); return 0; } ``` -------------------------------- ### Slice Multi-dimensional Arrays with Ellipsis (Python, C++ Pybind11) Source: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy These snippets illustrate how to slice multi-dimensional arrays using the ellipsis notation. The Python example uses `...` for NumPy arrays, while the C++ example leverages Pybind11's `py::ellipsis()` within `py::make_tuple` to achieve similar flexible slicing, extracting sub-arrays by fixing specific dimensions. ```Python a = ... # a NumPy array b = a[0, ..., 0] ``` ```C++ py::array a = /* A NumPy array */; py::array b = a[py::make_tuple(0, py::ellipsis(), 0)]; ``` -------------------------------- ### Define a Basic pybind11 Module with a Function Source: https://pybind11.readthedocs.io/en/stable/reference This snippet demonstrates how to define a basic pybind11 module using `PYBIND11_MODULE`. It sets the module's documentation string and binds a simple C++ lambda function named "foo" that returns "Hello, World!" to be accessible from Python. This macro serves as the entry point for a pybind11 extension. ```cpp PYBIND11_MODULE(example, m) { m.doc() = "pybind11 example module"; // Add bindings here m.def("foo", []() { return "Hello, World!"; }); } ``` -------------------------------- ### Define pybind11 build system requirements using pyproject.toml Source: https://pybind11.readthedocs.io/en/stable/compiling This `pyproject.toml` configuration specifies the necessary build dependencies for a `pybind11` project, namely `setuptools` and `pybind11`. When present, Pip creates an isolated environment, installs these packages from the `requires` list, and then builds the project's wheel. This ensures a consistent build environment and handles `pybind11`'s availability during compilation. ```toml [build-system] requires = ["setuptools", "pybind11"] build-backend = "setuptools.build_meta" ``` -------------------------------- ### Chain exceptions using 'raise from' in Python Source: https://pybind11.readthedocs.io/en/stable/advanced/exceptions Illustrates Python's exception chaining mechanism using 'raise from' syntax. This example shows how to indicate that one exception was caused by another, preserving the exception context for debugging purposes. ```python try: print(1 / 0) except Exception as exc: raise RuntimeError("could not divide by zero") from exc ``` -------------------------------- ### Import and Execute pybind11-Compiled Python Module Source: https://pybind11.readthedocs.io/en/stable/basics Interactive Python session demonstrating how to import and use a compiled pybind11 module. Shows the module can be imported like any Python module and functions can be called with standard Python syntax. The binary module must be in the current directory or Python path. ```python $ python Python 3.9.10 (main, Jan 15 2022, 11:48:04) [Clang 13.0.0 (clang-1300.0.29.3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import example >>> example.add(1, 2) 3 >>> ``` -------------------------------- ### Configure pyproject.toml for Meson Build with meson-python Source: https://pybind11.readthedocs.io/en/stable/compiling A pyproject.toml configuration for building pybind11 extensions using meson-python as the build backend. This minimal configuration specifies build dependencies and requires the project to be in a git or mercurial repository for SDist creation. Additional project metadata should be added for PyPI uploads. ```toml [build-system] requires = ["meson-python", "pybind11"] build-backend = "mesonpy" ``` -------------------------------- ### Call Bound Python Method via pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object This example illustrates how to call a bound method of a Python object from C++ using `pybind11`, accessing the method via `.attr("method_name")` and then invoking it with `()`. ```C++ // Calculate e^π in decimal py::object exp_pi = pi.attr("exp")(); py::print(py::str(exp_pi)); ``` -------------------------------- ### Add Keyword Arguments to pybind11 Function Binding using py::arg Source: https://pybind11.readthedocs.io/en/stable/basics Demonstrates how to add named parameter metadata to Python bindings using py::arg(). This enables keyword argument calling in Python and improves documentation by making parameter names visible in function signatures. Makes functions more readable and self-documenting. ```cpp m.def("add", &add, "A function which adds two numbers", py::arg("i"), py::arg("j")); ``` -------------------------------- ### Import Python SciPy Module and Get Version with pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object This snippet illustrates how to import the `scipy` module from Python into C++ using `pybind11::module_::import()` and then retrieve one of its attributes, specifically the `__version__` string. ```C++ // Try to import scipy py::object scipy = py::module_::import("scipy"); return scipy.attr("__version__"); ``` -------------------------------- ### Inspect pybind11 Function Documentation with Default Arguments (Python) Source: https://pybind11.readthedocs.io/en/stable/basics This Python snippet shows how the default arguments defined in the pybind11 binding are reflected in the function's documentation when inspected using Python's built-in `help()` function. It confirms that the defaults are correctly exposed. ```python >>> help(example) .... FUNCTIONS add(...) Signature : (i: int = 1, j: int = 2) -> int A function which adds two numbers ``` -------------------------------- ### Define C++ struct with overloaded methods Source: https://pybind11.readthedocs.io/en/stable/classes This C++ struct `Pet` demonstrates method overloading with two `set` methods: one taking an `int` for age and another taking a `std::string` for name. It serves as the base for pybind11 binding examples. ```cpp struct Pet { Pet(const std::string &name, int age) : name(name), age(age) { } void set(int age_) { age = age_; } void set(const std::string &name_) { name = name_; } std::string name; int age; }; ``` -------------------------------- ### Compile pybind11 C++ Extension Module for Python on Linux Source: https://pybind11.readthedocs.io/en/stable/basics Command-line compilation of a pybind11 C++ extension using g++ with necessary flags including C++11 standard, shared library generation, and position-independent code. Uses python3 to automatically detect include paths and extension suffix for proper module loading. Alternative includes path provided for submodule installations. ```bash $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3 -m pybind11 --extension-suffix) ``` -------------------------------- ### Include pybind11 Header and Namespace Alias in C++ Source: https://pybind11.readthedocs.io/en/stable/basics This C++ snippet demonstrates the standard practice of including the main pybind11 header and defining a convenient namespace alias. It's crucial to include `pybind11/pybind11.h` as the first file due to its dependency on `Python.h`. ```cpp #include namespace py = pybind11; ``` -------------------------------- ### C++ Reference Argument Examples Source: https://pybind11.readthedocs.io/en/stable/faq Illustrates basic C++ functions `increment` and `increment_ptr` that modify integer arguments passed by reference or pointer. This highlights a common C++ pattern for in-place modification, which behaves differently in Python. ```cpp void increment(int &i) { i++; } void increment_ptr(int *i) { (*i)++; } ``` -------------------------------- ### Catching Python Exceptions as `pybind11::error_already_set` in C++ Source: https://pybind11.readthedocs.io/en/stable/advanced/exceptions This C++ example demonstrates how to catch Python exceptions that propagate into C++ as `pybind11::error_already_set`. It attempts to open a non-existent file, catches the resulting `FileNotFoundError` or `PermissionError` using `e.matches()`, and prints a descriptive message. Other exceptions are re-thrown. ```C++ try { // open("missing.txt", "r") auto file = py::module_::import("io").attr("open")("missing.txt", "r"); auto text = file.attr("read")(); file.attr("close")(); } catch (py::error_already_set &e) { if (e.matches(PyExc_FileNotFoundError)) { py::print("missing.txt not found"); } else if (e.matches(PyExc_PermissionError)) { py::print("missing.txt found but not accessible"); } else { throw; } } ``` -------------------------------- ### Get Error Message from pybind11 error_already_set in C++ Source: https://pybind11.readthedocs.io/en/stable/reference Implements the `std::exception::what()` method for `error_already_set`, providing a string description of the captured Python error. The result is built on demand and requires acquiring the Python GIL, which can cause issues during interpreter finalization. ```cpp inline const char *what() const noexcept override ``` -------------------------------- ### Call pybind11 Function with Keyword Arguments in Python Source: https://pybind11.readthedocs.io/en/stable/basics Shows how Python code can call pybind11-bound functions using keyword arguments when parameters are named using py::arg(). This provides a more readable alternative for functions with many parameters and matches standard Python conventions. ```python >>> import example >>> example.add(i=1, j=2) 3L ``` -------------------------------- ### Define pybind11 Module Entry Points (New vs. Deprecated Syntax) Source: https://pybind11.readthedocs.io/en/stable/changelog This C++ snippet compares the new `PYBIND11_MODULE` macro with the deprecated `PYBIND11_PLUGIN` macro for defining pybind11 module entry points. `PYBIND11_MODULE` simplifies module creation, making it the preferred method, while `PYBIND11_PLUGIN` is shown for context, explicitly creating and returning a `py::module` pointer. ```cpp // new PYBIND11_MODULE(example, m) { m.def("add", [](int a, int b) { return a + b; }); } // old PYBIND11_PLUGIN(example) { py::module m("example"); m.def("add", [](int a, int b) { return a + b; }); return m.ptr(); } ``` -------------------------------- ### Non-Polymorphic Type Python Behavior Without Downcasting Source: https://pybind11.readthedocs.io/en/stable/classes Python example showing that non-polymorphic types do not support automatic downcasting. Even though the underlying instance is a Dog, Python treats it as a Pet and cannot access Dog-specific methods like bark, resulting in an AttributeError. ```python >>> p = example.pet_store() >>> type(p) # `Dog` instance behind `Pet` pointer Pet # no pointer downcasting for regular non-polymorphic types >>> p.bark() AttributeError: 'Pet' object has no attribute 'bark' ``` -------------------------------- ### Define Positional-Only Arguments with pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/functions This C++ example shows how to use `py::pos_only()` in pybind11 to make arguments positional-only, meaning they cannot be passed by keyword from Python. This mirrors Python 3.8's `/` syntax and is useful for functions where argument order is semantically significant. ```cpp m.def("f", [](int a, int b) { /* ... */ }, py::arg("a"), py::pos_only(), py::arg("b")); ``` -------------------------------- ### Configure pyproject.toml for CMake Build with scikit-build-core Source: https://pybind11.readthedocs.io/en/stable/compiling A pyproject.toml configuration for building pybind11 extensions using scikit-build-core as the build backend. This replaces traditional setuptools files and integrates with modern Python packaging tools like pip, build, cibuildwheel, and uv. The configuration specifies build dependencies and basic project metadata. ```toml [build-system] requires = ["scikit-build-core", "pybind11"] build-backend = "scikit_build_core.build" [project] name = "example" version = "0.1.0" ``` -------------------------------- ### Pybind11 Deprecation Warning for Old-Style Constructors Source: https://pybind11.readthedocs.io/en/stable/upgrade This snippet shows an example of the runtime warning issued by pybind11 when an old-style placement-new `__init__` method is detected during module initialization. These warnings are typically only visible when pybind11 is compiled in debug mode, indicating the need to update to the newer `py::init()` API. ```console pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__' which has been deprecated. See the upgrade guide in pybind11's docs. ``` -------------------------------- ### Example Python Script for Embedded Module Interaction Source: https://pybind11.readthedocs.io/en/stable/advanced/embedding A sample Python script (`py_module.py`) illustrating how an embedded C++ module, once defined and loaded into the Python interpreter, can be imported and its attributes accessed just like any other Python module. This script expects a `cpp_module` with an attribute 'a' to be available. ```python """py_module.py located in the working directory""" import cpp_module a = cpp_module.a b = a + 1 ``` -------------------------------- ### Cast pybind11 Python Object to C++ Object Source: https://pybind11.readthedocs.io/en/stable/advanced/pycpp/object This example demonstrates the reverse conversion, casting a pybind11 Python object (`py::object`) back to a C++ object pointer (`MyClass *`) using the `.cast()` method. Conversion failure throws `cast_error`. ```C++ py::object obj = ...; MyClass *cls = obj.cast(); ``` -------------------------------- ### Compile pybind11 Extension Module on Linux - Manual Build with C++ Source: https://pybind11.readthedocs.io/en/stable/compiling Compiles a pybind11 C++ extension module on Linux using g++/c++ compiler. The command uses Python 3 to fetch pybind11 include paths and generates a shared library with the appropriate extension suffix. Requires pybind11 to be installed via pip or conda, or manually specified include paths. ```bash $ c++ -O3 -Wall -shared -std=c++11 -fPIC $(python3 -m pybind11 --includes) example.cpp -o example$(python3-config --extension-suffix) ``` -------------------------------- ### Bind overloaded C++ methods using C++11 workaround for overload_cast Source: https://pybind11.readthedocs.io/en/stable/classes For C++11 compilers, this pybind11 example provides a workaround to achieve similar syntax to `py::overload_cast`. It defines a custom `overload_cast_` template alias which uses `pybind11::detail::overload_cast_impl` for binding overloaded methods. ```cpp template using overload_cast_ = pybind11::detail::overload_cast_impl; py::class_(m, "Pet") .def("set", overload_cast_()(&Pet::set), "Set the pet's age") .def("set", overload_cast_()(&Pet::set), "Set the pet's name"); ``` -------------------------------- ### Call Python Module Function from C++ with pybind11 Source: https://pybind11.readthedocs.io/en/stable/advanced/embedding This C++ example illustrates importing a custom Python module (`calc`), accessing its `add` function as an attribute, calling it with C++ arguments, and casting the Python return value (`py::object`) back to a C++ integer. ```cpp py::module_ calc = py::module_::import("calc"); py::object result = calc.attr("add")(1, 2); int n = result.cast(); assert(n == 3); ``` -------------------------------- ### Build Pybind11 C++ Extension Module with CMake Source: https://pybind11.readthedocs.io/en/stable/compiling This CMake example demonstrates how to build a C++ extension module using pybind11's advanced interface library targets. It configures the project, links against `pybind11::module`, `pybind11::lto`, and `pybind11::windows_extras` for specific build optimizations. The `pybind11_extension` helper ensures proper module naming, and `pybind11_strip` is used conditionally for binary size reduction. ```cmake cmake_minimum_required(VERSION 3.15...4.0) project(example LANGUAGES CXX) find_package(pybind11 REQUIRED) # or add_subdirectory(pybind11) add_library(example MODULE main.cpp) target_link_libraries(example PRIVATE pybind11::module pybind11::lto pybind11::windows_extras) pybind11_extension(example) if(NOT MSVC AND NOT ${CMAKE_BUILD_TYPE} MATCHES Debug|RelWithDebInfo) # Strip unnecessary sections of the binary on Linux/macOS pybind11_strip(example) endif() set_target_properties(example PROPERTIES CXX_VISIBILITY_PRESET "hidden" CUDA_VISIBILITY_PRESET "hidden") ``` -------------------------------- ### Import ParallelCompile for pybind11 with setuptools Source: https://pybind11.readthedocs.io/en/stable/compiling This Python import statement shows how to bring `ParallelCompile` into scope from `pybind11.setup_helpers`. `ParallelCompile` provides a lightweight, NumPy-independent replacement for parallel compilation tools within `distutils`, which can be beneficial when building pybind11 extensions. ```python from pybind11.setup_helpers import ParallelCompile ```