Blame external/pybind11/docs/advanced/misc.rst

Packit 534379
Miscellaneous
Packit 534379
#############
Packit 534379
Packit 534379
.. _macro_notes:
Packit 534379
Packit 534379
General notes regarding convenience macros
Packit 534379
==========================================
Packit 534379
Packit 534379
pybind11 provides a few convenience macros such as
Packit 534379
:func:`PYBIND11_DECLARE_HOLDER_TYPE` and ``PYBIND11_OVERLOAD_*``. Since these
Packit 534379
are "just" macros that are evaluated in the preprocessor (which has no concept
Packit 534379
of types), they *will* get confused by commas in a template argument; for
Packit 534379
example, consider:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    PYBIND11_OVERLOAD(MyReturnType<T1, T2>, Class<T3, T4>, func)
Packit 534379
Packit 534379
The limitation of the C preprocessor interprets this as five arguments (with new
Packit 534379
arguments beginning after each comma) rather than three.  To get around this,
Packit 534379
there are two alternatives: you can use a type alias, or you can wrap the type
Packit 534379
using the ``PYBIND11_TYPE`` macro:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Version 1: using a type alias
Packit 534379
    using ReturnType = MyReturnType<T1, T2>;
Packit 534379
    using ClassType = Class<T3, T4>;
Packit 534379
    PYBIND11_OVERLOAD(ReturnType, ClassType, func);
Packit 534379
Packit 534379
    // Version 2: using the PYBIND11_TYPE macro:
Packit 534379
    PYBIND11_OVERLOAD(PYBIND11_TYPE(MyReturnType<T1, T2>),
Packit 534379
                      PYBIND11_TYPE(Class<T3, T4>), func)
Packit 534379
Packit 534379
The ``PYBIND11_MAKE_OPAQUE`` macro does *not* require the above workarounds.
Packit 534379
Packit 534379
.. _gil:
Packit 534379
Packit 534379
Global Interpreter Lock (GIL)
Packit 534379
=============================
Packit 534379
Packit 534379
When calling a C++ function from Python, the GIL is always held.
Packit 534379
The classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
Packit 534379
used to acquire and release the global interpreter lock in the body of a C++
Packit 534379
function call. In this way, long-running C++ code can be parallelized using
Packit 534379
multiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
Packit 534379
could be realized as follows (important changes highlighted):
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
    :emphasize-lines: 8,9,31,32
Packit 534379
Packit 534379
    class PyAnimal : public Animal {
Packit 534379
    public:
Packit 534379
        /* Inherit the constructors */
Packit 534379
        using Animal::Animal;
Packit 534379
Packit 534379
        /* Trampoline (need one for each virtual function) */
Packit 534379
        std::string go(int n_times) {
Packit 534379
            /* Acquire GIL before calling Python code */
Packit 534379
            py::gil_scoped_acquire acquire;
Packit 534379
Packit 534379
            PYBIND11_OVERLOAD_PURE(
Packit 534379
                std::string, /* Return type */
Packit 534379
                Animal,      /* Parent class */
Packit 534379
                go,          /* Name of function */
Packit 534379
                n_times      /* Argument(s) */
Packit 534379
            );
Packit 534379
        }
Packit 534379
    };
Packit 534379
Packit 534379
    PYBIND11_MODULE(example, m) {
Packit 534379
        py::class_<Animal, PyAnimal> animal(m, "Animal");
Packit 534379
        animal
Packit 534379
            .def(py::init<>())
Packit 534379
            .def("go", &Animal::go);
Packit 534379
Packit 534379
        py::class_<Dog>(m, "Dog", animal)
Packit 534379
            .def(py::init<>());
Packit 534379
Packit 534379
        m.def("call_go", [](Animal *animal) -> std::string {
Packit 534379
            /* Release GIL before calling into (potentially long-running) C++ code */
Packit 534379
            py::gil_scoped_release release;
Packit 534379
            return call_go(animal);
Packit 534379
        });
Packit 534379
    }
Packit 534379
Packit 534379
The ``call_go`` wrapper can also be simplified using the `call_guard` policy
Packit 534379
(see :ref:`call_policies`) which yields the same result:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
Packit 534379
Packit 534379
Packit 534379
Binding sequence data types, iterators, the slicing protocol, etc.
Packit 534379
==================================================================
Packit 534379
Packit 534379
Please refer to the supplemental example for details.
Packit 534379
Packit 534379
.. seealso::
Packit 534379
Packit 534379
    The file :file:`tests/test_sequences_and_iterators.cpp` contains a
