• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Frequently asked questions
2##########################
3
4"ImportError: dynamic module does not define init function"
5===========================================================
6
71. Make sure that the name specified in PYBIND11_MODULE is identical to the
8filename of the extension library (without suffixes 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).
14
15"Symbol not found: ``__Py_ZeroStruct`` / ``_PyInstanceMethod_Type``"
16========================================================================
17
18See the first answer.
19
20"SystemError: dynamic module not initialized properly"
21======================================================
22
23See the first answer.
24
25The Python interpreter immediately crashes when importing my module
26===================================================================
27
28See the first answer.
29
30.. _faq_reference_arguments:
31
32Limitations involving reference arguments
33=========================================
34
35In C++, it's fairly common to pass arguments using mutable references or
36mutable pointers, which allows both read and write access to the value
37supplied by the caller. This is sometimes done for efficiency reasons, or to
38realize functions that have multiple return values. Here are two very basic
39examples:
40
41.. code-block:: cpp
42
43    void increment(int &i) { i++; }
44    void increment_ptr(int *i) { (*i)++; }
45
46In Python, all arguments are passed by reference, so there is no general
47issue in binding such code from Python.
48
49However, certain basic Python types (like ``str``, ``int``, ``bool``,
50``float``, etc.) are **immutable**. This means that the following attempt
51to port the function to Python doesn't have the same effect on the value
52provided by the caller -- in fact, it does nothing at all.
53
54.. code-block:: python
55
56    def increment(i):
57        i += 1 # nope..
58
59pybind11 is also affected by such language-level conventions, which means that
60binding ``increment`` or ``increment_ptr`` will also create Python functions
61that don't modify their arguments.
62
63Although inconvenient, one workaround is to encapsulate the immutable types in
64a custom type that does allow modifications.
65
66An other alternative involves binding a small wrapper lambda function that
67returns a tuple with all output arguments (see the remainder of the
68documentation for examples on binding lambda functions). An example:
69
70.. code-block:: cpp
71
72    int foo(int &i) { i++; return 123; }
73
74and the binding code
75
76.. code-block:: cpp
77
78   m.def("foo", [](int i) { int rv = foo(i); return std::make_tuple(rv, i); });
79
80
81How can I reduce the build time?
82================================
83
84It's good practice to split binding code over multiple files, as in the
85following example:
86
87:file:`example.cpp`:
88
89.. code-block:: cpp
90
91    void init_ex1(py::module_ &);
92    void init_ex2(py::module_ &);
93    /* ... */
94
95    PYBIND11_MODULE(example, m) {
96        init_ex1(m);
97        init_ex2(m);
98        /* ... */
99    }
100
101:file:`ex1.cpp`:
102
103.. code-block:: cpp
104
105    void init_ex1(py::module_ &m) {
106        m.def("add", [](int a, int b) { return a + b; });
107    }
108
109:file:`ex2.cpp`:
110
111.. code-block:: cpp
112
113    void init_ex2(py::module_ &m) {
114        m.def("sub", [](int a, int b) { return a - b; });
115    }
116
117:command:`python`:
118
119.. code-block:: pycon
120
121    >>> import example
122    >>> example.add(1, 2)
123    3
124    >>> example.sub(1, 1)
125    0
126
127As shown above, the various ``init_ex`` functions should be contained in
128separate files that can be compiled independently from one another, and then
129linked together into the same final shared object.  Following this approach
130will:
131
1321. reduce memory requirements per compilation unit.
133
1342. enable parallel builds (if desired).
135
1363. allow for faster incremental builds. For instance, when a single class
137   definition is changed, only a subset of the binding code will generally need
138   to be recompiled.
139
140"recursive template instantiation exceeded maximum depth of 256"
141================================================================
142
143If you receive an error about excessive recursive template evaluation, try
144specifying a larger value, e.g. ``-ftemplate-depth=1024`` on GCC/Clang. The
145culprit is generally the generation of function signatures at compile time
146using C++14 template metaprogramming.
147
148.. _`faq:hidden_visibility`:
149
150"‘SomeClass’ declared with greater visibility than the type of its field ‘SomeClass::member’ [-Wattributes]"
151============================================================================================================
152
153This error typically indicates that you are compiling without the required
154``-fvisibility`` flag.  pybind11 code internally forces hidden visibility on
155all internal code, but if non-hidden (and thus *exported*) code attempts to
156include a pybind type (for example, ``py::object`` or ``py::list``) you can run
157into this warning.
158
159To avoid it, make sure you are specifying ``-fvisibility=hidden`` when
160compiling pybind code.
161
162As to why ``-fvisibility=hidden`` is necessary, because pybind modules could
163have been compiled under different versions of pybind itself, it is also
164important that the symbols defined in one module do not clash with the
165potentially-incompatible symbols defined in another.  While Python extension
166modules are usually loaded with localized symbols (under POSIX systems
167typically using ``dlopen`` with the ``RTLD_LOCAL`` flag), this Python default
168can be changed, but even if it isn't it is not always enough to guarantee
169complete independence of the symbols involved when not using
170``-fvisibility=hidden``.
171
172Additionally, ``-fvisiblity=hidden`` can deliver considerably binary size
173savings.  (See the following section for more details).
174
175
176.. _`faq:symhidden`:
177
178How can I create smaller binaries?
179==================================
180
181To do its job, pybind11 extensively relies on a programming technique known as
182*template metaprogramming*, which is a way of performing computation at compile
183time using type information. Template metaprogamming usually instantiates code
184involving significant numbers of deeply nested types that are either completely
185removed or reduced to just a few instructions during the compiler's optimization
186phase. However, due to the nested nature of these types, the resulting symbol
187names in the compiled extension library can be extremely long. For instance,
188the included test suite contains the following symbol:
189
190.. only:: html
191
192    .. code-block:: none
193
194        _​_​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​_
195
196.. only:: not html
197
198    .. code-block:: cpp
199
200        __ZN8pybind1112cpp_functionC1Iv8Example2JRNSt3__16vectorINS3_12basic_stringIwNS3_11char_traitsIwEENS3_9allocatorIwEEEENS8_ISA_EEEEEJNS_4nameENS_7siblingENS_9is_methodEA28_cEEEMT0_FT_DpT1_EDpRKT2_
201
202which is the mangled form of the following function type:
203
204.. code-block:: cpp
205
206    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])
207
208The memory needed to store just the mangled name of this function (196 bytes)
209is larger than the actual piece of code (111 bytes) it represents! On the other
210hand, it's silly to even give this function a name -- after all, it's just a
211tiny cog in a bigger piece of machinery that is not exposed to the outside
212world. So we'll generally only want to export symbols for those functions which
213are actually called from the outside.
214
215This can be achieved by specifying the parameter ``-fvisibility=hidden`` to GCC
216and Clang, which sets the default symbol visibility to *hidden*, which has a
217tremendous impact on the final binary size of the resulting extension library.
218(On Visual Studio, symbols are already hidden by default, so nothing needs to
219be done there.)
220
221In addition to decreasing binary size, ``-fvisibility=hidden`` also avoids
222potential serious issues when loading multiple modules and is required for
223proper pybind operation.  See the previous FAQ entry for more details.
224
225Working with ancient Visual Studio 2008 builds on Windows
226=========================================================
227
228The official Windows distributions of Python are compiled using truly
229ancient versions of Visual Studio that lack good C++11 support. Some users
230implicitly assume that it would be impossible to load a plugin built with
231Visual Studio 2015 into a Python distribution that was compiled using Visual
232Studio 2008. However, no such issue exists: it's perfectly legitimate to
233interface DLLs that are built with different compilers and/or C libraries.
234Common gotchas to watch out for involve not ``free()``-ing memory region
235that that were ``malloc()``-ed in another shared library, using data
236structures with incompatible ABIs, and so on. pybind11 is very careful not
237to make these types of mistakes.
238
239How can I properly handle Ctrl-C in long-running functions?
240===========================================================
241
242Ctrl-C is received by the Python interpreter, and holds it until the GIL
243is released, so a long-running function won't be interrupted.
244
245To interrupt from inside your function, you can use the ``PyErr_CheckSignals()``
246function, that will tell if a signal has been raised on the Python side.  This
247function merely checks a flag, so its impact is negligible. When a signal has
248been received, you must either explicitly interrupt execution by throwing
249``py::error_already_set`` (which will propagate the existing
250``KeyboardInterrupt``), or clear the error (which you usually will not want):
251
252.. code-block:: cpp
253
254    PYBIND11_MODULE(example, m)
255    {
256        m.def("long running_func", []()
257        {
258            for (;;) {
259                if (PyErr_CheckSignals() != 0)
260                    throw py::error_already_set();
261                // Long running iteration
262            }
263        });
264    }
265
266CMake doesn't detect the right Python version
267=============================================
268
269The CMake-based build system will try to automatically detect the installed
270version of Python and link against that. When this fails, or when there are
271multiple versions of Python and it finds the wrong one, delete
272``CMakeCache.txt`` and then add ``-DPYTHON_EXECUTABLE=$(which python)`` to your
273CMake configure line. (Replace ``$(which python)`` with a path to python if
274your prefer.)
275
276You can alternatively try ``-DPYBIND11_FINDPYTHON=ON``, which will activate the
277new CMake FindPython support instead of pybind11's custom search. Requires
278CMake 3.12+, and 3.15+ or 3.18.2+ are even better. You can set this in your
279``CMakeLists.txt`` before adding or finding pybind11, as well.
280
281Inconsistent detection of Python version in CMake and pybind11
282==============================================================
283
284The functions ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
285provided by CMake for Python version detection are modified by pybind11 due to
286unreliability and limitations that make them unsuitable for pybind11's needs.
287Instead pybind11 provides its own, more reliable Python detection CMake code.
288Conflicts can arise, however, when using pybind11 in a project that *also* uses
289the CMake Python detection in a system with several Python versions installed.
290
291This difference may cause inconsistencies and errors if *both* mechanisms are
292used in the same project. Consider the following CMake code executed in a
293system with Python 2.7 and 3.x installed:
294
295.. code-block:: cmake
296
297    find_package(PythonInterp)
298    find_package(PythonLibs)
299    find_package(pybind11)
300
301It will detect Python 2.7 and pybind11 will pick it as well.
302
303In contrast this code:
304
305.. code-block:: cmake
306
307    find_package(pybind11)
308    find_package(PythonInterp)
309    find_package(PythonLibs)
310
311will detect Python 3.x for pybind11 and may crash on
312``find_package(PythonLibs)`` afterwards.
313
314There are three possible solutions:
315
3161. Avoid using ``find_package(PythonInterp)`` and ``find_package(PythonLibs)``
317   from CMake and rely on pybind11 in detecting Python version. If this is not
318   possible, the CMake machinery should be called *before* including pybind11.
3192. Set ``PYBIND11_FINDPYTHON`` to ``True`` or use ``find_package(Python
320   COMPONENTS Interpreter Development)`` on modern CMake (3.12+, 3.15+ better,
321   3.18.2+ best). Pybind11 in these cases uses the new CMake FindPython instead
322   of the old, deprecated search tools, and these modules are much better at
323   finding the correct Python.
3243. Set ``PYBIND11_NOPYTHON`` to ``TRUE``. Pybind11 will not search for Python.
325   However, you will have to use the target-based system, and do more setup
326   yourself, because it does not know about or include things that depend on
327   Python, like ``pybind11_add_module``. This might be ideal for integrating
328   into an existing system, like scikit-build's Python helpers.
329
330How to cite this project?
331=========================
332
333We suggest the following BibTeX template to cite pybind11 in scientific
334discourse:
335
336.. code-block:: bash
337
338    @misc{pybind11,
339       author = {Wenzel Jakob and Jason Rhinelander and Dean Moldovan},
340       year = {2017},
341       note = {https://github.com/pybind/pybind11},
342       title = {pybind11 -- Seamless operability between C++11 and Python}
343    }
344