• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Upgrade guide
2#############
3
4This is a companion guide to the :doc:`changelog`. While the changelog briefly
5lists all of the new features, improvements and bug fixes, this upgrade guide
6focuses only the subset which directly impacts your experience when upgrading
7to a new version. But it goes into more detail. This includes things like
8deprecated APIs and their replacements, build system changes, general code
9modernization and other useful information.
10
11.. _upgrade-guide-2.6:
12
13v2.6
14====
15
16Usage of the ``PYBIND11_OVERLOAD*`` macros and ``get_overload`` function should
17be replaced by ``PYBIND11_OVERRIDE*`` and ``get_override``. In the future, the
18old macros may be deprecated and removed.
19
20``py::module`` has been renamed ``py::module_``, but a backward compatible
21typedef has been included. This change was to avoid a language change in C++20
22that requires unqualified ``module`` not be placed at the start of a logical
23line. Qualified usage is unaffected and the typedef will remain unless the
24C++ language rules change again.
25
26The public constructors of ``py::module_`` have been deprecated. Use
27``PYBIND11_MODULE`` or ``module_::create_extension_module`` instead.
28
29An error is now thrown when ``__init__`` is forgotten on subclasses. This was
30incorrect before, but was not checked. Add a call to ``__init__`` if it is
31missing.
32
33A ``py::type_error`` is now thrown when casting to a subclass (like
34``py::bytes`` from ``py::object``) if the conversion is not valid. Make a valid
35conversion instead.
36
37The undocumented ``h.get_type()`` method has been deprecated and replaced by
38``py::type::of(h)``.
39
40Enums now have a ``__str__`` method pre-defined; if you want to override it,
41the simplest fix is to add the new ``py::prepend()`` tag when defining
42``"__str__"``.
43
44If ``__eq__`` defined but not ``__hash__``, ``__hash__`` is now set to
45``None``, as in normal CPython. You should add ``__hash__`` if you intended the
46class to be hashable, possibly using the new ``py::hash`` shortcut.
47
48The constructors for ``py::array`` now always take signed integers for size,
49for consistency. This may lead to compiler warnings on some systems. Cast to
50``py::ssize_t`` instead of ``std::size_t``.
51
52The ``tools/clang`` submodule and ``tools/mkdoc.py`` have been moved to a
53standalone package, `pybind11-mkdoc`_. If you were using those tools, please
54use them via a pip install from the new location.
55
56The ``pybind11`` package on PyPI no longer fills the wheel "headers" slot - if
57you were using the headers from this slot, they are available by requesting the
58``global`` extra, that is, ``pip install "pybind11[global]"``. (Most users will
59be unaffected, as the ``pybind11/include`` location is reported by ``python -m
60pybind11 --includes`` and ``pybind11.get_include()`` is still correct and has
61not changed since 2.5).
62
63.. _pybind11-mkdoc: https://github.com/pybind/pybind11-mkdoc
64
65CMake support:
66--------------
67
68The minimum required version of CMake is now 3.4.  Several details of the CMake
69support have been deprecated; warnings will be shown if you need to change
70something. The changes are:
71
72* ``PYBIND11_CPP_STANDARD=<platform-flag>`` is deprecated, please use
73  ``CMAKE_CXX_STANDARD=<number>`` instead, or any other valid CMake CXX or CUDA
74  standard selection method, like ``target_compile_features``.
75
76* If you do not request a standard, pybind11 targets will compile with the
77  compiler default, but not less than C++11, instead of forcing C++14 always.
78  If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14 CACHE STRING "")``
79  instead.
80
81* Direct ``pybind11::module`` usage should always be accompanied by at least
82  ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to
83  manually force this compiler flag (but not correctly on all compilers or with
84  CUDA).
85
86* ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing;
87  linking now behaves like other imported libraries consistently in both
88  config and submodule mode, and behaves like a ``SYSTEM`` library by
89  default.
90
91* If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``,
92  ``virtualenv``, and ``conda``) are prioritized over the standard search
93  (similar to the new FindPython mode).
94
95In addition, the following changes may be of interest:
96
97* ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by
98  ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or
99  ``pybind11::thin_lto``.
100
101* Using ``find_package(Python COMPONENTS Interpreter Development)`` before
102  pybind11 will cause pybind11 to use the new Python mechanisms instead of its
103  own custom search, based on a patched version of classic ``FindPythonInterp``
104  / ``FindPythonLibs``. In the future, this may become the default. A recent
105  (3.15+ or 3.18.2+) version of CMake is recommended.
106
107
108
109v2.5
110====
111
112The Python package now includes the headers as data in the package itself, as
113well as in the "headers" wheel slot. ``pybind11 --includes`` and
114``pybind11.get_include()`` report the new location, which is always correct
115regardless of how pybind11 was installed, making the old ``user=`` argument
116meaningless. If you are not using the function to get the location already, you
117are encouraged to switch to the package location.
118
119
120v2.2
121====
122
123Deprecation of the ``PYBIND11_PLUGIN`` macro
124--------------------------------------------
125
126``PYBIND11_MODULE`` is now the preferred way to create module entry points.
127The old macro emits a compile-time deprecation warning.
128
129.. code-block:: cpp
130
131    // old
132    PYBIND11_PLUGIN(example) {
133        py::module m("example", "documentation string");
134
135        m.def("add", [](int a, int b) { return a + b; });
136
137        return m.ptr();
138    }
139
140    // new
141    PYBIND11_MODULE(example, m) {
142        m.doc() = "documentation string"; // optional
143
144        m.def("add", [](int a, int b) { return a + b; });
145    }
146
147
148New API for defining custom constructors and pickling functions
149---------------------------------------------------------------
150
151The old placement-new custom constructors have been deprecated. The new approach
152uses ``py::init()`` and factory functions to greatly improve type safety.
153
154Placement-new can be called accidentally with an incompatible type (without any
155compiler errors or warnings), or it can initialize the same object multiple times
156if not careful with the Python-side ``__init__`` calls. The new-style custom
157constructors prevent such mistakes. See :ref:`custom_constructors` for details.
158
159.. code-block:: cpp
160
161    // old -- deprecated (runtime warning shown only in debug mode)
162    py::class<Foo>(m, "Foo")
163        .def("__init__", [](Foo &self, ...) {
164            new (&self) Foo(...); // uses placement-new
165        });
166
167    // new
168    py::class<Foo>(m, "Foo")
169        .def(py::init([](...) { // Note: no `self` argument
170            return new Foo(...); // return by raw pointer
171            // or: return std::make_unique<Foo>(...); // return by holder
172            // or: return Foo(...); // return by value (move constructor)
173        }));
174
175Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred
176way to get and set object state. See :ref:`pickling` for details.
177
178.. code-block:: cpp
179
180    // old -- deprecated (runtime warning shown only in debug mode)
181    py::class<Foo>(m, "Foo")
182        ...
183        .def("__getstate__", [](const Foo &self) {
184            return py::make_tuple(self.value1(), self.value2(), ...);
185        })
186        .def("__setstate__", [](Foo &self, py::tuple t) {
187            new (&self) Foo(t[0].cast<std::string>(), ...);
188        });
189
190    // new
191    py::class<Foo>(m, "Foo")
192        ...
193        .def(py::pickle(
194            [](const Foo &self) { // __getstate__
195                return py::make_tuple(self.value1(), self.value2(), ...); // unchanged
196            },
197            [](py::tuple t) { // __setstate__, note: no `self` argument
198                return new Foo(t[0].cast<std::string>(), ...);
199                // or: return std::make_unique<Foo>(...); // return by holder
200                // or: return Foo(...); // return by value (move constructor)
201            }
202        ));
203
204For both the constructors and pickling, warnings are shown at module
205initialization time (on import, not when the functions are called).
206They're only visible when compiled in debug mode. Sample warning:
207
208.. code-block:: none
209
210    pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__'
211    which has been deprecated. See the upgrade guide in pybind11's docs.
212
213
214Stricter enforcement of hidden symbol visibility for pybind11 modules
215---------------------------------------------------------------------
216
217pybind11 now tries to actively enforce hidden symbol visibility for modules.
218If you're using either one of pybind11's :doc:`CMake or Python build systems
219<compiling>` (the two example repositories) and you haven't been exporting any
220symbols, there's nothing to be concerned about. All the changes have been done
221transparently in the background. If you were building manually or relied on
222specific default visibility, read on.
223
224Setting default symbol visibility to *hidden* has always been recommended for
225pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol
226visibility (in conjunction with the ``strip`` utility) yields much smaller
227module binaries. `CPython's extension docs`_ also recommend hiding symbols
228by default, with the goal of avoiding symbol name clashes between modules.
229Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring
230all symbols inside the ``pybind11`` namespace as hidden and (2) by including
231the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension
232modules, not for embedding the interpreter).
233
234.. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module
235
236The namespace-scope hidden visibility is done automatically in pybind11's
237headers and it's generally transparent to users. It ensures that:
238
239* Modules compiled with different pybind11 versions don't clash with each other.
240
241* Some new features, like ``py::module_local`` bindings, can work as intended.
242
243The ``-fvisibility=hidden`` flag applies the same visibility to user bindings
244outside of the ``pybind11`` namespace. It's now set automatic by pybind11's
245CMake and Python build systems, but this needs to be done manually by users
246of other build systems. Adding this flag:
247
248* Minimizes the chances of symbol conflicts between modules. E.g. if two
249  unrelated modules were statically linked to different (ABI-incompatible)
250  versions of the same third-party library, a symbol clash would be likely
251  (and would end with unpredictable results).
252
253* Produces smaller binaries on Linux and macOS, as pointed out previously.
254
255Within pybind11's CMake build system, ``pybind11_add_module`` has always been
256setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's
257being applied unconditionally, even in debug mode and it can no longer be opted
258out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also
259adds this flag to it's interface. The ``pybind11::embed`` target is unchanged.
260
261The most significant change here is for the ``pybind11::module`` target. If you
262were previously relying on default visibility, i.e. if your Python module was
263doubling as a shared library with dependents, you'll need to either export
264symbols manually (recommended for cross-platform libraries) or factor out the
265shared library (and have the Python module link to it like the other
266dependents). As a temporary workaround, you can also restore default visibility
267using the CMake code below, but this is not recommended in the long run:
268
269.. code-block:: cmake
270
271    target_link_libraries(mymodule PRIVATE pybind11::module)
272
273    add_library(restore_default_visibility INTERFACE)
274    target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
275    target_link_libraries(mymodule PRIVATE restore_default_visibility)
276
277
278Local STL container bindings
279----------------------------
280
281Previous pybind11 versions could only bind types globally -- all pybind11
282modules, even unrelated ones, would have access to the same exported types.
283However, this would also result in a conflict if two modules exported the
284same C++ type, which is especially problematic for very common types, e.g.
285``std::vector<int>``. :ref:`module_local` were added to resolve this (see
286that section for a complete usage guide).
287
288``py::class_`` still defaults to global bindings (because these types are
289usually unique across modules), however in order to avoid clashes of opaque
290types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers
291as ``py::module_local`` if their elements are: builtins (``int``, ``float``,
292etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For
293example, this change allows multiple modules to bind ``std::vector<int>``
294without causing conflicts. See :ref:`stl_bind` for more details.
295
296When upgrading to this version, if you have multiple modules which depend on
297a single global binding of an STL container, note that all modules can still
298accept foreign  ``py::module_local`` types in the direction of Python-to-C++.
299The locality only affects the C++-to-Python direction. If this is needed in
300multiple modules, you'll need to either:
301
302* Add a copy of the same STL binding to all of the modules which need it.
303
304* Restore the global status of that single binding by marking it
305  ``py::module_local(false)``.
306
307The latter is an easy workaround, but in the long run it would be best to
308localize all common type bindings in order to avoid conflicts with
309third-party modules.
310
311
312Negative strides for Python buffer objects and numpy arrays
313-----------------------------------------------------------
314
315Support for negative strides required changing the integer type from unsigned
316to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you
317have compiler warnings enabled, you may notice some new conversion warnings
318after upgrading. These can be resolved using ``static_cast``.
319
320
321Deprecation of some ``py::object`` APIs
322---------------------------------------
323
324To compare ``py::object`` instances by pointer, you should now use
325``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.
326Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but
327that could be confusing and is now deprecated (so that it can eventually
328be replaced with proper rich object comparison in a future release).
329
330For classes which inherit from ``py::object``, ``borrowed`` and ``stolen``
331were previously available as protected constructor tags. Now the types
332should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``
333(`#771 <https://github.com/pybind/pybind11/pull/771>`_).
334
335
336Stricter compile-time error checking
337------------------------------------
338
339Some error checks have been moved from run time to compile time. Notably,
340automatic conversion of ``std::shared_ptr<T>`` is not possible when ``T`` is
341not directly registered with ``py::class_<T>`` (e.g. ``std::shared_ptr<int>``
342or ``std::shared_ptr<std::vector<T>>`` are not automatically convertible).
343Attempting to bind a function with such arguments now results in a compile-time
344error instead of waiting to fail at run time.
345
346``py::init<...>()`` constructor definitions are also stricter and now prevent
347bindings which could cause unexpected behavior:
348
349.. code-block:: cpp
350
351    struct Example {
352        Example(int &);
353    };
354
355    py::class_<Example>(m, "Example")
356        .def(py::init<int &>()); // OK, exact match
357        // .def(py::init<int>()); // compile-time error, mismatch
358
359A non-``const`` lvalue reference is not allowed to bind to an rvalue. However,
360note that a constructor taking ``const T &`` can still be registered using
361``py::init<T>()`` because a ``const`` lvalue reference can bind to an rvalue.
362
363v2.1
364====
365
366Minimum compiler versions are enforced at compile time
367------------------------------------------------------
368
369The minimums also apply to v2.0 but the check is now explicit and a compile-time
370error is raised if the compiler does not meet the requirements:
371
372* GCC >= 4.8
373* clang >= 3.3 (appleclang >= 5.0)
374* MSVC >= 2015u3
375* Intel C++ >= 15.0
376
377
378The ``py::metaclass`` attribute is not required for static properties
379---------------------------------------------------------------------
380
381Binding classes with static properties is now possible by default. The
382zero-parameter version of ``py::metaclass()`` is deprecated. However, a new
383one-parameter ``py::metaclass(python_type)`` version was added for rare
384cases when a custom metaclass is needed to override pybind11's default.
385
386.. code-block:: cpp
387
388    // old -- emits a deprecation warning
389    py::class_<Foo>(m, "Foo", py::metaclass())
390        .def_property_readonly_static("foo", ...);
391
392    // new -- static properties work without the attribute
393    py::class_<Foo>(m, "Foo")
394        .def_property_readonly_static("foo", ...);
395
396    // new -- advanced feature, override pybind11's default metaclass
397    py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type))
398        ...
399
400
401v2.0
402====
403
404Breaking changes in ``py::class_``
405----------------------------------
406
407These changes were necessary to make type definitions in pybind11
408future-proof, to support PyPy via its ``cpyext`` mechanism (`#527
409<https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency
410(`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).
411
4121. Declarations of types that provide access via the buffer protocol must
413   now include the ``py::buffer_protocol()`` annotation as an argument to
414   the ``py::class_`` constructor.
415
416   .. code-block:: cpp
417
418       py::class_<Matrix>("Matrix", py::buffer_protocol())
419           .def(py::init<...>())
420           .def_buffer(...);
421
4222. Classes which include static properties (e.g. ``def_readwrite_static()``)
423   must now include the ``py::metaclass()`` attribute. Note: this requirement
424   has since been removed in v2.1. If you're upgrading from 1.x, it's
425   recommended to skip directly to v2.1 or newer.
426
4273. This version of pybind11 uses a redesigned mechanism for instantiating
428   trampoline classes that are used to override virtual methods from within
429   Python. This led to the following user-visible syntax change:
430
431   .. code-block:: cpp
432
433       // old v1.x syntax
434       py::class_<TrampolineClass>("MyClass")
435           .alias<MyClass>()
436           ...
437
438       // new v2.x syntax
439       py::class_<MyClass, TrampolineClass>("MyClass")
440           ...
441
442   Importantly, both the original and the trampoline class are now specified
443   as arguments to the ``py::class_`` template, and the ``alias<..>()`` call
444   is gone. The new scheme has zero overhead in cases when Python doesn't
445   override any functions of the underlying C++ class.
446   `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.
447
448   The class type must be the first template argument given to ``py::class_``
449   while the trampoline can be mixed in arbitrary order with other arguments
450   (see the following section).
451
452
453Deprecation of the ``py::base<T>()`` attribute
454----------------------------------------------
455
456``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template
457argument to ``py::class_``. This new syntax also supports multiple inheritance.
458Note that, while the type being exported must be the first argument in the
459``py::class_<Class, ...>`` template, the order of the following types (bases,
460holder and/or trampoline) is not important.
461
462.. code-block:: cpp
463
464    // old v1.x
465    py::class_<Derived>("Derived", py::base<Base>());
466
467    // new v2.x
468    py::class_<Derived, Base>("Derived");
469
470    // new -- multiple inheritance
471    py::class_<Derived, Base1, Base2>("Derived");
472
473    // new -- apart from `Derived` the argument order can be arbitrary
474    py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived");
475
476
477Out-of-the-box support for ``std::shared_ptr``
478----------------------------------------------
479
480The relevant type caster is now built in, so it's no longer necessary to
481include a declaration of the form:
482
483.. code-block:: cpp
484
485    PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
486
487Continuing to do so won’t cause an error or even a deprecation warning,
488but it's completely redundant.
489
490
491Deprecation of a few ``py::object`` APIs
492----------------------------------------
493
494All of the old-style calls emit deprecation warnings.
495
496+---------------------------------------+---------------------------------------------+
497|  Old syntax                           |  New syntax                                 |
498+=======================================+=============================================+
499| ``obj.call(args...)``                 | ``obj(args...)``                            |
500+---------------------------------------+---------------------------------------------+
501| ``obj.str()``                         | ``py::str(obj)``                            |
502+---------------------------------------+---------------------------------------------+
503| ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)``           |
504+---------------------------------------+---------------------------------------------+
505| ``py::object(ptr, true)``             | ``py::reinterpret_borrow<py::object>(ptr)`` |
506+---------------------------------------+---------------------------------------------+
507| ``py::object(ptr, false)``            | ``py::reinterpret_steal<py::object>(ptr)``  |
508+---------------------------------------+---------------------------------------------+
509| ``if (obj.attr("foo"))``              | ``if (py::hasattr(obj, "foo"))``            |
510+---------------------------------------+---------------------------------------------+
511| ``if (obj["bar"])``                   | ``if (obj.contains("bar"))``                |
512+---------------------------------------+---------------------------------------------+
513