blob: bcbc6b13543a296a076d82912b32bea2f7b811a6 [file] [log] [blame]
Dean Moldovan1fb9df62017-08-18 19:26:49 +02001Upgrade 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
12v2.2
13====
14
15Deprecation of the ``PYBIND11_PLUGIN`` macro
16--------------------------------------------
17
18``PYBIND11_MODULE`` is now the preferred way to create module entry points.
19The old macro emits a compile-time deprecation warning.
20
21.. code-block:: cpp
22
23 // old
24 PYBIND11_PLUGIN(example) {
25 py::module m("example", "documentation string");
26
27 m.def("add", [](int a, int b) { return a + b; });
28
29 return m.ptr();
30 }
31
32 // new
33 PYBIND11_MODULE(example, m) {
34 m.doc() = "documentation string"; // optional
35
36 m.def("add", [](int a, int b) { return a + b; });
37 }
38
39
40Stricter enforcement of hidden symbol visibility for pybind11 modules
41---------------------------------------------------------------------
42
43pybind11 now tries to actively enforce hidden symbol visibility for modules.
44If you're using either one of pybind11's :doc:`CMake or Python build systems
45<compiling>` (the two example repositories) and you haven't been exporting any
46symbols, there's nothing to be concerned about. All the changes have been done
47transparently in the background. If you were building manually or relied on
48specific default visibility, read on.
49
50Setting default symbol visibility to *hidden* has always been recommended for
51pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol
52visibility (in conjunction with the ``strip`` utility) yields much smaller
53module binaries. `CPython's extension docs`_ also recommend hiding symbols
54by default, with the goal of avoiding symbol name clashes between modules.
55Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring
56all symbols inside the ``pybind11`` namespace as hidden and (2) by including
57the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension
58modules, not for embedding the interpreter).
59
60.. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module
61
62The namespace-scope hidden visibility is done automatically in pybind11's
63headers and it's generally transparent to users. It ensures that:
64
65* Modules compiled with different pybind11 versions don't clash with each other.
66
67* Some new features, like ``py::module_local`` bindings, can work as intended.
68
69The ``-fvisibility=hidden`` flag applies the same visibility to user bindings
70outside of the ``pybind11`` namespace. It's now set automatic by pybind11's
71CMake and Python build systems, but this needs to be done manually by users
72of other build systems. Adding this flag:
73
74* Minimizes the chances of symbol conflicts between modules. E.g. if two
75 unrelated modules were statically linked to different (ABI-incompatible)
76 versions of the same third-party library, a symbol clash would be likely
77 (and would end with unpredictable results).
78
79* Produces smaller binaries on Linux and macOS, as pointed out previously.
80
81Within pybind11's CMake build system, ``pybind11_add_module`` has always been
82setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's
83being applied unconditionally, even in debug mode and it can no longer be opted
84out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also
85adds this flag to it's interface. The ``pybind11::embed`` target is unchanged.
86
87The most significant change here is for the ``pybind11::module`` target. If you
88were previously relying on default visibility, i.e. if your Python module was
89doubling as a shared library with dependents, you'll need to either export
90symbols manually (recommended for cross-platform libraries) or factor out the
91shared library (and have the Python module link to it like the other
92dependents). As a temporary workaround, you can also restore default visibility
93using the CMake code below, but this is not recommended in the long run:
94
95.. code-block:: cmake
96
97 target_link_libraries(mymodule PRIVATE pybind11::module)
98
99 add_library(restore_default_visibility INTERFACE)
100 target_compile_options(restore_default_visibility INTERFACE -fvisibility=default)
101 target_link_libraries(mymodule PRIVATE restore_default_visibility)
102
103
104Local STL container bindings
105----------------------------
106
107Previous pybind11 versions could only bind types globally -- all pybind11
108modules, even unrelated ones, would have access to the same exported types.
109However, this would also result in a conflict if two modules exported the
110same C++ type, which is especially problematic for very common types, e.g.
111``std::vector<int>``. :ref:`module_local` were added to resolve this (see
112that section for a complete usage guide).
113
114``py::class_`` still defaults to global bindings (because these types are
115usually unique across modules), however in order to avoid clashes of opaque
116types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers
117as ``py::module_local`` if their elements are: builtins (``int``, ``float``,
118etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For
119example, this change allows multiple modules to bind ``std::vector<int>``
120without causing conflicts. See :ref:`stl_bind` for more details.
121
122When upgrading to this version, if you have multiple modules which depend on
123a single global binding of an STL container, note that all modules can still
124accept foreign ``py::module_local`` types in the direction of Python-to-C++.
125The locality only affects the C++-to-Python direction. If this is needed in
126multiple modules, you'll need to either:
127
128* Add a copy of the same STL binding to all of the modules which need it.
129
130* Restore the global status of that single binding by marking it
131 ``py::module_local(false)``.
132
133The latter is an easy workaround, but in the long run it would be best to
134localize all common type bindings in order to avoid conflicts with
135third-party modules.
136
137
138New syntax for custom constructors
139----------------------------------
140
141The old placement-new custom constructors are still valid, but the new approach
142greatly improves type safety. Placement-new can be called accidentally with an
143incompatible type (without any compiler errors or warnings), or it can initialize
144the same object multiple times if not careful with the Python-side ``__init__``
145calls. The new-style ``py::init()`` custom constructors prevent such mistakes.
146See :ref:`custom_constructors` for details.
147
148.. code-block:: cpp
149
150 // old
151 py::class<Foo>(m, "Foo")
152 .def("__init__", [](Foo &self, ...) {
153 new (&self) Foo(...); // uses placement-new
154 });
155
156 // new
157 py::class<Foo>(m, "Foo")
158 .def(py::init([](...) { // Note: no `self` argument
159 return new Foo(...); // return by raw pointer
160 // or: return std::make_unique<Foo>(...); // return by holder
161 // or: return Foo(...); // return by value (move constructor)
162 }));
163
164
Dean Moldovan1e5a7da2017-08-24 01:53:15 +0200165New syntax for pickling support
166-------------------------------
167
168Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred
169way to get and set object state. See :ref:`pickling` for details.
170
171.. code-block:: cpp
172
173 // old -- deprecated
174 py::class<Foo>(m, "Foo")
175 ...
176 .def("__getstate__", [](const Foo &self) {
177 return py::make_tuple(self.value1(), self.value2(), ...);
178 })
179 .def("__setstate__", [](Foo &self, py::tuple t) {
180 new (&self) Foo(t[0].cast<std::string>(), ...);
181 });
182
183 // new
184 py::class<Foo>(m, "Foo")
185 ...
186 .def(py::pickle(
187 [](const Foo &self) { // __getstate__
188 return py::make_tuple(f.value1(), f.value2(), ...); // unchanged
189 },
190 [](py::tuple t) { // __setstate__, note: no `self` argument
191 return new Foo(t[0].cast<std::string>(), ...);
192 // or: return std::make_unique<Foo>(...); // return by holder
193 // or: return Foo(...); // return by value (move constructor)
194 }
195 ));
196
197
Dean Moldovan1fb9df62017-08-18 19:26:49 +0200198Deprecation of some ``py::object`` APIs
199---------------------------------------
200
201To compare ``py::object`` instances by pointer, you should now use
202``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.
203Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but
204that could be confusing and is now deprecated (so that it can eventually
205be replaced with proper rich object comparison in a future release).
206
207For classes which inherit from ``py::object``, ``borrowed`` and ``stolen``
208were previously available as protected constructor tags. Now the types
209should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``
210(`#771 <https://github.com/pybind/pybind11/pull/771>`_).
211
212
213v2.1
214====
215
216Minimum compiler versions are enforced at compile time
217------------------------------------------------------
218
219The minimums also apply to v2.0 but the check is now explicit and a compile-time
220error is raised if the compiler does not meet the requirements:
221
222* GCC >= 4.8
223* clang >= 3.3 (appleclang >= 5.0)
224* MSVC >= 2015u3
225* Intel C++ >= 15.0
226
227
228The ``py::metaclass`` attribute is not required for static properties
229---------------------------------------------------------------------
230
231Binding classes with static properties is now possible by default. The
232zero-parameter version of ``py::metaclass()`` is deprecated. However, a new
233one-parameter ``py::metaclass(python_type)`` version was added for rare
234cases when a custom metaclass is needed to override pybind11's default.
235
236.. code-block:: cpp
237
238 // old -- emits a deprecation warning
239 py::class_<Foo>(m, "Foo", py::metaclass())
240 .def_property_readonly_static("foo", ...);
241
242 // new -- static properties work without the attribute
243 py::class_<Foo>(m, "Foo")
244 .def_property_readonly_static("foo", ...);
245
246 // new -- advanced feature, override pybind11's default metaclass
247 py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type))
248 ...
249
250
251v2.0
252====
253
254Breaking changes in ``py::class_``
255----------------------------------
256
257These changes were necessary to make type definitions in pybind11
258future-proof, to support PyPy via its ``cpyext`` mechanism (`#527
259<https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency
260(`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).
261
2621. Declarations of types that provide access via the buffer protocol must
263 now include the ``py::buffer_protocol()`` annotation as an argument to
264 the ``py::class_`` constructor.
265
266 .. code-block:: cpp
267
268 py::class_<Matrix>("Matrix", py::buffer_protocol())
269 .def(py::init<...>())
270 .def_buffer(...);
271
2722. Classes which include static properties (e.g. ``def_readwrite_static()``)
273 must now include the ``py::metaclass()`` attribute. Note: this requirement
274 has since been removed in v2.1. If you're upgrading from 1.x, it's
275 recommended to skip directly to v2.1 or newer.
276
2773. This version of pybind11 uses a redesigned mechanism for instantiating
278 trampoline classes that are used to override virtual methods from within
279 Python. This led to the following user-visible syntax change:
280
281 .. code-block:: cpp
282
283 // old v1.x syntax
284 py::class_<TrampolineClass>("MyClass")
285 .alias<MyClass>()
286 ...
287
288 // new v2.x syntax
289 py::class_<MyClass, TrampolineClass>("MyClass")
290 ...
291
292 Importantly, both the original and the trampoline class are now specified
293 as arguments to the ``py::class_`` template, and the ``alias<..>()`` call
294 is gone. The new scheme has zero overhead in cases when Python doesn't
295 override any functions of the underlying C++ class.
296 `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.
297
298 The class type must be the first template argument given to ``py::class_``
299 while the trampoline can be mixed in arbitrary order with other arguments
300 (see the following section).
301
302
303Deprecation of the ``py::base<T>()`` attribute
304----------------------------------------------
305
306``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template
307argument to ``py::class_``. This new syntax also supports multiple inheritance.
308Note that, while the type being exported must be the first argument in the
309``py::class_<Class, ...>`` template, the order of the following types (bases,
310holder and/or trampoline) is not important.
311
312.. code-block:: cpp
313
314 // old v1.x
315 py::class_<Derived>("Derived", py::base<Base>());
316
317 // new v2.x
318 py::class_<Derived, Base>("Derived");
319
320 // new -- multiple inheritance
321 py::class_<Derived, Base1, Base2>("Derived");
322
323 // new -- apart from `Derived` the argument order can be arbitrary
324 py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived");
325
326
327Out-of-the-box support for ``std::shared_ptr``
328----------------------------------------------
329
330The relevant type caster is now built in, so it's no longer necessary to
331include a declaration of the form:
332
333.. code-block:: cpp
334
335 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
336
337Continuing to do so won’t cause an error or even a deprecation warning,
338but it's completely redundant.
339
340
341Deprecation of a few ``py::object`` APIs
342----------------------------------------
343
344All of the old-style calls emit deprecation warnings.
345
346+---------------------------------------+---------------------------------------------+
347| Old syntax | New syntax |
348+=======================================+=============================================+
349| ``obj.call(args...)`` | ``obj(args...)`` |
350+---------------------------------------+---------------------------------------------+
351| ``obj.str()`` | ``py::str(obj)`` |
352+---------------------------------------+---------------------------------------------+
353| ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` |
354+---------------------------------------+---------------------------------------------+
355| ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` |
356+---------------------------------------+---------------------------------------------+
357| ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` |
358+---------------------------------------+---------------------------------------------+
359| ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` |
360+---------------------------------------+---------------------------------------------+
361| ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` |
362+---------------------------------------+---------------------------------------------+