Blame external/pybind11/docs/faq.rst

Packit 534379
Frequently asked questions
Packit 534379
##########################
Packit 534379
Packit 534379
"ImportError: dynamic module does not define init function"
Packit 534379
===========================================================
Packit 534379
Packit 534379
1. Make sure that the name specified in PYBIND11_MODULE is identical to the
Packit 534379
filename of the extension library (without prefixes such as .so)
Packit 534379
Packit 534379
2. If the above did not fix the issue, you are likely using an incompatible
Packit 534379
version of Python (for instance, the extension library was compiled against
Packit 534379
Python 2, while the interpreter is running on top of some version of Python
Packit 534379
3, or vice versa).
Packit 534379
Packit 534379
"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
Packit 534379
========================================================================
Packit 534379
Packit 534379
See the first answer.
Packit 534379
Packit 534379
"SystemError: dynamic module not initialized properly"
Packit 534379
======================================================
Packit 534379
Packit 534379
See the first answer.
Packit 534379
Packit 534379
The Python interpreter immediately crashes when importing my module
Packit 534379
===================================================================
Packit 534379
Packit 534379
See the first answer.
Packit 534379
Packit 534379
CMake doesn't detect the right Python version
Packit 534379
=============================================
Packit 534379
Packit 534379
The CMake-based build system will try to automatically detect the installed
Packit 534379
version of Python and link against that. When this fails, or when there are
Packit 534379
multiple versions of Python and it finds the wrong one, delete
Packit 534379
``CMakeCache.txt`` and then invoke CMake as follows:
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
Packit 534379
Packit 534379
.. _faq_reference_arguments:
Packit 534379
Packit 534379
Limitations involving reference arguments
Packit 534379
=========================================
Packit 534379
Packit 534379
In C++, it's fairly common to pass arguments using mutable references or
Packit 534379
mutable pointers, which allows both read and write access to the value
Packit 534379
supplied by the caller. This is sometimes done for efficiency reasons, or to
Packit 534379
realize functions that have multiple return values. Here are two very basic
Packit 534379
examples:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    void increment(int &i) { i++; }
Packit 534379
    void increment_ptr(int *i) { (*i)++; }
Packit 534379
Packit 534379
In Python, all arguments are passed by reference, so there is no general
Packit 534379
issue in binding such code from Python.
Packit 534379
Packit 534379
However, certain basic Python types (like ``str``, ``int``, ``bool``,
Packit 534379
``float``, etc.) are **immutable**. This means that the following attempt
Packit 534379
to port the function to Python doesn't have the same effect on the value
Packit 534379
provided by the caller -- in fact, it does nothing at all.
Packit 534379
Packit 534379
.. code-block:: python
Packit 534379
Packit 534379
    def increment(i):
Packit 534379
        i += 1 # nope..
Packit 534379
Packit 534379
pybind11 is also affected by such language-level conventions, which means that
Packit 534379
binding ``increment`` or ``increment_ptr`` will also create Python functions
Packit 534379
that don't modify their arguments.
Packit 534379
Packit 534379
Although inconvenient, one workaround is to encapsulate the immutable types in
Packit 534379
a custom type that does allow modifications.
Packit 534379
Packit 534379
An other alternative involves binding a small wrapper lambda function that
Packit 534379
returns a tuple with all output arguments (see the remainder of the
Packit 534379
documentation for examples on binding lambda functions). An example:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    int foo(int &i) { i++; return 123; }
Packit 534379
Packit 534379
and the binding code
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
   m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
Packit 534379
Packit 534379
Packit 534379
How can I reduce the build time?
Packit 534379
================================
Packit 534379
Packit 534379
It's good practice to split binding code over multiple files, as in the
Packit 534379
following example:
Packit 534379
Packit 534379
:file:`example.cpp`:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    void init_ex1(py::module &);
Packit 534379
    void init_ex2(py::module &);
Packit 534379
    /* ... */
Packit 534379
Packit 534379
    PYBIND11_MODULE(example, m) {
Packit 534379
        init_ex1(m);
Packit 534379
        init_ex2(m);
Packit 534379
        /* ... */
Packit 534379
    }
Packit 534379
Packit 534379
:file:`ex1.cpp`:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    void init_ex1(py::module &m) {
Packit 534379
        m.def("add", [](int a, int b) { return a + b; });
Packit 534379
    }
Packit 534379
Packit 534379
:file:`ex2.cpp`:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    void init_ex2(py::module &m) {
Packit 534379
        m.def("sub", [](int a, int b) { return a - b; });
Packit 534379
    }
