faq.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. Frequently asked questions
  2. ##########################
  3. "ImportError: dynamic module does not define init function"
  4. ===========================================================
  5. You are likely using an incompatible version of Python (for instance, the
  6. extension library was compiled against Python 2, while the interpreter is
  7. running on top of some version of Python 3, or vice versa).
  8. "Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
  9. ========================================================================
  10. See the first answer.
  11. "SystemError: dynamic module not initialized properly"
  12. ======================================================
  13. See the first answer.
  14. The Python interpreter immediately crashes when importing my module
  15. ===================================================================
  16. See the first answer.
  17. CMake doesn't detect the right Python version
  18. =============================================
  19. The CMake-based build system will try to automatically detect the installed
  20. version of Python and link against that. When this fails, or when there are
  21. multiple versions of Python and it finds the wrong one, delete
  22. ``CMakeCache.txt`` and then invoke CMake as follows:
  23. .. code-block:: bash
  24. cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
  25. Limitations involving reference arguments
  26. =========================================
  27. In C++, it's fairly common to pass arguments using mutable references or
  28. mutable pointers, which allows both read and write access to the value
  29. supplied by the caller. This is sometimes done for efficiency reasons, or to
  30. realize functions that have multiple return values. Here are two very basic
  31. examples:
  32. .. code-block:: cpp
  33. void increment(int &i) { i++; }
  34. void increment_ptr(int *i) { (*i)++; }
  35. In Python, all arguments are passed by reference, so there is no general
  36. issue in binding such code from Python.
  37. However, certain basic Python types (like ``str``, ``int``, ``bool``,
  38. ``float``, etc.) are **immutable**. This means that the following attempt
  39. to port the function to Python doesn't have the same effect on the value
  40. provided by the caller -- in fact, it does nothing at all.
  41. .. code-block:: python
  42. def increment(i):
  43. i += 1 # nope..
  44. pybind11 is also affected by such language-level conventions, which means that
  45. binding ``increment`` or ``increment_ptr`` will also create Python functions
  46. that don't modify their arguments.
  47. Although inconvenient, one workaround is to encapsulate the immutable types in
  48. a custom type that does allow modifications.
  49. An other alternative involves binding a small wrapper lambda function that
  50. returns a tuple with all output arguments (see the remainder of the
  51. documentation for examples on binding lambda functions). An example:
  52. .. code-block:: cpp
  53. int foo(int &i) { i++; return 123; }
  54. and the binding code
  55. .. code-block:: cpp
  56. m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
  57. How can I reduce the build time?
  58. ================================
  59. It's good practice to split binding code over multiple files, as in the
  60. following example:
  61. :file:`example.cpp`:
  62. .. code-block:: cpp
  63. void init_ex1(py::module &);
  64. void init_ex2(py::module &);
  65. /* ... */
  66. PYBIND11_MODULE(example, m) {
  67. init_ex1(m);
  68. init_ex2(m);
  69. /* ... */
  70. }
  71. :file:`ex1.cpp`:
  72. .. code-block:: cpp
  73. void init_ex1(py::module &m) {
  74. m.def("add", [](int a, int b) { return a + b; });
  75. }
  76. :file:`ex2.cpp`:
  77. .. code-block:: cpp
  78. void init_ex2(py::module &m) {
  79. m.def("sub", [](int a, int b) { return a - b; });
  80. }
  81. :command:`python`:
  82. .. code-block:: pycon
  83. >>> import example
  84. >>> example.add(1, 2)
  85. 3
  86. >>> example.sub(1, 1)
  87. 0
  88. As shown above, the various ``init_ex`` functions should be contained in
  89. separate files that can be compiled independently from one another, and then
  90. linked together into the same final shared object. Following this approach
  91. will:
  92. 1. reduce memory requirements per compilation unit.
  93. 2. enable parallel builds (if desired).
  94. 3. allow for faster incremental builds. For instance, when a single class
  95. definition is changed, only a subset of the binding code will generally need
  96. to be recompiled.
  97. "recursive template instantiation exceeded maximum depth of 256"
  98. ================================================================
  99. If you receive an error about excessive recursive template evaluation, try
  100. specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
  101. culprit is generally the generation of function signatures at compile time
  102. using C++14 template metaprogramming.
  103. .. _`faq:hidden_visibility`:
  104. "‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
  105. ============================================================================================================
  106. This error typically indicates that you are compiling without the required
  107. ``-fvisibility`` flag. pybind11 code internally forces hidden visibility on
  108. all internal code, but if non-hidden (and thus *exported*) code attempts to
  109. include a pybind type (for example, ``py::object`` or ``py::list``) you can run
  110. into this warning.
  111. To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
  112. compiling pybind code.
  113. As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
  114. have been compiled under different versions of pybind itself, it is also
  115. important that the symbols defined in one module do not clash with the
  116. potentially-incompatible symbols defined in another. While Python extension
  117. modules are usually loaded with localized symbols (under POSIX systems
  118. typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
  119. can be changed, but even if it isn't it is not always enough to guarantee
  120. complete independence of the symbols involved when not using
  121. ``-fvisibility=hidden``.
  122. Additionally, ``-fvisiblity=hidden`` can deliver considerably binary size
  123. savings. (See the following section for more details).
  124. .. _`faq:symhidden`:
  125. How can I create smaller binaries?
  126. ==================================
  127. To do its job, pybind11 extensively relies on a programming technique known as
  128. *template metaprogramming*, which is a way of performing computation at compile
  129. time using type information. Template metaprogamming usually instantiates code
  130. involving significant numbers of deeply nested types that are either completely
  131. removed or reduced to just a few instructions during the compiler's optimization
  132. phase. However, due to the nested nature of these types, the resulting symbol
  133. names in the compiled extension library can be extremely long. For instance,
  134. the included test suite contains the following symbol:
  135. .. only:: html
  136. .. code-block:: none
  137. _​_​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​_
  138. .. only:: not html
  139. .. code-block:: cpp
  140. __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
  141. which is the mangled form of the following function type:
  142. .. code-block:: cpp
  143. 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])
  144. The memory needed to store just the mangled name of this function (196 bytes)
  145. is larger than the actual piece of code (111 bytes) it represents! On the other
  146. hand, it's silly to even give this function a name -- after all, it's just a
  147. tiny cog in a bigger piece of machinery that is not exposed to the outside
  148. world. So we'll generally only want to export symbols for those functions which
  149. are actually called from the outside.
  150. This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
  151. and Clang, which sets the default symbol visibility to *hidden*, which has a
  152. tremendous impact on the final binary size of the resulting extension library.
  153. (On Visual Studio, symbols are already hidden by default, so nothing needs to
  154. be done there.)
  155. In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
  156. potential serious issues when loading multiple modules and is required for
  157. proper pybind operation. See the previous FAQ entry for more details.
  158. Another aspect that can require a fair bit of code are function signature
  159. descriptions. pybind11 automatically generates human-readable function
  160. signatures for docstrings, e.g.:
  161. .. code-block:: none
  162. | __init__(...)
  163. | __init__(*args, **kwargs)
  164. | Overloaded function.
  165. |
  166. | 1. __init__(example.Example1) -> NoneType
  167. |
  168. | Docstring for overload #1 goes here
  169. |
  170. | 2. __init__(example.Example1, int) -> NoneType
  171. |
  172. | Docstring for overload #2 goes here
  173. |
  174. | 3. __init__(example.Example1, example.Example1) -> NoneType
  175. |
  176. | Docstring for overload #3 goes here
  177. In C++11 mode, these are generated at run time using string concatenation,
  178. which can amount to 10-20% of the size of the resulting binary. If you can,
  179. enable C++14 language features (using ``-std=c++14`` for GCC/Clang), in which
  180. case signatures are efficiently pre-generated at compile time. Unfortunately,
  181. Visual Studio's C++14 support (``constexpr``) is not good enough as of April
  182. 2016, so it always uses the more expensive run-time approach.
  183. Working with ancient Visual Studio 2009 builds on Windows
  184. =========================================================
  185. The official Windows distributions of Python are compiled using truly
  186. ancient versions of Visual Studio that lack good C++11 support. Some users
  187. implicitly assume that it would be impossible to load a plugin built with
  188. Visual Studio 2015 into a Python distribution that was compiled using Visual
  189. Studio 2009. However, no such issue exists: it's perfectly legitimate to
  190. interface DLLs that are built with different compilers and/or C libraries.
  191. Common gotchas to watch out for involve not ``free()``-ing memory region
  192. that that were ``malloc()``-ed in another shared library, using data
  193. structures with incompatible ABIs, and so on. pybind11 is very careful not
  194. to make these types of mistakes.
  195. How to cite this project?
  196. =========================
  197. We suggest the following BibTeX template to cite pybind11 in scientific
  198. discourse:
  199. .. code-block:: bash
  200. @misc{pybind11,
  201. author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
  202. year = {2017},
  203. note = {https://github.com/pybind/pybind11},
  204. title = {pybind11 -- Seamless operability between C++11 and Python}
  205. }