With pybind11, how to split my code into multiple modules/files? This would speed up the compilation step. Pybind11 documentation addresses the special case of extending a type declared in a different extension module, here. But not the more general/simpler one.
Bookmark this question. Show activity on this post. I have a set of modules that I've written in C++ and exported to Python using pybind11. All of these modules should be able to be used independently, but they use a common set of custom types that are defined in a utility library.
It’s good practice to split binding code over multiple files, as in the following example: void init_ex1(py::module_ &); void init_ex2(py::module_ &); /* ... */ PYBIND11_MODULE(example, m) { init_ex1(m); init_ex2(m); /* ... */ }
To do its job, pybind11 extensively relies on a programming technique known as template metaprogramming, which is a way of performing computation at compile time using type information.
Using multiple files to create sub-modules helps keep the code organized and makes reusing code between projects/functions much easier. Functions and variables defined within a module importable into other modules and allows you to scope your function and variable names without worrying about conflicts. From the Python docs:
As per pybind11 FAQ, here, PYBIND11_MODULE(module_name, m){ /* bindings */ }
can be split in multiple functions defined in different files. Example:
example.cpp:
void init_ex1(py::module &);
void init_ex2(py::module &);
/* ... */
PYBIND11_MODULE(example, m) {
init_ex1(m);
init_ex2(m);
/* ... */
}
ex1.cpp:
void init_ex1(py::module &m) {
m.def("add", [](int a, int b) { return a + b; });
}
ex2.cpp:
void init_ex2(py::module &m) {
m.def("sub", [](int a, int b) { return a - b; });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With