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