Packit 534379
    complete example that shows how to bind a sequence data type, including
Packit 534379
    length queries (``__len__``), iterators (``__iter__``), the slicing
Packit 534379
    protocol and other kinds of useful operations.
Packit 534379
Packit 534379
Packit 534379
Partitioning code over multiple extension modules
Packit 534379
=================================================
Packit 534379
Packit 534379
It's straightforward to split binding code over multiple extension modules,
Packit 534379
while referencing types that are declared elsewhere. Everything "just" works
Packit 534379
without any special precautions. One exception to this rule occurs when
Packit 534379
extending a type declared in another extension module. Recall the basic example
Packit 534379
from Section :ref:`inheritance`.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::class_<Pet> pet(m, "Pet");
Packit 534379
    pet.def(py::init<const std::string &>())
Packit 534379
       .def_readwrite("name", &Pet::name);
Packit 534379
Packit 534379
    py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
Packit 534379
        .def(py::init<const std::string &>())
Packit 534379
        .def("bark", &Dog::bark);
Packit 534379
Packit 534379
Suppose now that ``Pet`` bindings are defined in a module named ``basic``,
Packit 534379
whereas the ``Dog`` bindings are defined somewhere else. The challenge is of
Packit 534379
course that the variable ``pet`` is not available anymore though it is needed
Packit 534379
to indicate the inheritance relationship to the constructor of ``class_<Dog>``.
Packit 534379
However, it can be acquired as follows:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::object pet = (py::object) py::module::import("basic").attr("Pet");
Packit 534379
Packit 534379
    py::class_<Dog>(m, "Dog", pet)
Packit 534379
        .def(py::init<const std::string &>())
Packit 534379
        .def("bark", &Dog::bark);
Packit 534379
Packit 534379
Alternatively, you can specify the base class as a template parameter option to
Packit 534379
``class_``, which performs an automated lookup of the corresponding Python
Packit 534379
type. Like the above code, however, this also requires invoking the ``import``
Packit 534379
function once to ensure that the pybind11 binding code of the module ``basic``
Packit 534379
has been executed:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    py::module::import("basic");
Packit 534379
Packit 534379
    py::class_<Dog, Pet>(m, "Dog")
Packit 534379
        .def(py::init<const std::string &>())
Packit 534379
        .def("bark", &Dog::bark);
Packit 534379
Packit 534379
Naturally, both methods will fail when there are cyclic dependencies.
Packit 534379
Packit 534379
Note that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
Packit 534379
via the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
Packit 534379
required for proper pybind11 functionality, can interfere with the ability to
Packit 534379
access types defined in another extension module.  Working around this requires
Packit 534379
manually exporting types that are accessed by multiple extension modules;
Packit 534379
pybind11 provides a macro to do just this:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    class PYBIND11_EXPORT Dog : public Animal {
Packit 534379
        ...
Packit 534379
    };
