Back to home page

EIC code displayed by LXR

 
 

    


Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/misc.rst is written in an unsupported language. File is not indexed.

0001 Miscellaneous
0002 #############
0003 
0004 .. _macro_notes:
0005 
0006 General notes regarding convenience macros
0007 ==========================================
0008 
0009 pybind11 provides a few convenience macros such as
0010 :func:`PYBIND11_DECLARE_HOLDER_TYPE` and ``PYBIND11_OVERRIDE_*``. Since these
0011 are "just" macros that are evaluated in the preprocessor (which has no concept
0012 of types), they *will* get confused by commas in a template argument; for
0013 example, consider:
0014 
0015 .. code-block:: cpp
0016 
0017     PYBIND11_OVERRIDE(MyReturnType<T1, T2>, Class<T3, T4>, func)
0018 
0019 The limitation of the C preprocessor interprets this as five arguments (with new
0020 arguments beginning after each comma) rather than three.  To get around this,
0021 there are two alternatives: you can use a type alias, or you can wrap the type
0022 using the ``PYBIND11_TYPE`` macro:
0023 
0024 .. code-block:: cpp
0025 
0026     // Version 1: using a type alias
0027     using ReturnType = MyReturnType<T1, T2>;
0028     using ClassType = Class<T3, T4>;
0029     PYBIND11_OVERRIDE(ReturnType, ClassType, func);
0030 
0031     // Version 2: using the PYBIND11_TYPE macro:
0032     PYBIND11_OVERRIDE(PYBIND11_TYPE(MyReturnType<T1, T2>),
0033                       PYBIND11_TYPE(Class<T3, T4>), func)
0034 
0035 The ``PYBIND11_MAKE_OPAQUE`` macro does *not* require the above workarounds.
0036 
0037 .. _gil:
0038 
0039 Global Interpreter Lock (GIL)
0040 =============================
0041 
0042 The Python C API dictates that the Global Interpreter Lock (GIL) must always
0043 be held by the current thread to safely access Python objects. As a result,
0044 when Python calls into C++ via pybind11 the GIL must be held, and pybind11
0045 will never implicitly release the GIL.
0046 
0047 .. code-block:: cpp
0048 
0049     void my_function() {
0050         /* GIL is held when this function is called from Python */
0051     }
0052 
0053     PYBIND11_MODULE(example, m) {
0054         m.def("my_function", &my_function);
0055     }
0056 
0057 pybind11 will ensure that the GIL is held when it knows that it is calling
0058 Python code. For example, if a Python callback is passed to C++ code via
0059 ``std::function``, when C++ code calls the function the built-in wrapper
0060 will acquire the GIL before calling the Python callback. Similarly, the
0061 ``PYBIND11_OVERRIDE`` family of macros will acquire the GIL before calling
0062 back into Python.
0063 
0064 When writing C++ code that is called from other C++ code, if that code accesses
0065 Python state, it must explicitly acquire and release the GIL.
0066 
0067 The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
0068 used to acquire and release the global interpreter lock in the body of a C++
0069 function call. In this way, long-running C++ code can be parallelized using
0070 multiple Python threads, **but great care must be taken** when any
0071 :class:`gil_scoped_release` appear: if there is any way that the C++ code
0072 can access Python objects, :class:`gil_scoped_acquire` should be used to
0073 reacquire the GIL. Taking :ref:`overriding_virtuals` as an example, this
0074 could be realized as follows (important changes highlighted):
0075 
0076 .. code-block:: cpp
0077     :emphasize-lines: 8,30,31
0078 
0079     class PyAnimal : public Animal {
0080     public:
0081         /* Inherit the constructors */
0082         using Animal::Animal;
0083 
0084         /* Trampoline (need one for each virtual function) */
0085         std::string go(int n_times) {
0086             /* PYBIND11_OVERRIDE_PURE will acquire the GIL before accessing Python state */
0087             PYBIND11_OVERRIDE_PURE(
0088                 std::string, /* Return type */
0089                 Animal,      /* Parent class */
0090                 go,          /* Name of function */
0091                 n_times      /* Argument(s) */
0092             );
0093         }
0094     };
0095 
0096     PYBIND11_MODULE(example, m) {
0097         py::class_<Animal, PyAnimal> animal(m, "Animal");
0098         animal
0099             .def(py::init<>())
0100             .def("go", &Animal::go);
0101 
0102         py::class_<Dog>(m, "Dog", animal)
0103             .def(py::init<>());
0104 
0105         m.def("call_go", [](Animal *animal) -> std::string {
0106             // GIL is held when called from Python code. Release GIL before
0107             // calling into (potentially long-running) C++ code
0108             py::gil_scoped_release release;
0109             return call_go(animal);
0110         });
0111     }
0112 
0113 The ``call_go`` wrapper can also be simplified using the ``call_guard`` policy
0114 (see :ref:`call_policies`) which yields the same result:
0115 
0116 .. code-block:: cpp
0117 
0118     m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
0119 
0120 
0121 Common Sources Of Global Interpreter Lock Errors
0122 ==================================================================
0123 
0124 Failing to properly hold the Global Interpreter Lock (GIL) is one of the
0125 more common sources of bugs within code that uses pybind11. If you are
0126 running into GIL related errors, we highly recommend you consult the
0127 following checklist.
0128 
0129 - Do you have any global variables that are pybind11 objects or invoke
0130   pybind11 functions in either their constructor or destructor? You are generally
0131   not allowed to invoke any Python function in a global static context. We recommend
0132   using lazy initialization and then intentionally leaking at the end of the program.
0133 
0134 - Do you have any pybind11 objects that are members of other C++ structures? One
0135   commonly overlooked requirement is that pybind11 objects have to increase their reference count
0136   whenever their copy constructor is called. Thus, you need to be holding the GIL to invoke
0137   the copy constructor of any C++ class that has a pybind11 member. This can sometimes be very
0138   tricky to track for complicated programs Think carefully when you make a pybind11 object
0139   a member in another struct.
0140 
0141 - C++ destructors that invoke Python functions can be particularly troublesome as
0142   destructors can sometimes get invoked in weird and unexpected circumstances as a result
0143   of exceptions.
0144 
0145 - You should try running your code in a debug build. That will enable additional assertions
0146   within pybind11 that will throw exceptions on certain GIL handling errors
0147   (reference counting operations).
0148 
0149 Binding sequence data types, iterators, the slicing protocol, etc.
0150 ==================================================================
0151 
0152 Please refer to the supplemental example for details.
0153 
0154 .. seealso::
0155 
0156     The file :file:`tests/test_sequences_and_iterators.cpp` contains a
0157     complete example that shows how to bind a sequence data type, including
0158     length queries (``__len__``), iterators (``__iter__``), the slicing
0159     protocol and other kinds of useful operations.
0160 
0161 
0162 Partitioning code over multiple extension modules
0163 =================================================
0164 
0165 It's straightforward to split binding code over multiple extension modules,
0166 while referencing types that are declared elsewhere. Everything "just" works
0167 without any special precautions. One exception to this rule occurs when
0168 extending a type declared in another extension module. Recall the basic example
0169 from Section :ref:`inheritance`.
0170 
0171 .. code-block:: cpp
0172 
0173     py::class_<Pet> pet(m, "Pet");
0174     pet.def(py::init<const std::string &>())
0175        .def_readwrite("name", &Pet::name);
0176 
0177     py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
0178         .def(py::init<const std::string &>())
0179         .def("bark", &Dog::bark);
0180 
0181 Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
0182 whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
0183 course that the variable ``pet`` is not available anymore though it is needed
0184 to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
0185 However, it can be acquired as follows:
0186 
0187 .. code-block:: cpp
0188 
0189     py::object pet = (py::object) py::module_::import("basic").attr("Pet");
0190 
0191     py::class_<Dog>(m, "Dog", pet)
0192         .def(py::init<const std::string &>())
0193         .def("bark", &Dog::bark);
0194 
0195 Alternatively, you can specify the base class as a template parameter option to
0196 ``class_``, which performs an automated lookup of the corresponding Python
0197 type. Like the above code, however, this also requires invoking the ``import``
0198 function once to ensure that the pybind11 binding code of the module ``basic``
0199 has been executed:
0200 
0201 .. code-block:: cpp
0202 
0203     py::module_::import("basic");
0204 
0205     py::class_<Dog, Pet>(m, "Dog")
0206         .def(py::init<const std::string &>())
0207         .def("bark", &Dog::bark);
0208 
0209 Naturally, both methods will fail when there are cyclic dependencies.
0210 
0211 Note that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
0212 via the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
0213 required for proper pybind11 functionality, can interfere with the ability to
0214 access types defined in another extension module.  Working around this requires
0215 manually exporting types that are accessed by multiple extension modules;
0216 pybind11 provides a macro to do just this:
0217 
0218 .. code-block:: cpp
0219 
0220     class PYBIND11_EXPORT Dog : public Animal {
0221         ...
0222     };
0223 
0224 Note also that it is possible (although would rarely be required) to share arbitrary
0225 C++ objects between extension modules at runtime. Internal library data is shared
0226 between modules using capsule machinery [#f6]_ which can be also utilized for
0227 storing, modifying and accessing user-defined data. Note that an extension module
0228 will "see" other extensions' data if and only if they were built with the same
0229 pybind11 version. Consider the following example:
0230 
0231 .. code-block:: cpp
0232 
0233     auto data = reinterpret_cast<MyData *>(py::get_shared_data("mydata"));
0234     if (!data)
0235         data = static_cast<MyData *>(py::set_shared_data("mydata", new MyData(42)));
0236 
0237 If the above snippet was used in several separately compiled extension modules,
0238 the first one to be imported would create a ``MyData`` instance and associate
0239 a ``"mydata"`` key with a pointer to it. Extensions that are imported later
0240 would be then able to access the data behind the same pointer.
0241 
0242 .. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
0243 
0244 Module Destructors
0245 ==================
0246 
0247 pybind11 does not provide an explicit mechanism to invoke cleanup code at
0248 module destruction time. In rare cases where such functionality is required, it
0249 is possible to emulate it using Python capsules or weak references with a
0250 destruction callback.
0251 
0252 .. code-block:: cpp
0253 
0254     auto cleanup_callback = []() {
0255         // perform cleanup here -- this function is called with the GIL held
0256     };
0257 
0258     m.add_object("_cleanup", py::capsule(cleanup_callback));
0259 
0260 This approach has the potential downside that instances of classes exposed
0261 within the module may still be alive when the cleanup callback is invoked
0262 (whether this is acceptable will generally depend on the application).
0263 
0264 Alternatively, the capsule may also be stashed within a type object, which
0265 ensures that it not called before all instances of that type have been
0266 collected:
0267 
0268 .. code-block:: cpp
0269 
0270     auto cleanup_callback = []() { /* ... */ };
0271     m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
0272 
0273 Both approaches also expose a potentially dangerous ``_cleanup`` attribute in
0274 Python, which may be undesirable from an API standpoint (a premature explicit
0275 call from Python might lead to undefined behavior). Yet another approach that
0276 avoids this issue involves weak reference with a cleanup callback:
0277 
0278 .. code-block:: cpp
0279 
0280     // Register a callback function that is invoked when the BaseClass object is collected
0281     py::cpp_function cleanup_callback(
0282         [](py::handle weakref) {
0283             // perform cleanup here -- this function is called with the GIL held
0284 
0285             weakref.dec_ref(); // release weak reference
0286         }
0287     );
0288 
0289     // Create a weak reference with a cleanup callback and initially leak it
0290     (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
0291 
0292 .. note::
0293 
0294     PyPy does not garbage collect objects when the interpreter exits. An alternative
0295     approach (which also works on CPython) is to use the :py:mod:`atexit` module [#f7]_,
0296     for example:
0297 
0298     .. code-block:: cpp
0299 
0300         auto atexit = py::module_::import("atexit");
0301         atexit.attr("register")(py::cpp_function([]() {
0302             // perform cleanup here -- this function is called with the GIL held
0303         }));
0304 
0305     .. [#f7] https://docs.python.org/3/library/atexit.html
0306 
0307 
0308 Generating documentation using Sphinx
0309 =====================================
0310 
0311 Sphinx [#f4]_ has the ability to inspect the signatures and documentation
0312 strings in pybind11-based extension modules to automatically generate beautiful
0313 documentation in a variety formats. The python_example repository [#f5]_ contains a
0314 simple example repository which uses this approach.
0315 
0316 There are two potential gotchas when using this approach: first, make sure that
0317 the resulting strings do not contain any :kbd:`TAB` characters, which break the
0318 docstring parsing routines. You may want to use C++11 raw string literals,
0319 which are convenient for multi-line comments. Conveniently, any excess
0320 indentation will be automatically be removed by Sphinx. However, for this to
0321 work, it is important that all lines are indented consistently, i.e.:
0322 
0323 .. code-block:: cpp
0324 
0325     // ok
0326     m.def("foo", &foo, R"mydelimiter(
0327         The foo function
0328 
0329         Parameters
0330         ----------
0331     )mydelimiter");
0332 
0333     // *not ok*
0334     m.def("foo", &foo, R"mydelimiter(The foo function
0335 
0336         Parameters
0337         ----------
0338     )mydelimiter");
0339 
0340 By default, pybind11 automatically generates and prepends a signature to the docstring of a function
0341 registered with ``module_::def()`` and ``class_::def()``. Sometimes this
0342 behavior is not desirable, because you want to provide your own signature or remove
0343 the docstring completely to exclude the function from the Sphinx documentation.
0344 The class ``options`` allows you to selectively suppress auto-generated signatures:
0345 
0346 .. code-block:: cpp
0347 
0348     PYBIND11_MODULE(example, m) {
0349         py::options options;
0350         options.disable_function_signatures();
0351 
0352         m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
0353     }
0354 
0355 pybind11 also appends all members of an enum to the resulting enum docstring.
0356 This default behavior can be disabled by using the ``disable_enum_members_docstring()``
0357 function of the ``options`` class.
0358 
0359 With ``disable_user_defined_docstrings()`` all user defined docstrings of
0360 ``module_::def()``, ``class_::def()`` and ``enum_()`` are disabled, but the
0361 function signatures and enum members are included in the docstring, unless they
0362 are disabled separately.
0363 
0364 Note that changes to the settings affect only function bindings created during the
0365 lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function,
0366 the default settings are restored to prevent unwanted side effects.
0367 
0368 .. [#f4] http://www.sphinx-doc.org
0369 .. [#f5] http://github.com/pybind/python_example
0370 
0371 .. _avoiding-cpp-types-in-docstrings:
0372 
0373 Avoiding C++ types in docstrings
0374 ================================
0375 
0376 Docstrings are generated at the time of the declaration, e.g. when ``.def(...)`` is called.
0377 At this point parameter and return types should be known to pybind11.
0378 If a custom type is not exposed yet through a ``py::class_`` constructor or a custom type caster,
0379 its C++ type name will be used instead to generate the signature in the docstring:
0380 
0381 .. code-block:: text
0382 
0383      |  __init__(...)
0384      |      __init__(self: example.Foo, arg0: ns::Bar) -> None
0385                                               ^^^^^^^
0386 
0387 
0388 This limitation can be circumvented by ensuring that C++ classes are registered with pybind11
0389 before they are used as a parameter or return type of a function:
0390 
0391 .. code-block:: cpp
0392 
0393     PYBIND11_MODULE(example, m) {
0394 
0395         auto pyFoo = py::class_<ns::Foo>(m, "Foo");
0396         auto pyBar = py::class_<ns::Bar>(m, "Bar");
0397 
0398         pyFoo.def(py::init<const ns::Bar&>());
0399         pyBar.def(py::init<const ns::Foo&>());
0400     }