Packit 534379
Packit 534379
:command:`python`:
Packit 534379
Packit 534379
.. code-block:: pycon
Packit 534379
Packit 534379
    >>> import example
Packit 534379
    >>> example.add(1, 2)
Packit 534379
    3
Packit 534379
    >>> example.sub(1, 1)
Packit 534379
    0
Packit 534379
Packit 534379
As shown above, the various ``init_ex`` functions should be contained in
Packit 534379
separate files that can be compiled independently from one another, and then
Packit 534379
linked together into the same final shared object.  Following this approach
Packit 534379
will:
Packit 534379
Packit 534379
1. reduce memory requirements per compilation unit.
Packit 534379
Packit 534379
2. enable parallel builds (if desired).
Packit 534379
Packit 534379
3. allow for faster incremental builds. For instance, when a single class
Packit 534379
   definition is changed, only a subset of the binding code will generally need
Packit 534379
   to be recompiled.
Packit 534379
Packit 534379
"recursive template instantiation exceeded maximum depth of 256"
Packit 534379
================================================================
Packit 534379
Packit 534379
If you receive an error about excessive recursive template evaluation, try
Packit 534379
specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
Packit 534379
culprit is generally the generation of function signatures at compile time
Packit 534379
using C++14 template metaprogramming.
Packit 534379
Packit 534379
.. _`faq:hidden_visibility`:
Packit 534379
Packit 534379
"‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
Packit 534379
============================================================================================================
Packit 534379
Packit 534379
This error typically indicates that you are compiling without the required
Packit 534379
``-fvisibility`` flag.  pybind11 code internally forces hidden visibility on
Packit 534379
all internal code, but if non-hidden (and thus *exported*) code attempts to
Packit 534379
include a pybind type (for example, ``py::object`` or ``py::list``) you can run
Packit 534379
into this warning.
Packit 534379
Packit 534379
To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
Packit 534379
compiling pybind code.
Packit 534379
Packit 534379
As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
Packit 534379
have been compiled under different versions of pybind itself, it is also
Packit 534379
important that the symbols defined in one module do not clash with the
Packit 534379
potentially-incompatible symbols defined in another.  While Python extension
Packit 534379
modules are usually loaded with localized symbols (under POSIX systems
Packit 534379
typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
Packit 534379
can be changed, but even if it isn't it is not always enough to guarantee
Packit 534379
complete independence of the symbols involved when not using
Packit 534379
``-fvisibility=hidden``.
Packit 534379
Packit 534379
Additionally, ``-fvisiblity=hidden`` can deliver considerably binary size
Packit 534379
savings.  (See the following section for more details).
Packit 534379
Packit 534379
Packit 534379
.. _`faq:symhidden`:
Packit 534379
Packit 534379
How can I create smaller binaries?
Packit 534379
==================================
Packit 534379
Packit 534379
To do its job, pybind11 extensively relies on a programming technique known as
Packit 534379
*template metaprogramming*, which is a way of performing computation at compile
Packit 534379
time using type information. Template metaprogamming usually instantiates code
Packit 534379
involving significant numbers of deeply nested types that are either completely
Packit 534379
removed or reduced to just a few instructions during the compiler's optimization
Packit 534379
phase. However, due to the nested nature of these types, the resulting symbol
Packit 534379
names in the compiled extension library can be extremely long. For instance,
Packit 534379
the included test suite contains the following symbol:
Packit 534379
Packit 534379
.. only:: html
Packit 534379
Packit 534379
    .. code-block:: none
Packit 534379
Packit 534379
        _​_​Z​N​8​p​y​b​i​n​d​1​1​1​2​c​p​p​_​f​u​n​c​t​i​o​n​C​1​I​v​8​E​x​a​m​p​l​e​2​J​R​N​S​t​3​_​_​1​6​v​e​c​t​o​r​I​N​S​3​_​1​2​b​a​s​i​c​_​s​t​r​i​n​g​I​w​N​S​3​_​1​1​c​h​a​r​_​t​r​a​i​t​s​I​w​E​E​N​S​3​_​9​a​l​l​o​c​a​t​o​r​I​w​E​E​E​E​N​S​8​_​I​S​A​_​E​E​E​E​E​J​N​S​_​4​n​a​m​e​E​N​S​_​7​s​i​b​l​i​n​g​E​N​S​_​9​i​s​_​m​e​t​h​o​d​E​A​2​8​_​c​E​E​E​M​T​0​_​F​T​_​D​p​T​1​_​E​D​p​R​K​T​2​_
Packit 534379
Packit 534379
.. only:: not html
Packit 534379
Packit 534379
    .. code-block:: cpp
Packit 534379
Packit 534379
        __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
Packit 534379
Packit 534379
which is the mangled form of the following function type:
Packit 534379
Packit 534379
.. code-block:: cpp
Packit 534379
Packit 534379
    pybind11::cpp_function::cpp_function<void, Example2, std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&, pybind11::name, pybind11::sibling, pybind11::is_method, char [28]>(void (Example2::*)(std::__1::vector<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> >, std::__1::allocator<std::__1::basic_string<wchar_t, std::__1::char_traits<wchar_t>, std::__1::allocator<wchar_t> > > >&), pybind11::name const&, pybind11::sibling const&, pybind11::is_method const&, char const (&) [28])
Packit 534379
Packit 534379
The memory needed to store just the mangled name of this function (196 bytes)
Packit 534379
is larger than the actual piece of code (111 bytes) it represents! On the other
Packit 534379
hand, it's silly to even give this function a name -- after all, it's just a
Packit 534379
tiny cog in a bigger piece of machinery that is not exposed to the outside
Packit 534379
world. So we'll generally only want to export symbols for those functions which
Packit 534379
are actually called from the outside.
Packit 534379
Packit 534379
This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
Packit 534379
and Clang, which sets the default symbol visibility to *hidden*, which has a
Packit 534379
tremendous impact on the final binary size of the resulting extension library.
Packit 534379
(On Visual Studio, symbols are already hidden by default, so nothing needs to
Packit 534379
be done there.)
Packit 534379
Packit 534379
In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
Packit 534379
potential serious issues when loading multiple modules and is required for
Packit 534379
proper pybind operation.  See the previous FAQ entry for more details.
Packit 534379
Packit 534379
Working with ancient Visual Studio 2008 builds on Windows
Packit 534379
=========================================================
Packit 534379
Packit 534379
The official Windows distributions of Python are compiled using truly
Packit 534379
ancient versions of Visual Studio that lack good C++11 support. Some users
Packit 534379
implicitly assume that it would be impossible to load a plugin built with
Packit 534379
Visual Studio 2015 into a Python distribution that was compiled using Visual
Packit 534379
Studio 2008. However, no such issue exists: it's perfectly legitimate to
Packit 534379
interface DLLs that are built with different compilers and/or C libraries.
Packit 534379
Common gotchas to watch out for involve not ``free()``-ing memory region
Packit 534379
that that were ``malloc()``-ed in another shared library, using data
Packit 534379
structures with incompatible ABIs, and so on. pybind11 is very careful not
Packit 534379
to make these types of mistakes.
Packit 534379
Packit 534379
Inconsistent detection of Python version in CMake and pybind11
Packit 534379
==============================================================
Packit 534379
Packit 534379
The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` provided by CMake
Packit 534379
for Python version detection are not used by pybind11 due to unreliability and limitations that make
Packit 534379
them unsuitable for pybind11's needs. Instead pybind provides its own, more reliable Python detection
Packit 534379
CMake code. Conflicts can arise, however, when using pybind11 in a project that *also* uses the CMake
Packit 534379
Python detection in a system with several Python versions installed.
Packit 534379
Packit 534379
This difference may cause inconsistencies and errors if *both* mechanisms are used in the same project. Consider the following
Packit 534379
Cmake code executed in a system with Python 2.7 and 3.x installed:
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    find_package(PythonInterp)
Packit 534379
    find_package(PythonLibs)
Packit 534379
    find_package(pybind11)
Packit 534379
Packit 534379
It will detect Python 2.7 and pybind11 will pick it as well.
Packit 534379
Packit 534379
In contrast this code:
Packit 534379
Packit 534379
.. code-block:: cmake
Packit 534379
Packit 534379
    find_package(pybind11)
Packit 534379
    find_package(PythonInterp)
Packit 534379
    find_package(PythonLibs)
Packit 534379
Packit 534379
will detect Python 3.x for pybind11 and may crash on ``find_package(PythonLibs)`` afterwards.
Packit 534379
Packit 534379
It is advised to avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` from CMake and rely
Packit 534379
on pybind11 in detecting Python version. If this is not possible CMake machinery should be called *before* including pybind11.
Packit 534379
Packit 534379
How to cite this project?
Packit 534379
=========================
Packit 534379
Packit 534379
We suggest the following BibTeX template to cite pybind11 in scientific
Packit 534379
discourse:
Packit 534379
Packit 534379
.. code-block:: bash
Packit 534379
Packit 534379
    @misc{pybind11,
Packit 534379
       author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
Packit 534379
       year = {2017},
Packit 534379
       note = {https://github.com/pybind/pybind11},
Packit 534379
       title = {pybind11 -- Seamless operability between C++11 and Python}
Packit 534379
    }