misc.rst 12 KB

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