misc.rst 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. Miscellaneous
  2. #############
  3. .. _macro_notes:
  4. General notes regarding convenience macros
  5. ==========================================
  6. pybind11 provides a few convenience macros such as
  7. :func:`PYBIND11_MAKE_OPAQUE` and :func:`PYBIND11_DECLARE_HOLDER_TYPE`, and
  8. ``PYBIND11_OVERLOAD_*``. Since these are "just" macros that are evaluated
  9. in the preprocessor (which has no concept of types), they *will* get confused
  10. by commas in a template argument such as ``PYBIND11_OVERLOAD(MyReturnValue<T1,
  11. T2>, myFunc)``. In this case, the preprocessor assumes that the comma indicates
  12. the beginning of the next parameter. Use a ``typedef`` to bind the template to
  13. another name and use it in the macro to avoid this problem.
  14. .. _gil:
  15. Global Interpreter Lock (GIL)
  16. =============================
  17. When calling a C++ function from Python, the GIL is always held.
  18. The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
  19. used to acquire and release the global interpreter lock in the body of a C++
  20. function call. In this way, long-running C++ code can be parallelized using
  21. multiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
  22. could be realized as follows (important changes highlighted):
  23. .. code-block:: cpp
  24. :emphasize-lines: 8,9,31,32
  25. class PyAnimal : public Animal {
  26. public:
  27. /* Inherit the constructors */
  28. using Animal::Animal;
  29. /* Trampoline (need one for each virtual function) */
  30. std::string go(int n_times) {
  31. /* Acquire GIL before calling Python code */
  32. py::gil_scoped_acquire acquire;
  33. PYBIND11_OVERLOAD_PURE(
  34. std::string, /* Return type */
  35. Animal, /* Parent class */
  36. go, /* Name of function */
  37. n_times /* Argument(s) */
  38. );
  39. }
  40. };
  41. PYBIND11_MODULE(example, m) {
  42. py::class_<Animal, PyAnimal> animal(m, "Animal");
  43. animal
  44. .def(py::init<>())
  45. .def("go", &Animal::go);
  46. py::class_<Dog>(m, "Dog", animal)
  47. .def(py::init<>());
  48. m.def("call_go", [](Animal *animal) -> std::string {
  49. /* Release GIL before calling into (potentially long-running) C++ code */
  50. py::gil_scoped_release release;
  51. return call_go(animal);
  52. });
  53. }
  54. The ``call_go`` wrapper can also be simplified using the `call_guard` policy
  55. (see :ref:`call_policies`) which yields the same result:
  56. .. code-block:: cpp
  57. m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
  58. Binding sequence data types, iterators, the slicing protocol, etc.
  59. ==================================================================
  60. Please refer to the supplemental example for details.
  61. .. seealso::
  62. The file :file:`tests/test_sequences_and_iterators.cpp` contains a
  63. complete example that shows how to bind a sequence data type, including
  64. length queries (``__len__``), iterators (``__iter__``), the slicing
  65. protocol and other kinds of useful operations.
  66. Partitioning code over multiple extension modules
  67. =================================================
  68. It's straightforward to split binding code over multiple extension modules,
  69. while referencing types that are declared elsewhere. Everything "just" works
  70. without any special precautions. One exception to this rule occurs when
  71. extending a type declared in another extension module. Recall the basic example
  72. from Section :ref:`inheritance`.
  73. .. code-block:: cpp
  74. py::class_<Pet> pet(m, "Pet");
  75. pet.def(py::init<const std::string &>())
  76. .def_readwrite("name", &Pet::name);
  77. py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
  78. .def(py::init<const std::string &>())
  79. .def("bark", &Dog::bark);
  80. Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
  81. whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
  82. course that the variable ``pet`` is not available anymore though it is needed
  83. to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
  84. However, it can be acquired as follows:
  85. .. code-block:: cpp
  86. py::object pet = (py::object) py::module::import("basic").attr("Pet");
  87. py::class_<Dog>(m, "Dog", pet)
  88. .def(py::init<const std::string &>())
  89. .def("bark", &Dog::bark);
  90. Alternatively, you can specify the base class as a template parameter option to
  91. ``class_``, which performs an automated lookup of the corresponding Python
  92. type. Like the above code, however, this also requires invoking the ``import``
  93. function once to ensure that the pybind11 binding code of the module ``basic``
  94. has been executed:
  95. .. code-block:: cpp
  96. py::module::import("basic");
  97. py::class_<Dog, Pet>(m, "Dog")
  98. .def(py::init<const std::string &>())
  99. .def("bark", &Dog::bark);
  100. Naturally, both methods will fail when there are cyclic dependencies.
  101. Note that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
  102. via the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
  103. required proper pybind11 functionality, can interfere with the ability to
  104. access types defined in another extension module. Working around this requires
  105. manually exporting types that are accessed by multiple extension modules;
  106. pybind11 provides a macro to do just this:
  107. .. code-block:: cpp
  108. class PYBIND11_EXPORT Dog : public Animal {
  109. ...
  110. };
  111. Note also that it is possible (although would rarely be required) to share arbitrary
  112. C++ objects between extension modules at runtime. Internal library data is shared
  113. between modules using capsule machinery [#f6]_ which can be also utilized for
  114. storing, modifying and accessing user-defined data. Note that an extension module
  115. will "see" other extensions' data if and only if they were built with the same
  116. pybind11 version. Consider the following example:
  117. .. code-block:: cpp
  118. auto data = (MyData *) py::get_shared_data("mydata");
  119. if (!data)
  120. data = (MyData *) py::set_shared_data("mydata", new MyData(42));
  121. If the above snippet was used in several separately compiled extension modules,
  122. the first one to be imported would create a ``MyData`` instance and associate
  123. a ``"mydata"`` key with a pointer to it. Extensions that are imported later
  124. would be then able to access the data behind the same pointer.
  125. .. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
  126. Module Destructors
  127. ==================
  128. pybind11 does not provide an explicit mechanism to invoke cleanup code at
  129. module destruction time. In rare cases where such functionality is required, it
  130. is possible to emulate it using Python capsules or weak references with a
  131. destruction callback.
  132. .. code-block:: cpp
  133. auto cleanup_callback = []() {
  134. // perform cleanup here -- this function is called with the GIL held
  135. };
  136. m.add_object("_cleanup", py::capsule(cleanup_callback));
  137. This approach has the potential downside that instances of classes exposed
  138. within the module may still be alive when the cleanup callback is invoked
  139. (whether this is acceptable will generally depend on the application).
  140. Alternatively, the capsule may also be stashed within a type object, which
  141. ensures that it not called before all instances of that type have been
  142. collected:
  143. .. code-block:: cpp
  144. auto cleanup_callback = []() { /* ... */ };
  145. m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
  146. Both approaches also expose a potentially dangerous ``_cleanup`` attribute in
  147. Python, which may be undesirable from an API standpoint (a premature explicit
  148. call from Python might lead to undefined behavior). Yet another approach that
  149. avoids this issue involves weak reference with a cleanup callback:
  150. .. code-block:: cpp
  151. // Register a callback function that is invoked when the BaseClass object is colelcted
  152. py::cpp_function cleanup_callback(
  153. [](py::handle weakref) {
  154. // perform cleanup here -- this function is called with the GIL held
  155. weakref.dec_ref(); // release weak reference
  156. }
  157. );
  158. // Create a weak reference with a cleanup callback and initially leak it
  159. (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
  160. Generating documentation using Sphinx
  161. =====================================
  162. Sphinx [#f4]_ has the ability to inspect the signatures and documentation
  163. strings in pybind11-based extension modules to automatically generate beautiful
  164. documentation in a variety formats. The python_example repository [#f5]_ contains a
  165. simple example repository which uses this approach.
  166. There are two potential gotchas when using this approach: first, make sure that
  167. the resulting strings do not contain any :kbd:`TAB` characters, which break the
  168. docstring parsing routines. You may want to use C++11 raw string literals,
  169. which are convenient for multi-line comments. Conveniently, any excess
  170. indentation will be automatically be removed by Sphinx. However, for this to
  171. work, it is important that all lines are indented consistently, i.e.:
  172. .. code-block:: cpp
  173. // ok
  174. m.def("foo", &foo, R"mydelimiter(
  175. The foo function
  176. Parameters
  177. ----------
  178. )mydelimiter");
  179. // *not ok*
  180. m.def("foo", &foo, R"mydelimiter(The foo function
  181. Parameters
  182. ----------
  183. )mydelimiter");
  184. By default, pybind11 automatically generates and prepends a signature to the docstring of a function
  185. registered with ``module::def()`` and ``class_::def()``. Sometimes this
  186. behavior is not desirable, because you want to provide your own signature or remove
  187. the docstring completely to exclude the function from the Sphinx documentation.
  188. The class ``options`` allows you to selectively suppress auto-generated signatures:
  189. .. code-block:: cpp
  190. PYBIND11_MODULE(example, m) {
  191. py::options options;
  192. options.disable_function_signatures();
  193. m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
  194. }
  195. Note that changes to the settings affect only function bindings created during the
  196. lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
  197. the default settings are restored to prevent unwanted side effects.
  198. .. [#f4] http://www.sphinx-doc.org
  199. .. [#f5] http://github.com/pybind/python_example