blob: 2fe8470b791f2f25556f97e6a8c8fa0400942fe6 [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
165Deprecation of some ``py::object`` APIs
166---------------------------------------
167
168To compare ``py::object`` instances by pointer, you should now use
169``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python.
170Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but
171that could be confusing and is now deprecated (so that it can eventually
172be replaced with proper rich object comparison in a future release).
173
174For classes which inherit from ``py::object``, ``borrowed`` and ``stolen``
175were previously available as protected constructor tags. Now the types
176should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}``
177(`#771 <https://github.com/pybind/pybind11/pull/771>`_).
178
179
180v2.1
181====
182
183Minimum compiler versions are enforced at compile time
184------------------------------------------------------
185
186The minimums also apply to v2.0 but the check is now explicit and a compile-time
187error is raised if the compiler does not meet the requirements:
188
189* GCC >= 4.8
190* clang >= 3.3 (appleclang >= 5.0)
191* MSVC >= 2015u3
192* Intel C++ >= 15.0
193
194
195The ``py::metaclass`` attribute is not required for static properties
196---------------------------------------------------------------------
197
198Binding classes with static properties is now possible by default. The
199zero-parameter version of ``py::metaclass()`` is deprecated. However, a new
200one-parameter ``py::metaclass(python_type)`` version was added for rare
201cases when a custom metaclass is needed to override pybind11's default.
202
203.. code-block:: cpp
204
205 // old -- emits a deprecation warning
206 py::class_<Foo>(m, "Foo", py::metaclass())
207 .def_property_readonly_static("foo", ...);
208
209 // new -- static properties work without the attribute
210 py::class_<Foo>(m, "Foo")
211 .def_property_readonly_static("foo", ...);
212
213 // new -- advanced feature, override pybind11's default metaclass
214 py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type))
215 ...
216
217
218v2.0
219====
220
221Breaking changes in ``py::class_``
222----------------------------------
223
224These changes were necessary to make type definitions in pybind11
225future-proof, to support PyPy via its ``cpyext`` mechanism (`#527
226<https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency
227(`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_).
228
2291. Declarations of types that provide access via the buffer protocol must
230 now include the ``py::buffer_protocol()`` annotation as an argument to
231 the ``py::class_`` constructor.
232
233 .. code-block:: cpp
234
235 py::class_<Matrix>("Matrix", py::buffer_protocol())
236 .def(py::init<...>())
237 .def_buffer(...);
238
2392. Classes which include static properties (e.g. ``def_readwrite_static()``)
240 must now include the ``py::metaclass()`` attribute. Note: this requirement
241 has since been removed in v2.1. If you're upgrading from 1.x, it's
242 recommended to skip directly to v2.1 or newer.
243
2443. This version of pybind11 uses a redesigned mechanism for instantiating
245 trampoline classes that are used to override virtual methods from within
246 Python. This led to the following user-visible syntax change:
247
248 .. code-block:: cpp
249
250 // old v1.x syntax
251 py::class_<TrampolineClass>("MyClass")
252 .alias<MyClass>()
253 ...
254
255 // new v2.x syntax
256 py::class_<MyClass, TrampolineClass>("MyClass")
257 ...
258
259 Importantly, both the original and the trampoline class are now specified
260 as arguments to the ``py::class_`` template, and the ``alias<..>()`` call
261 is gone. The new scheme has zero overhead in cases when Python doesn't
262 override any functions of the underlying C++ class.
263 `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_.
264
265 The class type must be the first template argument given to ``py::class_``
266 while the trampoline can be mixed in arbitrary order with other arguments
267 (see the following section).
268
269
270Deprecation of the ``py::base<T>()`` attribute
271----------------------------------------------
272
273``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template
274argument to ``py::class_``. This new syntax also supports multiple inheritance.
275Note that, while the type being exported must be the first argument in the
276``py::class_<Class, ...>`` template, the order of the following types (bases,
277holder and/or trampoline) is not important.
278
279.. code-block:: cpp
280
281 // old v1.x
282 py::class_<Derived>("Derived", py::base<Base>());
283
284 // new v2.x
285 py::class_<Derived, Base>("Derived");
286
287 // new -- multiple inheritance
288 py::class_<Derived, Base1, Base2>("Derived");
289
290 // new -- apart from `Derived` the argument order can be arbitrary
291 py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived");
292
293
294Out-of-the-box support for ``std::shared_ptr``
295----------------------------------------------
296
297The relevant type caster is now built in, so it's no longer necessary to
298include a declaration of the form:
299
300.. code-block:: cpp
301
302 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>)
303
304Continuing to do so won’t cause an error or even a deprecation warning,
305but it's completely redundant.
306
307
308Deprecation of a few ``py::object`` APIs
309----------------------------------------
310
311All of the old-style calls emit deprecation warnings.
312
313+---------------------------------------+---------------------------------------------+
314| Old syntax | New syntax |
315+=======================================+=============================================+
316| ``obj.call(args...)`` | ``obj(args...)`` |
317+---------------------------------------+---------------------------------------------+
318| ``obj.str()`` | ``py::str(obj)`` |
319+---------------------------------------+---------------------------------------------+
320| ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` |
321+---------------------------------------+---------------------------------------------+
322| ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` |
323+---------------------------------------+---------------------------------------------+
324| ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` |
325+---------------------------------------+---------------------------------------------+
326| ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` |
327+---------------------------------------+---------------------------------------------+
328| ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` |
329+---------------------------------------+---------------------------------------------+