11

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.

gmagno
  • 1,770
  • 1
  • 19
  • 40

1 Answers1

20

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; });
}
gmagno
  • 1,770
  • 1
  • 19
  • 40
  • 15
    What about the `PYBIND11_MODULE` statement? Can you have multiple `PYBIND11_MODULE` that append to the current module? – Mikhail Dec 04 '20 at 19:16
  • @Mikhail no, there should only be one, you can share the module object. As any lib that you compile. – Ivan Feb 08 '23 at 16:04