misc.rst revision 12391
12SN/AMiscellaneous
212680Sgiacomo.travaglini@arm.com#############
38703Sandreas.hansson@arm.com
48703Sandreas.hansson@arm.com.. _macro_notes:
58703Sandreas.hansson@arm.com
68703Sandreas.hansson@arm.comGeneral notes regarding convenience macros
78703Sandreas.hansson@arm.com==========================================
88703Sandreas.hansson@arm.com
98703Sandreas.hansson@arm.compybind11 provides a few convenience macros such as
108703Sandreas.hansson@arm.com:func:`PYBIND11_MAKE_OPAQUE` and :func:`PYBIND11_DECLARE_HOLDER_TYPE`, and
118703Sandreas.hansson@arm.com``PYBIND11_OVERLOAD_*``. Since these are "just" macros that are evaluated
128703Sandreas.hansson@arm.comin the preprocessor (which has no concept of types), they *will* get confused
138703Sandreas.hansson@arm.comby commas in a template argument such as ``PYBIND11_OVERLOAD(MyReturnValue<T1,
141762SN/AT2>, myFunc)``. In this case, the preprocessor assumes that the comma indicates
157897Shestness@cs.utexas.eduthe beginning of the next parameter. Use a ``typedef`` to bind the template to
162SN/Aanother name and use it in the macro to avoid this problem.
172SN/A
182SN/A.. _gil:
192SN/A
202SN/AGlobal Interpreter Lock (GIL)
212SN/A=============================
222SN/A
232SN/AWhen calling a C++ function from Python, the GIL is always held.
242SN/AThe classes :class:`gil_scoped_release` and :class:`gil_scoped_acquire` can be
252SN/Aused to acquire and release the global interpreter lock in the body of a C++
262SN/Afunction call. In this way, long-running C++ code can be parallelized using
272SN/Amultiple Python threads. Taking :ref:`overriding_virtuals` as an example, this
282SN/Acould be realized as follows (important changes highlighted):
292SN/A
302SN/A.. code-block:: cpp
312SN/A    :emphasize-lines: 8,9,31,32
322SN/A
332SN/A    class PyAnimal : public Animal {
342SN/A    public:
352SN/A        /* Inherit the constructors */
362SN/A        using Animal::Animal;
372SN/A
382SN/A        /* Trampoline (need one for each virtual function) */
392SN/A        std::string go(int n_times) {
402665Ssaidi@eecs.umich.edu            /* Acquire GIL before calling Python code */
412665Ssaidi@eecs.umich.edu            py::gil_scoped_acquire acquire;
422665Ssaidi@eecs.umich.edu
432665Ssaidi@eecs.umich.edu            PYBIND11_OVERLOAD_PURE(
447897Shestness@cs.utexas.edu                std::string, /* Return type */
452SN/A                Animal,      /* Parent class */
462SN/A                go,          /* Name of function */
472SN/A                n_times      /* Argument(s) */
482SN/A            );
492SN/A        }
502SN/A    };
5111911SBrandon.Potter@amd.com
529645SAndreas.Sandberg@ARM.com    PYBIND11_MODULE(example, m) {
5375SN/A        py::class_<Animal, PyAnimal> animal(m, "Animal");
542SN/A        animal
5510466Sandreas.hansson@arm.com            .def(py::init<>())
562439SN/A            .def("go", &Animal::go);
57603SN/A
5810466Sandreas.hansson@arm.com        py::class_<Dog>(m, "Dog", animal)
594762Snate@binkert.org            .def(py::init<>());
6012680Sgiacomo.travaglini@arm.com
6111911SBrandon.Potter@amd.com        m.def("call_go", [](Animal *animal) -> std::string {
622520SN/A            /* Release GIL before calling into (potentially long-running) C++ code */
639847Sandreas.hansson@arm.com            py::gil_scoped_release release;
644762Snate@binkert.org            return call_go(animal);
6511911SBrandon.Potter@amd.com        });
6613883Sdavid.hashe@amd.com    }
6711909SBrandon.Potter@amd.com
6813892Sgabeblack@google.comThe ``call_go`` wrapper can also be simplified using the `call_guard` policy
696658Snate@binkert.org(see :ref:`call_policies`) which yields the same result:
7010494Sandreas.hansson@arm.com
7110494Sandreas.hansson@arm.com.. code-block:: cpp
7210494Sandreas.hansson@arm.com
7310494Sandreas.hansson@arm.com    m.def("call_go", &call_go, py::call_guard<py::gil_scoped_release>());
7410494Sandreas.hansson@arm.com
7510494Sandreas.hansson@arm.com
7611911SBrandon.Potter@amd.comBinding sequence data types, iterators, the slicing protocol, etc.
7710494Sandreas.hansson@arm.com==================================================================
7810494Sandreas.hansson@arm.com
798769Sgblack@eecs.umich.eduPlease refer to the supplemental example for details.
8011839SCurtis.Dunham@arm.com
811634SN/A.. seealso::
828769Sgblack@eecs.umich.edu
832SN/A    The file :file:`tests/test_sequences_and_iterators.cpp` contains a
8413892Sgabeblack@google.com    complete example that shows how to bind a sequence data type, including
852SN/A    length queries (``__len__``), iterators (``__iter__``), the slicing
868703Sandreas.hansson@arm.com    protocol and other kinds of useful operations.
878703Sandreas.hansson@arm.com
888703Sandreas.hansson@arm.com
898703Sandreas.hansson@arm.comPartitioning code over multiple extension modules
908703Sandreas.hansson@arm.com=================================================
918703Sandreas.hansson@arm.com
928703Sandreas.hansson@arm.comIt's straightforward to split binding code over multiple extension modules,
938922Swilliam.wang@arm.comwhile referencing types that are declared elsewhere. Everything "just" works
948703Sandreas.hansson@arm.comwithout any special precautions. One exception to this rule occurs when
958703Sandreas.hansson@arm.comextending a type declared in another extension module. Recall the basic example
968703Sandreas.hansson@arm.comfrom Section :ref:`inheritance`.
978703Sandreas.hansson@arm.com
988703Sandreas.hansson@arm.com.. code-block:: cpp
998703Sandreas.hansson@arm.com
10013892Sgabeblack@google.com    py::class_<Pet> pet(m, "Pet");
1018922Swilliam.wang@arm.com    pet.def(py::init<const std::string &>())
1028703Sandreas.hansson@arm.com       .def_readwrite("name", &Pet::name);
10311169Sandreas.hansson@arm.com
1048703Sandreas.hansson@arm.com    py::class_<Dog>(m, "Dog", pet /* <- specify parent */)
10511169Sandreas.hansson@arm.com        .def(py::init<const std::string &>())
1068922Swilliam.wang@arm.com        .def("bark", &Dog::bark);
1078703Sandreas.hansson@arm.com
1088703Sandreas.hansson@arm.comSuppose now that ``Pet`` bindings are defined in a module named ``basic``,
1098703Sandreas.hansson@arm.comwhereas the ``Dog`` bindings are defined somewhere else. The challenge is of
1108703Sandreas.hansson@arm.comcourse that the variable ``pet`` is not available anymore though it is needed
111603SN/Ato indicate the inheritance relationship to the constructor of ``class_<Dog>``.
1122901Ssaidi@eecs.umich.eduHowever, it can be acquired as follows:
1138703Sandreas.hansson@arm.com
1148706Sandreas.hansson@arm.com.. code-block:: cpp
1158706Sandreas.hansson@arm.com
1168706Sandreas.hansson@arm.com    py::object pet = (py::object) py::module::import("basic").attr("Pet");
11711169Sandreas.hansson@arm.com
1188706Sandreas.hansson@arm.com    py::class_<Dog>(m, "Dog", pet)
1198706Sandreas.hansson@arm.com        .def(py::init<const std::string &>())
1208852Sandreas.hansson@arm.com        .def("bark", &Dog::bark);
1218703Sandreas.hansson@arm.com
1228703Sandreas.hansson@arm.comAlternatively, you can specify the base class as a template parameter option to
1238703Sandreas.hansson@arm.com``class_``, which performs an automated lookup of the corresponding Python
1248703Sandreas.hansson@arm.comtype. Like the above code, however, this also requires invoking the ``import``
1258852Sandreas.hansson@arm.comfunction once to ensure that the pybind11 binding code of the module ``basic``
1268703Sandreas.hansson@arm.comhas been executed:
1278922Swilliam.wang@arm.com
1288703Sandreas.hansson@arm.com.. code-block:: cpp
1298703Sandreas.hansson@arm.com
1308703Sandreas.hansson@arm.com    py::module::import("basic");
1318703Sandreas.hansson@arm.com
13213784Sgabeblack@google.com    py::class_<Dog, Pet>(m, "Dog")
13313784Sgabeblack@google.com        .def(py::init<const std::string &>())
1348703Sandreas.hansson@arm.com        .def("bark", &Dog::bark);
1359524SAndreas.Sandberg@ARM.com
1369524SAndreas.Sandberg@ARM.comNaturally, both methods will fail when there are cyclic dependencies.
1379524SAndreas.Sandberg@ARM.com
1389524SAndreas.Sandberg@ARM.comNote that pybind11 code compiled with hidden-by-default symbol visibility (e.g.
1399524SAndreas.Sandberg@ARM.comvia the command line flag ``-fvisibility=hidden`` on GCC/Clang), which is
1409524SAndreas.Sandberg@ARM.comrequired proper pybind11 functionality, can interfere with the ability to
1419524SAndreas.Sandberg@ARM.comaccess types defined in another extension module.  Working around this requires
1429524SAndreas.Sandberg@ARM.commanually exporting types that are accessed by multiple extension modules;
1439524SAndreas.Sandberg@ARM.compybind11 provides a macro to do just this:
1449524SAndreas.Sandberg@ARM.com
1459524SAndreas.Sandberg@ARM.com.. code-block:: cpp
1469524SAndreas.Sandberg@ARM.com
1479524SAndreas.Sandberg@ARM.com    class PYBIND11_EXPORT Dog : public Animal {
1484762Snate@binkert.org        ...
1492901Ssaidi@eecs.umich.edu    };
1509524SAndreas.Sandberg@ARM.com
1519524SAndreas.Sandberg@ARM.comNote also that it is possible (although would rarely be required) to share arbitrary
1529524SAndreas.Sandberg@ARM.comC++ objects between extension modules at runtime. Internal library data is shared
1539524SAndreas.Sandberg@ARM.combetween modules using capsule machinery [#f6]_ which can be also utilized for
1549524SAndreas.Sandberg@ARM.comstoring, modifying and accessing user-defined data. Note that an extension module
1559524SAndreas.Sandberg@ARM.comwill "see" other extensions' data if and only if they were built with the same
1569524SAndreas.Sandberg@ARM.compybind11 version. Consider the following example:
1579524SAndreas.Sandberg@ARM.com
1589524SAndreas.Sandberg@ARM.com.. code-block:: cpp
1599524SAndreas.Sandberg@ARM.com
1609524SAndreas.Sandberg@ARM.com    auto data = (MyData *) py::get_shared_data("mydata");
1619524SAndreas.Sandberg@ARM.com    if (!data)
1629524SAndreas.Sandberg@ARM.com        data = (MyData *) py::set_shared_data("mydata", new MyData(42));
1639524SAndreas.Sandberg@ARM.com
1649524SAndreas.Sandberg@ARM.comIf the above snippet was used in several separately compiled extension modules,
1659524SAndreas.Sandberg@ARM.comthe first one to be imported would create a ``MyData`` instance and associate
1669524SAndreas.Sandberg@ARM.coma ``"mydata"`` key with a pointer to it. Extensions that are imported later
1679524SAndreas.Sandberg@ARM.comwould be then able to access the data behind the same pointer.
1689524SAndreas.Sandberg@ARM.com
1699524SAndreas.Sandberg@ARM.com.. [#f6] https://docs.python.org/3/extending/extending.html#using-capsules
1709524SAndreas.Sandberg@ARM.com
1719524SAndreas.Sandberg@ARM.comModule Destructors
1729524SAndreas.Sandberg@ARM.com==================
1739524SAndreas.Sandberg@ARM.com
1749524SAndreas.Sandberg@ARM.compybind11 does not provide an explicit mechanism to invoke cleanup code at
1759524SAndreas.Sandberg@ARM.commodule destruction time. In rare cases where such functionality is required, it
1769524SAndreas.Sandberg@ARM.comis possible to emulate it using Python capsules or weak references with a
1779524SAndreas.Sandberg@ARM.comdestruction callback.
1789524SAndreas.Sandberg@ARM.com
1799524SAndreas.Sandberg@ARM.com.. code-block:: cpp
1809524SAndreas.Sandberg@ARM.com
1819524SAndreas.Sandberg@ARM.com    auto cleanup_callback = []() {
1829524SAndreas.Sandberg@ARM.com        // perform cleanup here -- this function is called with the GIL held
1839524SAndreas.Sandberg@ARM.com    };
1849524SAndreas.Sandberg@ARM.com
1859524SAndreas.Sandberg@ARM.com    m.add_object("_cleanup", py::capsule(cleanup_callback));
1869524SAndreas.Sandberg@ARM.com
1872901Ssaidi@eecs.umich.eduThis approach has the potential downside that instances of classes exposed
1884762Snate@binkert.orgwithin the module may still be alive when the cleanup callback is invoked
1899524SAndreas.Sandberg@ARM.com(whether this is acceptable will generally depend on the application).
1902901Ssaidi@eecs.umich.edu
1919814Sandreas.hansson@arm.comAlternatively, the capsule may also be stashed within a type object, which
1929814Sandreas.hansson@arm.comensures that it not called before all instances of that type have been
1939814Sandreas.hansson@arm.comcollected:
1949814Sandreas.hansson@arm.com
1959814Sandreas.hansson@arm.com.. code-block:: cpp
1969850Sandreas.hansson@arm.com
1972SN/A    auto cleanup_callback = []() { /* ... */ };
1989850Sandreas.hansson@arm.com    m.attr("BaseClass").attr("_cleanup") = py::capsule(cleanup_callback);
1992SN/A
2002680Sktlim@umich.eduBoth approaches also expose a potentially dangerous ``_cleanup`` attribute in
20111146Smitch.hayenga@arm.comPython, which may be undesirable from an API standpoint (a premature explicit
2021806SN/Acall from Python might lead to undefined behavior). Yet another approach that 
20311005Sandreas.sandberg@arm.comavoids this issue involves weak reference with a cleanup callback:
2045713Shsul@eecs.umich.edu
2055713Shsul@eecs.umich.edu.. code-block:: cpp
2065713Shsul@eecs.umich.edu
2075713Shsul@eecs.umich.edu    // Register a callback function that is invoked when the BaseClass object is colelcted
20812515Sgiacomo.travaglini@arm.com    py::cpp_function cleanup_callback(
209180SN/A        [](py::handle weakref) {
2106029Ssteve.reinhardt@amd.com            // perform cleanup here -- this function is called with the GIL held
2116029Ssteve.reinhardt@amd.com
2126029Ssteve.reinhardt@amd.com            weakref.dec_ref(); // release weak reference
2136029Ssteve.reinhardt@amd.com        }
2148765Sgblack@eecs.umich.edu    );
2158765Sgblack@eecs.umich.edu
2162378SN/A    // Create a weak reference with a cleanup callback and initially leak it
2172378SN/A    (void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
2182520SN/A
2192520SN/A
2208852Sandreas.hansson@arm.comGenerating documentation using Sphinx
2212520SN/A=====================================
2221885SN/A
2231070SN/ASphinx [#f4]_ has the ability to inspect the signatures and documentation
224954SN/Astrings in pybind11-based extension modules to automatically generate beautiful
2251070SN/Adocumentation in a variety formats. The python_example repository [#f5]_ contains a
2261070SN/Asimple example repository which uses this approach.
2271070SN/A
22812262Sandreas.sandberg@arm.comThere are two potential gotchas when using this approach: first, make sure that
22912262Sandreas.sandberg@arm.comthe resulting strings do not contain any :kbd:`TAB` characters, which break the
23012262Sandreas.sandberg@arm.comdocstring parsing routines. You may want to use C++11 raw string literals,
23111838SCurtis.Dunham@arm.comwhich are convenient for multi-line comments. Conveniently, any excess
2321070SN/Aindentation will be automatically be removed by Sphinx. However, for this to
2331070SN/Awork, it is important that all lines are indented consistently, i.e.:
2341070SN/A
2351070SN/A.. code-block:: cpp
2361070SN/A
2371070SN/A    // ok
2381070SN/A    m.def("foo", &foo, R"mydelimiter(
2391070SN/A        The foo function
2407580SAli.Saidi@arm.com
2417580SAli.Saidi@arm.com        Parameters
2427580SAli.Saidi@arm.com        ----------
2437580SAli.Saidi@arm.com    )mydelimiter");
2447580SAli.Saidi@arm.com
2457580SAli.Saidi@arm.com    // *not ok*
2467580SAli.Saidi@arm.com    m.def("foo", &foo, R"mydelimiter(The foo function
2477580SAli.Saidi@arm.com
24810037SARM gem5 Developers        Parameters
24911838SCurtis.Dunham@arm.com        ----------
25011838SCurtis.Dunham@arm.com    )mydelimiter");
25110037SARM gem5 Developers
25210037SARM gem5 DevelopersBy default, pybind11 automatically generates and prepends a signature to the docstring of a function 
25310037SARM gem5 Developersregistered with ``module::def()`` and ``class_::def()``. Sometimes this
25410037SARM gem5 Developersbehavior is not desirable, because you want to provide your own signature or remove 
2554997Sgblack@eecs.umich.eduthe docstring completely to exclude the function from the Sphinx documentation.
25611839SCurtis.Dunham@arm.comThe class ``options`` allows you to selectively suppress auto-generated signatures:
25711839SCurtis.Dunham@arm.com
25811839SCurtis.Dunham@arm.com.. code-block:: cpp
25911839SCurtis.Dunham@arm.com
26011839SCurtis.Dunham@arm.com    PYBIND11_MODULE(example, m) {
26111839SCurtis.Dunham@arm.com        py::options options;
26211839SCurtis.Dunham@arm.com        options.disable_function_signatures();
26311839SCurtis.Dunham@arm.com
26412100SCurtis.Dunham@arm.com        m.def("add", [](int a, int b) { return a + b; }, "A function which adds two numbers");
26512100SCurtis.Dunham@arm.com    }
26612100SCurtis.Dunham@arm.com
2678931Sandreas.hansson@arm.comNote that changes to the settings affect only function bindings created during the 
2688931Sandreas.hansson@arm.comlifetime of the ``options`` instance. When it goes out of scope at the end of the module's init function, 
2698931Sandreas.hansson@arm.comthe default settings are restored to prevent unwanted side effects.
2705795Ssaidi@eecs.umich.edu
2718931Sandreas.hansson@arm.com.. [#f4] http://www.sphinx-doc.org
2725795Ssaidi@eecs.umich.edu.. [#f5] http://github.com/pybind/python_example
2735795Ssaidi@eecs.umich.edu