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