blob: 99a12cb31e280352b8404db4f46a5b48ce605763 [file] [log] [blame]
Wenzel Jakobde623a72016-03-09 21:11:19 +01001Frequently asked questions
2##########################
3
Wenzel Jakobc62360d2016-05-03 14:32:47 +02004"ImportError: dynamic module does not define init function"
5===========================================================
Wenzel Jakob50ed3612016-04-11 17:38:25 +02006
Ahuva Kroizer8f5b7fc2018-11-13 14:25:57 +020071. Make sure that the name specified in PYBIND11_MODULE is identical to the
8filename of the extension library (without prefixes such as .so)
9
102. If the above did not fix the issue, you are likely using an incompatible
11version of Python (for instance, the extension library was compiled against
12Python 2, while the interpreter is running on top of some version of Python
133, or vice versa).
Wenzel Jakobc62360d2016-05-03 14:32:47 +020014
15"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
16========================================================================
17
Dean Moldovan443ab592017-04-24 01:51:44 +020018See the first answer.
Wenzel Jakobc62360d2016-05-03 14:32:47 +020019
Wenzel Jakob70f5a4d2016-09-05 17:19:18 +090020"SystemError: dynamic module not initialized properly"
21======================================================
22
Dean Moldovan443ab592017-04-24 01:51:44 +020023See the first answer.
Wenzel Jakob70f5a4d2016-09-05 17:19:18 +090024
Wenzel Jakobc62360d2016-05-03 14:32:47 +020025The Python interpreter immediately crashes when importing my module
26===================================================================
27
Dean Moldovan443ab592017-04-24 01:51:44 +020028See the first answer.
Wenzel Jakob50ed3612016-04-11 17:38:25 +020029
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020030CMake doesn't detect the right Python version
31=============================================
Wenzel Jakoba439cca2016-05-17 10:47:52 +020032
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020033The CMake-based build system will try to automatically detect the installed
34version of Python and link against that. When this fails, or when there are
35multiple versions of Python and it finds the wrong one, delete
36``CMakeCache.txt`` and then invoke CMake as follows:
Wenzel Jakoba439cca2016-05-17 10:47:52 +020037
38.. code-block:: bash
39
Wenzel Jakobf600c1d2016-06-03 14:47:54 +020040 cmake -DPYTHON_EXECUTABLE:FILEPATH=<path-to-python-executable> .
Wenzel Jakoba439cca2016-05-17 10:47:52 +020041
Wenzel Jakobde623a72016-03-09 21:11:19 +010042Limitations involving reference arguments
43=========================================
44
45In C++, it's fairly common to pass arguments using mutable references or
46mutable pointers, which allows both read and write access to the value
47supplied by the caller. This is sometimes done for efficiency reasons, or to
48realize functions that have multiple return values. Here are two very basic
49examples:
50
51.. code-block:: cpp
52
53 void increment(int &i) { i++; }
54 void increment_ptr(int *i) { (*i)++; }
55
56In Python, all arguments are passed by reference, so there is no general
57issue in binding such code from Python.
58
59However, certain basic Python types (like ``str``, ``int``, ``bool``,
60``float``, etc.) are **immutable**. This means that the following attempt
61to port the function to Python doesn't have the same effect on the value
62provided by the caller -- in fact, it does nothing at all.
63
64.. code-block:: python
65
66 def increment(i):
67 i += 1 # nope..
68
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010069pybind11 is also affected by such language-level conventions, which means that
70binding ``increment`` or ``increment_ptr`` will also create Python functions
71that don't modify their arguments.
Wenzel Jakobde623a72016-03-09 21:11:19 +010072
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010073Although inconvenient, one workaround is to encapsulate the immutable types in
Wenzel Jakob2e03a582016-04-14 11:27:15 +020074a custom type that does allow modifications.
Wenzel Jakob4a48afb2016-03-09 21:31:21 +010075
76An other alternative involves binding a small wrapper lambda function that
77returns a tuple with all output arguments (see the remainder of the
78documentation for examples on binding lambda functions). An example:
79
80.. code-block:: cpp
81
82 int foo(int &i) { i++; return 123; }
83
84and the binding code
85
86.. code-block:: cpp
87
88 m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
89
Wenzel Jakob2e03a582016-04-14 11:27:15 +020090
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020091How can I reduce the build time?
92================================
93
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -040094It's good practice to split binding code over multiple files, as in the
95following example:
96
97:file:`example.cpp`:
Wenzel Jakobc79dbe42016-04-17 21:54:31 +020098
99.. code-block:: cpp
100
101 void init_ex1(py::module &);
102 void init_ex2(py::module &);
103 /* ... */
104
Dean Moldovan443ab592017-04-24 01:51:44 +0200105 PYBIND11_MODULE(example, m) {
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200106 init_ex1(m);
107 init_ex2(m);
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200108 /* ... */
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200109 }
110
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -0400111:file:`ex1.cpp`:
112
113.. code-block:: cpp
114
115 void init_ex1(py::module &m) {
116 m.def("add", [](int a, int b) { return a + b; });
117 }
118
119:file:`ex2.cpp`:
120
121.. code-block:: cpp
122
David Caron307ea6b2018-04-24 10:16:18 -0400123 void init_ex2(py::module &m) {
Jason Rhinelanderfb7c9fd2016-10-22 12:54:33 -0400124 m.def("sub", [](int a, int b) { return a - b; });
125 }
126
127:command:`python`:
128
129.. code-block:: pycon
130
131 >>> import example
132 >>> example.add(1, 2)
133 3
134 >>> example.sub(1, 1)
135 0
136
137As shown above, the various ``init_ex`` functions should be contained in
138separate files that can be compiled independently from one another, and then
139linked together into the same final shared object. Following this approach
140will:
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200141
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001421. reduce memory requirements per compilation unit.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200143
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001442. enable parallel builds (if desired).
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200145
Wenzel Jakobf64feaf2016-04-28 14:33:45 +02001463. allow for faster incremental builds. For instance, when a single class
Jason Rhinelander20ef6262016-09-21 13:39:02 -0400147 definition is changed, only a subset of the binding code will generally need
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200148 to be recompiled.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200149
Wenzel Jakob2fb5f1d2016-11-16 17:36:54 +0100150"recursive template instantiation exceeded maximum depth of 256"
151================================================================
152
153If you receive an error about excessive recursive template evaluation, try
154specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
155culprit is generally the generation of function signatures at compile time
156using C++14 template metaprogramming.
157
Jason Rhinelander97aa54f2017-08-10 12:08:42 -0400158.. _`faq:hidden_visibility`:
159
160"‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
161============================================================================================================
162
163This error typically indicates that you are compiling without the required
164``-fvisibility`` flag. pybind11 code internally forces hidden visibility on
165all internal code, but if non-hidden (and thus *exported*) code attempts to
166include a pybind type (for example, ``py::object`` or ``py::list``) you can run
167into this warning.
168
169To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
170compiling pybind code.
171
172As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
173have been compiled under different versions of pybind itself, it is also
174important that the symbols defined in one module do not clash with the
175potentially-incompatible symbols defined in another. While Python extension
176modules are usually loaded with localized symbols (under POSIX systems
177typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
178can be changed, but even if it isn't it is not always enough to guarantee
179complete independence of the symbols involved when not using
180``-fvisibility=hidden``.
181
182Additionally, ``-fvisiblity=hidden`` can deliver considerably binary size
183savings. (See the following section for more details).
184
Wenzel Jakob2fb5f1d2016-11-16 17:36:54 +0100185
Lori A. Burns5cafc992016-12-13 10:55:38 -0500186.. _`faq:symhidden`:
187
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200188How can I create smaller binaries?
189==================================
190
191To do its job, pybind11 extensively relies on a programming technique known as
192*template metaprogramming*, which is a way of performing computation at compile
193time using type information. Template metaprogamming usually instantiates code
194involving significant numbers of deeply nested types that are either completely
Jason Rhinelander20ef6262016-09-21 13:39:02 -0400195removed or reduced to just a few instructions during the compiler's optimization
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200196phase. However, due to the nested nature of these types, the resulting symbol
197names in the compiled extension library can be extremely long. For instance,
198the included test suite contains the following symbol:
199
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200200.. only:: html
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200201
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200202 .. code-block:: none
203
Wenzel Jakobfe342412016-09-06 13:02:29 +0900204 _​_​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​_
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200205
206.. only:: not html
207
208 .. code-block:: cpp
209
210 __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200211
212which is the mangled form of the following function type:
213
214.. code-block:: cpp
215
216 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])
217
Wenzel Jakobf64feaf2016-04-28 14:33:45 +0200218The memory needed to store just the mangled name of this function (196 bytes)
219is larger than the actual piece of code (111 bytes) it represents! On the other
220hand, it's silly to even give this function a name -- after all, it's just a
221tiny cog in a bigger piece of machinery that is not exposed to the outside
222world. So we'll generally only want to export symbols for those functions which
223are actually called from the outside.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200224
225This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
Jason Rhinelander97aa54f2017-08-10 12:08:42 -0400226and Clang, which sets the default symbol visibility to *hidden*, which has a
227tremendous impact on the final binary size of the resulting extension library.
228(On Visual Studio, symbols are already hidden by default, so nothing needs to
229be done there.)
230
231In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
232potential serious issues when loading multiple modules and is required for
233proper pybind operation. See the previous FAQ entry for more details.
Wenzel Jakobc79dbe42016-04-17 21:54:31 +0200234
Marc Schlaichab003db2018-02-06 16:07:27 +0100235Working with ancient Visual Studio 2008 builds on Windows
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200236=========================================================
237
238The official Windows distributions of Python are compiled using truly
239ancient versions of Visual Studio that lack good C++11 support. Some users
240implicitly assume that it would be impossible to load a plugin built with
241Visual Studio 2015 into a Python distribution that was compiled using Visual
Marc Schlaichab003db2018-02-06 16:07:27 +0100242Studio 2008. However, no such issue exists: it's perfectly legitimate to
Wenzel Jakobc62360d2016-05-03 14:32:47 +0200243interface DLLs that are built with different compilers and/or C libraries.
244Common gotchas to watch out for involve not ``free()``-ing memory region
245that that were ``malloc()``-ed in another shared library, using data
246structures with incompatible ABIs, and so on. pybind11 is very careful not
247to make these types of mistakes.
Wenzel Jakobe7d304f2017-11-17 18:44:20 +0100248
Semen Yesylevskyyef13fb22018-09-12 01:20:56 +0300249Inconsistent detection of Python version in CMake and pybind11
250==============================================================
251
252The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` provided by CMake
253for Python version detection are not used by pybind11 due to unreliability and limitations that make
254them unsuitable for pybind11's needs. Instead pybind provides its own, more reliable Python detection
255CMake code. Conflicts can arise, however, when using pybind11 in a project that *also* uses the CMake
256Python detection in a system with several Python versions installed.
257
258This difference may cause inconsistencies and errors if *both* mechanisms are used in the same project. Consider the following
259Cmake code executed in a system with Python 2.7 and 3.x installed:
260
261.. code-block:: cmake
262
263 find_package(PythonInterp)
264 find_package(PythonLibs)
265 find_package(pybind11)
266
267It will detect Python 2.7 and pybind11 will pick it as well.
268
269In contrast this code:
270
271.. code-block:: cmake
272
273 find_package(pybind11)
274 find_package(PythonInterp)
275 find_package(PythonLibs)
276
277will detect Python 3.x for pybind11 and may crash on ``find_package(PythonLibs)`` afterwards.
278
279It is advised to avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)`` from CMake and rely
280on pybind11 in detecting Python version. If this is not possible CMake machinery should be called *before* including pybind11.
281
Wenzel Jakobe7d304f2017-11-17 18:44:20 +0100282How to cite this project?
283=========================
284
285We suggest the following BibTeX template to cite pybind11 in scientific
286discourse:
287
288.. code-block:: bash
289
290 @misc{pybind11,
291 author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
292 year = {2017},
293 note = {https://github.com/pybind/pybind11},
294 title = {pybind11 -- Seamless operability between C++11 and Python}
295 }