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 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 40New 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 106Stricter 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 204Negative 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 213Deprecation 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 228Stricter compile-time error checking 229------------------------------------ 230 231Some error checks have been moved from run time to compile time. Notably, 232automatic conversion of ``std::shared_ptr<T>`` is not possible when ``T`` is 233not directly registered with ``py::class_<T>`` (e.g. ``std::shared_ptr<int>`` 234or ``std::shared_ptr<std::vector<T>>`` are not automatically convertible). 235Attempting to bind a function with such arguments now results in a compile-time 236error instead of waiting to fail at run time. 237 238``py::init<...>()`` constructor definitions are also stricter and now prevent 239bindings which could cause unexpected behavior: 240 241.. code-block:: cpp 242 243 struct Example { 244 Example(int &); 245 }; 246 247 py::class_<Example>(m, "Example") 248 .def(py::init<int &>()); // OK, exact match 249 // .def(py::init<int>()); // compile-time error, mismatch 250 251A non-``const`` lvalue reference is not allowed to bind to an rvalue. However, 252note that a constructor taking ``const T &`` can still be registered using 253``py::init<T>()`` because a ``const`` lvalue reference can bind to an rvalue. 254 255v2.1 256==== 257 258Minimum compiler versions are enforced at compile time 259------------------------------------------------------ 260 261The minimums also apply to v2.0 but the check is now explicit and a compile-time 262error is raised if the compiler does not meet the requirements: 263 264* GCC >= 4.8 265* clang >= 3.3 (appleclang >= 5.0) 266* MSVC >= 2015u3 267* Intel C++ >= 15.0 268 269 270The ``py::metaclass`` attribute is not required for static properties 271--------------------------------------------------------------------- 272 273Binding classes with static properties is now possible by default. The 274zero-parameter version of ``py::metaclass()`` is deprecated. However, a new 275one-parameter ``py::metaclass(python_type)`` version was added for rare 276cases when a custom metaclass is needed to override pybind11's default. 277 278.. code-block:: cpp 279 280 // old -- emits a deprecation warning 281 py::class_<Foo>(m, "Foo", py::metaclass()) 282 .def_property_readonly_static("foo", ...); 283 284 // new -- static properties work without the attribute 285 py::class_<Foo>(m, "Foo") 286 .def_property_readonly_static("foo", ...); 287 288 // new -- advanced feature, override pybind11's default metaclass 289 py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type)) 290 ... 291 292 293v2.0 294==== 295 296Breaking changes in ``py::class_`` 297---------------------------------- 298 299These changes were necessary to make type definitions in pybind11 300future-proof, to support PyPy via its ``cpyext`` mechanism (`#527 301<https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency 302(`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_). 303 3041. Declarations of types that provide access via the buffer protocol must 305 now include the ``py::buffer_protocol()`` annotation as an argument to 306 the ``py::class_`` constructor. 307 308 .. code-block:: cpp 309 310 py::class_<Matrix>("Matrix", py::buffer_protocol()) 311 .def(py::init<...>()) 312 .def_buffer(...); 313 3142. Classes which include static properties (e.g. ``def_readwrite_static()``) 315 must now include the ``py::metaclass()`` attribute. Note: this requirement 316 has since been removed in v2.1. If you're upgrading from 1.x, it's 317 recommended to skip directly to v2.1 or newer. 318 3193. This version of pybind11 uses a redesigned mechanism for instantiating 320 trampoline classes that are used to override virtual methods from within 321 Python. This led to the following user-visible syntax change: 322 323 .. code-block:: cpp 324 325 // old v1.x syntax 326 py::class_<TrampolineClass>("MyClass") 327 .alias<MyClass>() 328 ... 329 330 // new v2.x syntax 331 py::class_<MyClass, TrampolineClass>("MyClass") 332 ... 333 334 Importantly, both the original and the trampoline class are now specified 335 as arguments to the ``py::class_`` template, and the ``alias<..>()`` call 336 is gone. The new scheme has zero overhead in cases when Python doesn't 337 override any functions of the underlying C++ class. 338 `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_. 339 340 The class type must be the first template argument given to ``py::class_`` 341 while the trampoline can be mixed in arbitrary order with other arguments 342 (see the following section). 343 344 345Deprecation of the ``py::base<T>()`` attribute 346---------------------------------------------- 347 348``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template 349argument to ``py::class_``. This new syntax also supports multiple inheritance. 350Note that, while the type being exported must be the first argument in the 351``py::class_<Class, ...>`` template, the order of the following types (bases, 352holder and/or trampoline) is not important. 353 354.. code-block:: cpp 355 356 // old v1.x 357 py::class_<Derived>("Derived", py::base<Base>()); 358 359 // new v2.x 360 py::class_<Derived, Base>("Derived"); 361 362 // new -- multiple inheritance 363 py::class_<Derived, Base1, Base2>("Derived"); 364 365 // new -- apart from `Derived` the argument order can be arbitrary 366 py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived"); 367 368 369Out-of-the-box support for ``std::shared_ptr`` 370---------------------------------------------- 371 372The relevant type caster is now built in, so it's no longer necessary to 373include a declaration of the form: 374 375.. code-block:: cpp 376 377 PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>) 378 379Continuing to do so won’t cause an error or even a deprecation warning, 380but it's completely redundant. 381 382 383Deprecation of a few ``py::object`` APIs 384---------------------------------------- 385 386All of the old-style calls emit deprecation warnings. 387 388+---------------------------------------+---------------------------------------------+ 389| Old syntax | New syntax | 390+=======================================+=============================================+ 391| ``obj.call(args...)`` | ``obj(args...)`` | 392+---------------------------------------+---------------------------------------------+ 393| ``obj.str()`` | ``py::str(obj)`` | 394+---------------------------------------+---------------------------------------------+ 395| ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` | 396+---------------------------------------+---------------------------------------------+ 397| ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` | 398+---------------------------------------+---------------------------------------------+ 399| ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` | 400+---------------------------------------+---------------------------------------------+ 401| ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` | 402+---------------------------------------+---------------------------------------------+ 403| ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` | 404+---------------------------------------+---------------------------------------------+ 405