Packit 534379
Packit 534379
Note also that it is possible (although would rarely be required) to share arbitrary
Packit 534379
C++ objects between extension modules at runtime. Internal library data is shared
Packit 534379
between modules using capsule machinery [#f6]_ which can be also utilized for
Packit 534379
storing, modifying and accessing user-defined data. Note that an extension module
Packit 534379
will "see" other extensions' data if and only if they were built with the same
Packit 534379
pybind11 version. Consider the following example:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    auto data = (MyData *) py::get_shared_data("mydata");
Packit 534379
    if (!data)
Packit 534379
        data = (MyData *) py::set_shared_data("mydata", new MyData(42));
Packit 534379
Packit 534379
If the above snippet was used in several separately compiled extension modules,
Packit 534379
the first one to be imported would create a ``MyData`` instance and associate
Packit 534379
a ``"mydata"`` key with a pointer to it. Extensions that are imported later
Packit 534379
would be then able to access the data behind the same pointer.
Packit 534379
Packit 534379
.. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
Packit 534379
Packit 534379
Module Destructors
Packit 534379
==================
Packit 534379
Packit 534379
pybind11 does not provide an explicit mechanism to invoke cleanup code at
Packit 534379
module destruction time. In rare cases where such functionality is required, it
Packit 534379
is possible to emulate it using Python capsules or weak references with a
Packit 534379
destruction callback.
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    auto cleanup_callback = []() {
Packit 534379
        // perform cleanup here -- this function is called with the GIL held
Packit 534379
    };
Packit 534379
Packit 534379
    m.add_object("_cleanup", py::capsule(cleanup_callback));
Packit 534379
Packit 534379
This approach has the potential downside that instances of classes exposed
Packit 534379
within the module may still be alive when the cleanup callback is invoked
Packit 534379
(whether this is acceptable will generally depend on the application).
Packit 534379
Packit 534379
Alternatively, the capsule may also be stashed within a type object, which
Packit 534379
ensures that it not called before all instances of that type have been
Packit 534379
collected:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    auto cleanup_callback = []() { /* ... */ };
Packit 534379
    m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
Packit 534379
Packit 534379
Both approaches also expose a potentially dangerous ``_cleanup`` attribute in
Packit 534379
Python, which may be undesirable from an API standpoint (a premature explicit
Packit 534379
call from Python might lead to undefined behavior). Yet another approach that 
Packit 534379
avoids this issue involves weak reference with a cleanup callback:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // Register a callback function that is invoked when the BaseClass object is colelcted
Packit 534379
    py::cpp_function cleanup_callback(
Packit 534379
        [](py::handle weakref) {
Packit 534379
            // perform cleanup here -- this function is called with the GIL held
Packit 534379
Packit 534379
            weakref.dec_ref(); // release weak reference
Packit 534379
        }
Packit 534379
    );
Packit 534379
Packit 534379
    // Create a weak reference with a cleanup callback and initially leak it
Packit 534379
    (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
Packit 534379
Packit 534379
.. note::
Packit 534379
Packit 534379
    PyPy (at least version 5.9) does not garbage collect objects when the
Packit 534379
    interpreter exits. An alternative approach (which also works on CPython) is to use
Packit 534379
    the :py:mod:`atexit` module [#f7]_, for example:
Packit 534379
Packit 534379
    .. code-block:: cpp
Packit 534379
Packit 534379
        auto atexit = py::module::import("atexit");
Packit 534379
        atexit.attr("register")(py::cpp_function([]() {
Packit 534379
            // perform cleanup here -- this function is called with the GIL held
Packit 534379
        }));
Packit 534379
Packit 534379
    .. [#f7] https://docs.python.org/3/library/atexit.html
Packit 534379
Packit 534379
Packit 534379
Generating documentation using Sphinx
Packit 534379
=====================================
Packit 534379
Packit 534379
Sphinx [#f4]_ has the ability to inspect the signatures and documentation
Packit 534379
strings in pybind11-based extension modules to automatically generate beautiful
Packit 534379
documentation in a variety formats. The python_example repository [#f5]_ contains a
Packit 534379
simple example repository which uses this approach.
Packit 534379
Packit 534379
There are two potential gotchas when using this approach: first, make sure that
Packit 534379
the resulting strings do not contain any :kbd:`TAB` characters, which break the
Packit 534379
docstring parsing routines. You may want to use C++11 raw string literals,
Packit 534379
which are convenient for multi-line comments. Conveniently, any excess
Packit 534379
indentation will be automatically be removed by Sphinx. However, for this to
Packit 534379
work, it is important that all lines are indented consistently, i.e.:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    // ok
Packit 534379
    m.def("foo", &foo, R"mydelimiter(
Packit 534379
        The foo function
Packit 534379
Packit 534379
        Parameters
Packit 534379
        ----------
Packit 534379
    )mydelimiter");
Packit 534379
Packit 534379
    // *not ok*
Packit 534379
    m.def("foo", &foo, R"mydelimiter(The foo function
Packit 534379
Packit 534379
        Parameters
Packit 534379
        ----------
Packit 534379
    )mydelimiter");
Packit 534379
Packit 534379
By default, pybind11 automatically generates and prepends a signature to the docstring of a function 
Packit 534379
registered with ``module::def()`` and ``class_::def()``. Sometimes this
Packit 534379
behavior is not desirable, because you want to provide your own signature or remove 
Packit 534379
the docstring completely to exclude the function from the Sphinx documentation.
Packit 534379
The class ``options`` allows you to selectively suppress auto-generated signatures:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    PYBIND11_MODULE(example, m) {
Packit 534379
        py::options options;
Packit 534379
        options.disable_function_signatures();
Packit 534379
Packit 534379
        m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
Packit 534379
    }
Packit 534379
Packit 534379
Note that changes to the settings affect only function bindings created during the 
Packit 534379
lifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function, 
Packit 534379
the default settings are restored to prevent unwanted side effects.
Packit 534379
Packit 534379
.. [#f4] http://www.sphinx-doc.org
Packit 534379
.. [#f5] http://github.com/pybind/python_example