misc.rst revision 12391
111986Sandreas.sandberg@arm.comMiscellaneous
211986Sandreas.sandberg@arm.com#############
311986Sandreas.sandberg@arm.com
411986Sandreas.sandberg@arm.com.. _macro_notes:
511986Sandreas.sandberg@arm.com
611986Sandreas.sandberg@arm.comGeneral notes regarding convenience macros
711986Sandreas.sandberg@arm.com==========================================
811986Sandreas.sandberg@arm.com
911986Sandreas.sandberg@arm.compybind11 provides a few convenience macros such as
1011986Sandreas.sandberg@arm.com:func:`PYBIND11_MAKE_OPAQUE` and :func:`PYBIND11_DECLARE_HOLDER_TYPE`, and
1111986Sandreas.sandberg@arm.com``PYBIND11_OVERLOAD_*``. Since these are "just" macros that are evaluated
1211986Sandreas.sandberg@arm.comin the preprocessor (which has no concept of types), they *will* get confused
1311986Sandreas.sandberg@arm.comby commas in a template argument such as ``PYBIND11_OVERLOAD(MyReturnValue<T1,
1411986Sandreas.sandberg@arm.comT2>, myFunc)``. In this case, the preprocessor assumes that the comma indicates
1511986Sandreas.sandberg@arm.comthe beginning of the next parameter. Use a ``typedef`` to bind the template to
1611986Sandreas.sandberg@arm.comanother name and use it in the macro to avoid this problem.
1711986Sandreas.sandberg@arm.com
1812391Sjason@lowepower.com.. _gil:
1911986Sandreas.sandberg@arm.com
2011986Sandreas.sandberg@arm.comGlobal Interpreter Lock (GIL)
2111986Sandreas.sandberg@arm.com=============================
2211986Sandreas.sandberg@arm.com
2312037Sandreas.sandberg@arm.comWhen calling a C++ function from Python, the GIL is always held.
2411986Sandreas.sandberg@arm.comThe classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
2511986Sandreas.sandberg@arm.comused to acquire and release the global interpreter lock in the body of a C++
2611986Sandreas.sandberg@arm.comfunction call. In this way, long-running C++ code can be parallelized using
2711986Sandreas.sandberg@arm.commultiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
2811986Sandreas.sandberg@arm.comcould be realized as follows (important changes highlighted):
2911986Sandreas.sandberg@arm.com
3011986Sandreas.sandberg@arm.com.. code-block:: cpp
3112391Sjason@lowepower.com    :emphasize-lines: 8,9,31,32
3211986Sandreas.sandberg@arm.com
3311986Sandreas.sandberg@arm.com    class PyAnimal : public Animal {
3411986Sandreas.sandberg@arm.com    public:
3511986Sandreas.sandberg@arm.com        /* Inherit the constructors */
3611986Sandreas.sandberg@arm.com        using Animal::Animal;
3711986Sandreas.sandberg@arm.com
3811986Sandreas.sandberg@arm.com        /* Trampoline (need one for each virtual function) */
3911986Sandreas.sandberg@arm.com        std::string go(int n_times) {
4011986Sandreas.sandberg@arm.com            /* Acquire GIL before calling Python code */
4111986Sandreas.sandberg@arm.com            py::gil_scoped_acquire acquire;
4211986Sandreas.sandberg@arm.com
4311986Sandreas.sandberg@arm.com            PYBIND11_OVERLOAD_PURE(
4411986Sandreas.sandberg@arm.com                std::string, /* Return type */
4511986Sandreas.sandberg@arm.com                Animal,      /* Parent class */
4611986Sandreas.sandberg@arm.com                go,          /* Name of function */
4711986Sandreas.sandberg@arm.com                n_times      /* Argument(s) */
4811986Sandreas.sandberg@arm.com            );
4911986Sandreas.sandberg@arm.com        }
5011986Sandreas.sandberg@arm.com    };
5111986Sandreas.sandberg@arm.com
5212391Sjason@lowepower.com    PYBIND11_MODULE(example, m) {
5311986Sandreas.sandberg@arm.com        py::class_<Animal, PyAnimal> animal(m, "Animal");
5411986Sandreas.sandberg@arm.com        animal
5511986Sandreas.sandberg@arm.com            .def(py::init<>())
5611986Sandreas.sandberg@arm.com            .def("go", &Animal::go);
5711986Sandreas.sandberg@arm.com
5811986Sandreas.sandberg@arm.com        py::class_<Dog>(m, "Dog", animal)
5911986Sandreas.sandberg@arm.com            .def(py::init<>());
6011986Sandreas.sandberg@arm.com
6111986Sandreas.sandberg@arm.com        m.def("call_go", [](Animal *animal) -> std::string {
6211986Sandreas.sandberg@arm.com            /* Release GIL before calling into (potentially long-running) C++ code */
6311986Sandreas.sandberg@arm.com            py::gil_scoped_release release;
6411986Sandreas.sandberg@arm.com            return call_go(animal);
6511986Sandreas.sandberg@arm.com        });
6612391Sjason@lowepower.com    }
6711986Sandreas.sandberg@arm.com
6812391Sjason@lowepower.comThe ``call_go`` wrapper can also be simplified using the `call_guard` policy
6912391Sjason@lowepower.com(see :ref:`call_policies`) which yields the same result:
7012391Sjason@lowepower.com
7112391Sjason@lowepower.com.. code-block:: cpp
7212391Sjason@lowepower.com
7312391Sjason@lowepower.com    m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
7411986Sandreas.sandberg@arm.com
7511986Sandreas.sandberg@arm.com
7611986Sandreas.sandberg@arm.comBinding sequence data types, iterators, the slicing protocol, etc.
7711986Sandreas.sandberg@arm.com==================================================================
7811986Sandreas.sandberg@arm.com
7911986Sandreas.sandberg@arm.comPlease refer to the supplemental example for details.
8011986Sandreas.sandberg@arm.com
8111986Sandreas.sandberg@arm.com.. seealso::
8211986Sandreas.sandberg@arm.com
8311986Sandreas.sandberg@arm.com    The file :file:`tests/test_sequences_and_iterators.cpp` contains a
8411986Sandreas.sandberg@arm.com    complete example that shows how to bind a sequence data type, including
8511986Sandreas.sandberg@arm.com    length queries (``__len__``), iterators (``__iter__``), the slicing
8611986Sandreas.sandberg@arm.com    protocol and other kinds of useful operations.
8711986Sandreas.sandberg@arm.com
8811986Sandreas.sandberg@arm.com
8911986Sandreas.sandberg@arm.comPartitioning code over multiple extension modules
9011986Sandreas.sandberg@arm.com=================================================
9111986Sandreas.sandberg@arm.com
9211986Sandreas.sandberg@arm.comIt's straightforward to split binding code over multiple extension modules,
9311986Sandreas.sandberg@arm.comwhile referencing types that are declared elsewhere. Everything "just" works
9411986Sandreas.sandberg@arm.comwithout any special precautions. One exception to this rule occurs when
9511986Sandreas.sandberg@arm.comextending a type declared in another extension module. Recall the basic example
9611986Sandreas.sandberg@arm.comfrom Section :ref:`inheritance`.
9711986Sandreas.sandberg@arm.com
9811986Sandreas.sandberg@arm.com.. code-block:: cpp
9911986Sandreas.sandberg@arm.com
10011986Sandreas.sandberg@arm.com    py::class_<Pet> pet(m, "Pet");
10111986Sandreas.sandberg@arm.com    pet.def(py::init<const std::string &>())
10211986Sandreas.sandberg@arm.com       .def_readwrite("name", &Pet::name);
10311986Sandreas.sandberg@arm.com
10411986Sandreas.sandberg@arm.com    py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
10511986Sandreas.sandberg@arm.com        .def(py::init<const std::string &>())
10611986Sandreas.sandberg@arm.com        .def("bark", &Dog::bark);
10711986Sandreas.sandberg@arm.com
10811986Sandreas.sandberg@arm.comSuppose now that ``Pet`` bindings are defined in a module named ``basic``,
10911986Sandreas.sandberg@arm.comwhereas the ``Dog`` bindings are defined somewhere else. The challenge is of
11011986Sandreas.sandberg@arm.comcourse that the variable ``pet`` is not available anymore though it is needed
11111986Sandreas.sandberg@arm.comto indicate the inheritance relationship to the constructor of ``class_<Dog>``.
11211986Sandreas.sandberg@arm.comHowever, it can be acquired as follows:
11311986Sandreas.sandberg@arm.com
11411986Sandreas.sandberg@arm.com.. code-block:: cpp
11511986Sandreas.sandberg@arm.com
11611986Sandreas.sandberg@arm.com    py::object pet = (py::object) py::module::import("basic").attr("Pet");
11711986Sandreas.sandberg@arm.com
11811986Sandreas.sandberg@arm.com    py::class_<Dog>(m, "Dog", pet)
11911986Sandreas.sandberg@arm.com        .def(py::init<const std::string &>())
12011986Sandreas.sandberg@arm.com        .def("bark", &Dog::bark);
12111986Sandreas.sandberg@arm.com
12211986Sandreas.sandberg@arm.comAlternatively, you can specify the base class as a template parameter option to
12311986Sandreas.sandberg@arm.com``class_``, which performs an automated lookup of the corresponding Python
12411986Sandreas.sandberg@arm.comtype. Like the above code, however, this also requires invoking the ``import``
12511986Sandreas.sandberg@arm.comfunction once to ensure that the pybind11 binding code of the module ``basic``
12611986Sandreas.sandberg@arm.comhas been executed:
12711986Sandreas.sandberg@arm.com
12811986Sandreas.sandberg@arm.com.. code-block:: cpp
12911986Sandreas.sandberg@arm.com
13011986Sandreas.sandberg@arm.com    py::module::import("basic");
13111986Sandreas.sandberg@arm.com
13211986Sandreas.sandberg@arm.com    py::class_<Dog, Pet>(m, "Dog")
13311986Sandreas.sandberg@arm.com        .def(py::init<const std::string &>())
13411986Sandreas.sandberg@arm.com        .def("bark", &Dog::bark);
13511986Sandreas.sandberg@arm.com
13611986Sandreas.sandberg@arm.comNaturally, both methods will fail when there are cyclic dependencies.
13711986Sandreas.sandberg@arm.com
13812391Sjason@lowepower.comNote that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
13912391Sjason@lowepower.comvia the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
14012391Sjason@lowepower.comrequired proper pybind11 functionality, can interfere with the ability to
14112391Sjason@lowepower.comaccess types defined in another extension module.  Working around this requires
14212391Sjason@lowepower.commanually exporting types that are accessed by multiple extension modules;
14312391Sjason@lowepower.compybind11 provides a macro to do just this:
14411986Sandreas.sandberg@arm.com
14511986Sandreas.sandberg@arm.com.. code-block:: cpp
14611986Sandreas.sandberg@arm.com
14712391Sjason@lowepower.com    class PYBIND11_EXPORT Dog : public Animal {
14811986Sandreas.sandberg@arm.com        ...
14911986Sandreas.sandberg@arm.com    };
15011986Sandreas.sandberg@arm.com
15111986Sandreas.sandberg@arm.comNote also that it is possible (although would rarely be required) to share arbitrary
15211986Sandreas.sandberg@arm.comC++ objects between extension modules at runtime. Internal library data is shared
15311986Sandreas.sandberg@arm.combetween modules using capsule machinery [#f6]_ which can be also utilized for
15411986Sandreas.sandberg@arm.comstoring, modifying and accessing user-defined data. Note that an extension module
15511986Sandreas.sandberg@arm.comwill "see" other extensions' data if and only if they were built with the same
15611986Sandreas.sandberg@arm.compybind11 version. Consider the following example:
15711986Sandreas.sandberg@arm.com
15811986Sandreas.sandberg@arm.com.. code-block:: cpp
15911986Sandreas.sandberg@arm.com
16011986Sandreas.sandberg@arm.com    auto data = (MyData *) py::get_shared_data("mydata");
16111986Sandreas.sandberg@arm.com    if (!data)
16211986Sandreas.sandberg@arm.com        data = (MyData *) py::set_shared_data("mydata", new MyData(42));
16311986Sandreas.sandberg@arm.com
16411986Sandreas.sandberg@arm.comIf the above snippet was used in several separately compiled extension modules,
16511986Sandreas.sandberg@arm.comthe first one to be imported would create a ``MyData`` instance and associate
16611986Sandreas.sandberg@arm.coma ``"mydata"`` key with a pointer to it. Extensions that are imported later
16711986Sandreas.sandberg@arm.comwould be then able to access the data behind the same pointer.
16811986Sandreas.sandberg@arm.com
16911986Sandreas.sandberg@arm.com.. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
17011986Sandreas.sandberg@arm.com
17112037Sandreas.sandberg@arm.comModule Destructors
17212037Sandreas.sandberg@arm.com==================
17312037Sandreas.sandberg@arm.com
17412037Sandreas.sandberg@arm.compybind11 does not provide an explicit mechanism to invoke cleanup code at
17512037Sandreas.sandberg@arm.commodule destruction time. In rare cases where such functionality is required, it
17612391Sjason@lowepower.comis possible to emulate it using Python capsules or weak references with a
17712391Sjason@lowepower.comdestruction callback.
17812037Sandreas.sandberg@arm.com
17912037Sandreas.sandberg@arm.com.. code-block:: cpp
18012037Sandreas.sandberg@arm.com
18112037Sandreas.sandberg@arm.com    auto cleanup_callback = []() {
18212037Sandreas.sandberg@arm.com        // perform cleanup here -- this function is called with the GIL held
18312037Sandreas.sandberg@arm.com    };
18412037Sandreas.sandberg@arm.com
18512037Sandreas.sandberg@arm.com    m.add_object("_cleanup", py::capsule(cleanup_callback));
18611986Sandreas.sandberg@arm.com
18712391Sjason@lowepower.comThis approach has the potential downside that instances of classes exposed
18812391Sjason@lowepower.comwithin the module may still be alive when the cleanup callback is invoked
18912391Sjason@lowepower.com(whether this is acceptable will generally depend on the application).
19012391Sjason@lowepower.com
19112391Sjason@lowepower.comAlternatively, the capsule may also be stashed within a type object, which
19212391Sjason@lowepower.comensures that it not called before all instances of that type have been
19312391Sjason@lowepower.comcollected:
19412391Sjason@lowepower.com
19512391Sjason@lowepower.com.. code-block:: cpp
19612391Sjason@lowepower.com
19712391Sjason@lowepower.com    auto cleanup_callback = []() { /* ... */ };
19812391Sjason@lowepower.com    m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
19912391Sjason@lowepower.com
20012391Sjason@lowepower.comBoth approaches also expose a potentially dangerous ``_cleanup`` attribute in
20112391Sjason@lowepower.comPython, which may be undesirable from an API standpoint (a premature explicit
20212391Sjason@lowepower.comcall from Python might lead to undefined behavior). Yet another approach that 
20312391Sjason@lowepower.comavoids this issue involves weak reference with a cleanup callback:
20412391Sjason@lowepower.com
20512391Sjason@lowepower.com.. code-block:: cpp
20612391Sjason@lowepower.com
20712391Sjason@lowepower.com    // Register a callback function that is invoked when the BaseClass object is colelcted
20812391Sjason@lowepower.com    py::cpp_function cleanup_callback(
20912391Sjason@lowepower.com        [](py::handle weakref) {
21012391Sjason@lowepower.com            // perform cleanup here -- this function is called with the GIL held
21112391Sjason@lowepower.com
21212391Sjason@lowepower.com            weakref.dec_ref(); // release weak reference
21312391Sjason@lowepower.com        }
21412391Sjason@lowepower.com    );
21512391Sjason@lowepower.com
21612391Sjason@lowepower.com    // Create a weak reference with a cleanup callback and initially leak it
21712391Sjason@lowepower.com    (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
21812391Sjason@lowepower.com
21912391Sjason@lowepower.com
22011986Sandreas.sandberg@arm.comGenerating documentation using Sphinx
22111986Sandreas.sandberg@arm.com=====================================
22211986Sandreas.sandberg@arm.com
22311986Sandreas.sandberg@arm.comSphinx [#f4]_ has the ability to inspect the signatures and documentation
22411986Sandreas.sandberg@arm.comstrings in pybind11-based extension modules to automatically generate beautiful
22511986Sandreas.sandberg@arm.comdocumentation in a variety formats. The python_example repository [#f5]_ contains a
22611986Sandreas.sandberg@arm.comsimple example repository which uses this approach.
22711986Sandreas.sandberg@arm.com
22811986Sandreas.sandberg@arm.comThere are two potential gotchas when using this approach: first, make sure that
22911986Sandreas.sandberg@arm.comthe resulting strings do not contain any :kbd:`TAB` characters, which break the
23011986Sandreas.sandberg@arm.comdocstring parsing routines. You may want to use C++11 raw string literals,
23111986Sandreas.sandberg@arm.comwhich are convenient for multi-line comments. Conveniently, any excess
23211986Sandreas.sandberg@arm.comindentation will be automatically be removed by Sphinx. However, for this to
23311986Sandreas.sandberg@arm.comwork, it is important that all lines are indented consistently, i.e.:
23411986Sandreas.sandberg@arm.com
23511986Sandreas.sandberg@arm.com.. code-block:: cpp
23611986Sandreas.sandberg@arm.com
23711986Sandreas.sandberg@arm.com    // ok
23811986Sandreas.sandberg@arm.com    m.def("foo", &foo, R"mydelimiter(
23911986Sandreas.sandberg@arm.com        The foo function
24011986Sandreas.sandberg@arm.com
24111986Sandreas.sandberg@arm.com        Parameters
24211986Sandreas.sandberg@arm.com        ----------
24311986Sandreas.sandberg@arm.com    )mydelimiter");
24411986Sandreas.sandberg@arm.com
24511986Sandreas.sandberg@arm.com    // *not ok*
24611986Sandreas.sandberg@arm.com    m.def("foo", &foo, R"mydelimiter(The foo function
24711986Sandreas.sandberg@arm.com
24811986Sandreas.sandberg@arm.com        Parameters
24911986Sandreas.sandberg@arm.com        ----------
25011986Sandreas.sandberg@arm.com    )mydelimiter");
25111986Sandreas.sandberg@arm.com
25211986Sandreas.sandberg@arm.comBy default, pybind11 automatically generates and prepends a signature to the docstring of a function 
25311986Sandreas.sandberg@arm.comregistered with ``module::def()`` and ``class_::def()``. Sometimes this
25411986Sandreas.sandberg@arm.combehavior is not desirable, because you want to provide your own signature or remove 
25511986Sandreas.sandberg@arm.comthe docstring completely to exclude the function from the Sphinx documentation.
25611986Sandreas.sandberg@arm.comThe class ``options`` allows you to selectively suppress auto-generated signatures:
25711986Sandreas.sandberg@arm.com
25811986Sandreas.sandberg@arm.com.. code-block:: cpp
25911986Sandreas.sandberg@arm.com
26012391Sjason@lowepower.com    PYBIND11_MODULE(example, m) {
26111986Sandreas.sandberg@arm.com        py::options options;
26211986Sandreas.sandberg@arm.com        options.disable_function_signatures();
26312391Sjason@lowepower.com
26411986Sandreas.sandberg@arm.com        m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
26511986Sandreas.sandberg@arm.com    }
26611986Sandreas.sandberg@arm.com
26711986Sandreas.sandberg@arm.comNote that changes to the settings affect only function bindings created during the 
26811986Sandreas.sandberg@arm.comlifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function, 
26911986Sandreas.sandberg@arm.comthe default settings are restored to prevent unwanted side effects.
27011986Sandreas.sandberg@arm.com
27111986Sandreas.sandberg@arm.com.. [#f4] http://www.sphinx-doc.org
27211986Sandreas.sandberg@arm.com.. [#f5] http://github.com/pybind/python_example
273