blob: 5ad7c2981f4a34b0230a9eb5447c5962798a6ced [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 Moldovan4c540442017-08-30 21:53:08 +0200204Negative strides for Python buffer objects and numpy arrays
205-----------------------------------------------------------
206
207Support for negative strides required changing the integer type from unsigned
208to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you
209have compiler warnings enabled, you may notice some new conversion warnings
210after upgrading. These can be resolved using ``static_cast``.
211
212
Dean Moldovan1fb9df62017-08-18 19:26:49 +0200213Deprecation of some ``py::object`` APIs
214---------------------------------------
215
216To compare ``py::object`` instances by pointer, you should now use
217``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.
218Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but
219that could be confusing and is now deprecated (so that it can eventually
220be replaced with proper rich object comparison in a future release).
221
222For classes which inherit from ``py::object``, ``borrowed`` and ``stolen``
223were previously available as protected constructor tags. Now the types
224should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``
225(`#771 <https://github.com/pybind/pybind11/pull/771>`_).
226
227
228v2.1
229====
230
231Minimum compiler versions are enforced at compile time
232------------------------------------------------------
233
234The minimums also apply to v2.0 but the check is now explicit and a compile-time
235error is raised if the compiler does not meet the requirements:
236
237* GCC >= 4.8
238* clang >= 3.3 (appleclang >= 5.0)
239* MSVC >= 2015u3
240* Intel C++ >= 15.0
241
242
243The ``py::metaclass`` attribute is not required for static properties
244---------------------------------------------------------------------
245
246Binding classes with static properties is now possible by default. The
247zero-parameter version of ``py::metaclass()`` is deprecated. However, a new
248one-parameter ``py::metaclass(python_type)`` version was added for rare
249cases when a custom metaclass is needed to override pybind11's default.
250
251.. code-block:: cpp
252
253 // old -- emits a deprecation warning
254 py::class_<Foo>(m, "Foo", py::metaclass())
255 .def_property_readonly_static("foo", ...);
256
257 // new -- static properties work without the attribute
258 py::class_<Foo>(m, "Foo")
259 .def_property_readonly_static("foo", ...);
260
261 // new -- advanced feature, override pybind11's default metaclass
262 py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type))
263 ...
264
265
266v2.0
267====
268
269Breaking changes in ``py::class_``
270----------------------------------
271
272These changes were necessary to make type definitions in pybind11
273future-proof, to support PyPy via its ``cpyext`` mechanism (`#527
274<https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency
275(`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).
276
2771. Declarations of types that provide access via the buffer protocol must
278 now include the ``py::buffer_protocol()`` annotation as an argument to
279 the ``py::class_`` constructor.
280
281 .. code-block:: cpp
282
283 py::class_<Matrix>("Matrix", py::buffer_protocol())
284 .def(py::init<...>())
285 .def_buffer(...);
286
2872. Classes which include static properties (e.g. ``def_readwrite_static()``)
288 must now include the ``py::metaclass()`` attribute. Note: this requirement
289 has since been removed in v2.1. If you're upgrading from 1.x, it's
290 recommended to skip directly to v2.1 or newer.
291
2923. This version of pybind11 uses a redesigned mechanism for instantiating
293 trampoline classes that are used to override virtual methods from within
294 Python. This led to the following user-visible syntax change:
295
296 .. code-block:: cpp
297
298 // old v1.x syntax
299 py::class_<TrampolineClass>("MyClass")
300 .alias<MyClass>()
301 ...
302
303 // new v2.x syntax
304 py::class_<MyClass, TrampolineClass>("MyClass")
305 ...
306
307 Importantly, both the original and the trampoline class are now specified
308 as arguments to the ``py::class_`` template, and the ``alias<..>()`` call
309 is gone. The new scheme has zero overhead in cases when Python doesn't
310 override any functions of the underlying C++ class.
311 `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.
312
313 The class type must be the first template argument given to ``py::class_``
314 while the trampoline can be mixed in arbitrary order with other arguments
315 (see the following section).
316
317
318Deprecation of the ``py::base<T>()`` attribute
319----------------------------------------------
320
321``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template
322argument to ``py::class_``. This new syntax also supports multiple inheritance.
323Note that, while the type being exported must be the first argument in the
324``py::class_<Class, ...>`` template, the order of the following types (bases,
325holder and/or trampoline) is not important.
326
327.. code-block:: cpp
328
329 // old v1.x
330 py::class_<Derived>("Derived", py::base<Base>());
331
332 // new v2.x
333 py::class_<Derived, Base>("Derived");
334
335 // new -- multiple inheritance
336 py::class_<Derived, Base1, Base2>("Derived");
337
338 // new -- apart from `Derived` the argument order can be arbitrary
339 py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived");
340
341
342Out-of-the-box support for ``std::shared_ptr``
343----------------------------------------------
344
345The relevant type caster is now built in, so it's no longer necessary to
346include a declaration of the form:
347
348.. code-block:: cpp
349
350 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
351
352Continuing to do so wont cause an error or even a deprecation warning,
353but it's completely redundant.
354
355
356Deprecation of a few ``py::object`` APIs
357----------------------------------------
358
359All of the old-style calls emit deprecation warnings.
360
361+---------------------------------------+---------------------------------------------+
362| Old syntax | New syntax |
363+=======================================+=============================================+
364| ``obj.call(args...)`` | ``obj(args...)`` |
365+---------------------------------------+---------------------------------------------+
366| ``obj.str()`` | ``py::str(obj)`` |
367+---------------------------------------+---------------------------------------------+
368| ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` |
369+---------------------------------------+---------------------------------------------+
370| ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` |
371+---------------------------------------+---------------------------------------------+
372| ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` |
373+---------------------------------------+---------------------------------------------+
374| ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` |
375+---------------------------------------+---------------------------------------------+
376| ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` |
377+---------------------------------------+---------------------------------------------+