Dean Moldovan | 1fb9df6 | 2017-08-18 19:26:49 +0200 | [diff] [blame] | 1 | Upgrade guide |
| 2 | ############# |
| 3 | |
| 4 | This is a companion guide to the :doc:`changelog`. While the changelog briefly |
| 5 | lists all of the new features, improvements and bug fixes, this upgrade guide |
| 6 | focuses only the subset which directly impacts your experience when upgrading |
| 7 | to a new version. But it goes into more detail. This includes things like |
| 8 | deprecated APIs and their replacements, build system changes, general code |
| 9 | modernization and other useful information. |
| 10 | |
Henry Schreiner | 1729aae | 2020-08-19 12:26:26 -0400 | [diff] [blame^] | 11 | .. _upgrade-guide-2.6: |
| 12 | |
| 13 | v2.6 |
| 14 | ==== |
| 15 | |
| 16 | CMake support: |
| 17 | -------------- |
| 18 | |
| 19 | The minimum required version of CMake is now 3.4. Several details of the CMake |
| 20 | support have been deprecated; warnings will be shown if you need to change |
| 21 | something. The changes are: |
| 22 | |
| 23 | * ``PYBIND11_CPP_STANDARD=<platform-flag>`` is deprecated, please use |
| 24 | ``CMAKE_CXX_STANDARD=<number>`` instead, or any other valid CMake CXX or CUDA |
| 25 | standard selection method, like ``target_compile_features``. |
| 26 | |
| 27 | * If you do not request a standard, PyBind11 targets will compile with the |
| 28 | compiler default, but not less than C++11, instead of forcing C++14 always. |
| 29 | If you depend on the old behavior, please use ``set(CMAKE_CXX_STANDARD 14)`` |
| 30 | instead. |
| 31 | |
| 32 | * Direct ``pybind11::module`` usage should always be accompanied by at least |
| 33 | ``set(CMAKE_CXX_VISIBILITY_PRESET hidden)`` or similar - it used to try to |
| 34 | manually force this compiler flag (but not correctly on all compilers or with |
| 35 | CUDA). |
| 36 | |
| 37 | * ``pybind11_add_module``'s ``SYSTEM`` argument is deprecated and does nothing; |
| 38 | linking now behaves like other imported libraries consistently in both |
| 39 | config and submodule mode, and behaves like a ``SYSTEM`` library by |
| 40 | default. |
| 41 | |
| 42 | * If ``PYTHON_EXECUTABLE`` is not set, virtual environments (``venv``, |
| 43 | ``virtualenv``, and ``conda``) are prioritized over the standard search |
| 44 | (similar to the new FindPython mode). |
| 45 | |
| 46 | In addition, the following changes may be of interest: |
| 47 | |
| 48 | * ``CMAKE_INTERPROCEDURAL_OPTIMIZATION`` will be respected by |
| 49 | ``pybind11_add_module`` if set instead of linking to ``pybind11::lto`` or |
| 50 | ``pybind11::thin_lto``. |
| 51 | |
| 52 | * Using ``find_package(Python COMPONENTS Interpreter Development)`` before |
| 53 | pybind11 will cause pybind11 to use the new Python mechanisms instead of its |
| 54 | own custom search, based on a patched version of classic |
| 55 | FindPythonInterp/FindPythonLibs. In the future, this may become the default. |
| 56 | |
| 57 | |
Dean Moldovan | 1fb9df6 | 2017-08-18 19:26:49 +0200 | [diff] [blame] | 58 | |
| 59 | v2.2 |
| 60 | ==== |
| 61 | |
| 62 | Deprecation of the ``PYBIND11_PLUGIN`` macro |
| 63 | -------------------------------------------- |
| 64 | |
| 65 | ``PYBIND11_MODULE`` is now the preferred way to create module entry points. |
| 66 | The old macro emits a compile-time deprecation warning. |
| 67 | |
| 68 | .. code-block:: cpp |
| 69 | |
| 70 | // old |
| 71 | PYBIND11_PLUGIN(example) { |
| 72 | py::module m("example", "documentation string"); |
| 73 | |
| 74 | m.def("add", [](int a, int b) { return a + b; }); |
| 75 | |
| 76 | return m.ptr(); |
| 77 | } |
| 78 | |
| 79 | // new |
| 80 | PYBIND11_MODULE(example, m) { |
| 81 | m.doc() = "documentation string"; // optional |
| 82 | |
| 83 | m.def("add", [](int a, int b) { return a + b; }); |
| 84 | } |
| 85 | |
| 86 | |
Dean Moldovan | b8c5dbd | 2017-08-24 02:46:07 +0200 | [diff] [blame] | 87 | New API for defining custom constructors and pickling functions |
| 88 | --------------------------------------------------------------- |
| 89 | |
| 90 | The old placement-new custom constructors have been deprecated. The new approach |
| 91 | uses ``py::init()`` and factory functions to greatly improve type safety. |
| 92 | |
| 93 | Placement-new can be called accidentally with an incompatible type (without any |
| 94 | compiler errors or warnings), or it can initialize the same object multiple times |
| 95 | if not careful with the Python-side ``__init__`` calls. The new-style custom |
| 96 | constructors prevent such mistakes. See :ref:`custom_constructors` for details. |
| 97 | |
| 98 | .. code-block:: cpp |
| 99 | |
| 100 | // old -- deprecated (runtime warning shown only in debug mode) |
| 101 | py::class<Foo>(m, "Foo") |
| 102 | .def("__init__", [](Foo &self, ...) { |
| 103 | new (&self) Foo(...); // uses placement-new |
| 104 | }); |
| 105 | |
| 106 | // new |
| 107 | py::class<Foo>(m, "Foo") |
| 108 | .def(py::init([](...) { // Note: no `self` argument |
| 109 | return new Foo(...); // return by raw pointer |
| 110 | // or: return std::make_unique<Foo>(...); // return by holder |
| 111 | // or: return Foo(...); // return by value (move constructor) |
| 112 | })); |
| 113 | |
| 114 | Mirroring the custom constructor changes, ``py::pickle()`` is now the preferred |
| 115 | way to get and set object state. See :ref:`pickling` for details. |
| 116 | |
| 117 | .. code-block:: cpp |
| 118 | |
| 119 | // old -- deprecated (runtime warning shown only in debug mode) |
| 120 | py::class<Foo>(m, "Foo") |
| 121 | ... |
| 122 | .def("__getstate__", [](const Foo &self) { |
| 123 | return py::make_tuple(self.value1(), self.value2(), ...); |
| 124 | }) |
| 125 | .def("__setstate__", [](Foo &self, py::tuple t) { |
| 126 | new (&self) Foo(t[0].cast<std::string>(), ...); |
| 127 | }); |
| 128 | |
| 129 | // new |
| 130 | py::class<Foo>(m, "Foo") |
| 131 | ... |
| 132 | .def(py::pickle( |
| 133 | [](const Foo &self) { // __getstate__ |
| 134 | return py::make_tuple(f.value1(), f.value2(), ...); // unchanged |
| 135 | }, |
| 136 | [](py::tuple t) { // __setstate__, note: no `self` argument |
| 137 | return new Foo(t[0].cast<std::string>(), ...); |
| 138 | // or: return std::make_unique<Foo>(...); // return by holder |
| 139 | // or: return Foo(...); // return by value (move constructor) |
| 140 | } |
| 141 | )); |
| 142 | |
| 143 | For both the constructors and pickling, warnings are shown at module |
| 144 | initialization time (on import, not when the functions are called). |
| 145 | They're only visible when compiled in debug mode. Sample warning: |
| 146 | |
| 147 | .. code-block:: none |
| 148 | |
| 149 | pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__' |
| 150 | which has been deprecated. See the upgrade guide in pybind11's docs. |
| 151 | |
| 152 | |
Dean Moldovan | 1fb9df6 | 2017-08-18 19:26:49 +0200 | [diff] [blame] | 153 | Stricter enforcement of hidden symbol visibility for pybind11 modules |
| 154 | --------------------------------------------------------------------- |
| 155 | |
| 156 | pybind11 now tries to actively enforce hidden symbol visibility for modules. |
| 157 | If you're using either one of pybind11's :doc:`CMake or Python build systems |
| 158 | <compiling>` (the two example repositories) and you haven't been exporting any |
| 159 | symbols, there's nothing to be concerned about. All the changes have been done |
| 160 | transparently in the background. If you were building manually or relied on |
| 161 | specific default visibility, read on. |
| 162 | |
| 163 | Setting default symbol visibility to *hidden* has always been recommended for |
| 164 | pybind11 (see :ref:`faq:symhidden`). On Linux and macOS, hidden symbol |
| 165 | visibility (in conjunction with the ``strip`` utility) yields much smaller |
| 166 | module binaries. `CPython's extension docs`_ also recommend hiding symbols |
| 167 | by default, with the goal of avoiding symbol name clashes between modules. |
| 168 | Starting with v2.2, pybind11 enforces this more strictly: (1) by declaring |
| 169 | all symbols inside the ``pybind11`` namespace as hidden and (2) by including |
| 170 | the ``-fvisibility=hidden`` flag on Linux and macOS (only for extension |
| 171 | modules, not for embedding the interpreter). |
| 172 | |
| 173 | .. _CPython's extension docs: https://docs.python.org/3/extending/extending.html#providing-a-c-api-for-an-extension-module |
| 174 | |
| 175 | The namespace-scope hidden visibility is done automatically in pybind11's |
| 176 | headers and it's generally transparent to users. It ensures that: |
| 177 | |
| 178 | * Modules compiled with different pybind11 versions don't clash with each other. |
| 179 | |
| 180 | * Some new features, like ``py::module_local`` bindings, can work as intended. |
| 181 | |
| 182 | The ``-fvisibility=hidden`` flag applies the same visibility to user bindings |
| 183 | outside of the ``pybind11`` namespace. It's now set automatic by pybind11's |
| 184 | CMake and Python build systems, but this needs to be done manually by users |
| 185 | of other build systems. Adding this flag: |
| 186 | |
| 187 | * Minimizes the chances of symbol conflicts between modules. E.g. if two |
| 188 | unrelated modules were statically linked to different (ABI-incompatible) |
| 189 | versions of the same third-party library, a symbol clash would be likely |
| 190 | (and would end with unpredictable results). |
| 191 | |
| 192 | * Produces smaller binaries on Linux and macOS, as pointed out previously. |
| 193 | |
| 194 | Within pybind11's CMake build system, ``pybind11_add_module`` has always been |
| 195 | setting the ``-fvisibility=hidden`` flag in release mode. From now on, it's |
| 196 | being applied unconditionally, even in debug mode and it can no longer be opted |
| 197 | out of with the ``NO_EXTRAS`` option. The ``pybind11::module`` target now also |
| 198 | adds this flag to it's interface. The ``pybind11::embed`` target is unchanged. |
| 199 | |
| 200 | The most significant change here is for the ``pybind11::module`` target. If you |
| 201 | were previously relying on default visibility, i.e. if your Python module was |
| 202 | doubling as a shared library with dependents, you'll need to either export |
| 203 | symbols manually (recommended for cross-platform libraries) or factor out the |
| 204 | shared library (and have the Python module link to it like the other |
| 205 | dependents). As a temporary workaround, you can also restore default visibility |
| 206 | using the CMake code below, but this is not recommended in the long run: |
| 207 | |
| 208 | .. code-block:: cmake |
| 209 | |
| 210 | target_link_libraries(mymodule PRIVATE pybind11::module) |
| 211 | |
| 212 | add_library(restore_default_visibility INTERFACE) |
| 213 | target_compile_options(restore_default_visibility INTERFACE -fvisibility=default) |
| 214 | target_link_libraries(mymodule PRIVATE restore_default_visibility) |
| 215 | |
| 216 | |
| 217 | Local STL container bindings |
| 218 | ---------------------------- |
| 219 | |
| 220 | Previous pybind11 versions could only bind types globally -- all pybind11 |
| 221 | modules, even unrelated ones, would have access to the same exported types. |
| 222 | However, this would also result in a conflict if two modules exported the |
| 223 | same C++ type, which is especially problematic for very common types, e.g. |
| 224 | ``std::vector<int>``. :ref:`module_local` were added to resolve this (see |
| 225 | that section for a complete usage guide). |
| 226 | |
| 227 | ``py::class_`` still defaults to global bindings (because these types are |
| 228 | usually unique across modules), however in order to avoid clashes of opaque |
| 229 | types, ``py::bind_vector`` and ``py::bind_map`` will now bind STL containers |
| 230 | as ``py::module_local`` if their elements are: builtins (``int``, ``float``, |
| 231 | etc.), not bound using ``py::class_``, or bound as ``py::module_local``. For |
| 232 | example, this change allows multiple modules to bind ``std::vector<int>`` |
| 233 | without causing conflicts. See :ref:`stl_bind` for more details. |
| 234 | |
| 235 | When upgrading to this version, if you have multiple modules which depend on |
| 236 | a single global binding of an STL container, note that all modules can still |
| 237 | accept foreign ``py::module_local`` types in the direction of Python-to-C++. |
| 238 | The locality only affects the C++-to-Python direction. If this is needed in |
| 239 | multiple modules, you'll need to either: |
| 240 | |
| 241 | * Add a copy of the same STL binding to all of the modules which need it. |
| 242 | |
| 243 | * Restore the global status of that single binding by marking it |
| 244 | ``py::module_local(false)``. |
| 245 | |
| 246 | The latter is an easy workaround, but in the long run it would be best to |
| 247 | localize all common type bindings in order to avoid conflicts with |
| 248 | third-party modules. |
| 249 | |
| 250 | |
Dean Moldovan | 4c54044 | 2017-08-30 21:53:08 +0200 | [diff] [blame] | 251 | Negative strides for Python buffer objects and numpy arrays |
| 252 | ----------------------------------------------------------- |
| 253 | |
| 254 | Support for negative strides required changing the integer type from unsigned |
| 255 | to signed in the interfaces of ``py::buffer_info`` and ``py::array``. If you |
| 256 | have compiler warnings enabled, you may notice some new conversion warnings |
| 257 | after upgrading. These can be resolved using ``static_cast``. |
| 258 | |
| 259 | |
Dean Moldovan | 1fb9df6 | 2017-08-18 19:26:49 +0200 | [diff] [blame] | 260 | Deprecation of some ``py::object`` APIs |
| 261 | --------------------------------------- |
| 262 | |
| 263 | To compare ``py::object`` instances by pointer, you should now use |
| 264 | ``obj1.is(obj2)`` which is equivalent to ``obj1 is obj2`` in Python. |
| 265 | Previously, pybind11 used ``operator==`` for this (``obj1 == obj2``), but |
| 266 | that could be confusing and is now deprecated (so that it can eventually |
| 267 | be replaced with proper rich object comparison in a future release). |
| 268 | |
| 269 | For classes which inherit from ``py::object``, ``borrowed`` and ``stolen`` |
| 270 | were previously available as protected constructor tags. Now the types |
| 271 | should be used directly instead: ``borrowed_t{}`` and ``stolen_t{}`` |
| 272 | (`#771 <https://github.com/pybind/pybind11/pull/771>`_). |
| 273 | |
| 274 | |
Dean Moldovan | 91b42c8 | 2017-09-02 14:46:32 +0200 | [diff] [blame] | 275 | Stricter compile-time error checking |
| 276 | ------------------------------------ |
| 277 | |
| 278 | Some error checks have been moved from run time to compile time. Notably, |
| 279 | automatic conversion of ``std::shared_ptr<T>`` is not possible when ``T`` is |
| 280 | not directly registered with ``py::class_<T>`` (e.g. ``std::shared_ptr<int>`` |
| 281 | or ``std::shared_ptr<std::vector<T>>`` are not automatically convertible). |
| 282 | Attempting to bind a function with such arguments now results in a compile-time |
| 283 | error instead of waiting to fail at run time. |
| 284 | |
| 285 | ``py::init<...>()`` constructor definitions are also stricter and now prevent |
| 286 | bindings which could cause unexpected behavior: |
| 287 | |
| 288 | .. code-block:: cpp |
| 289 | |
| 290 | struct Example { |
| 291 | Example(int &); |
| 292 | }; |
| 293 | |
| 294 | py::class_<Example>(m, "Example") |
| 295 | .def(py::init<int &>()); // OK, exact match |
| 296 | // .def(py::init<int>()); // compile-time error, mismatch |
| 297 | |
| 298 | A non-``const`` lvalue reference is not allowed to bind to an rvalue. However, |
| 299 | note that a constructor taking ``const T &`` can still be registered using |
| 300 | ``py::init<T>()`` because a ``const`` lvalue reference can bind to an rvalue. |
| 301 | |
Dean Moldovan | 1fb9df6 | 2017-08-18 19:26:49 +0200 | [diff] [blame] | 302 | v2.1 |
| 303 | ==== |
| 304 | |
| 305 | Minimum compiler versions are enforced at compile time |
| 306 | ------------------------------------------------------ |
| 307 | |
| 308 | The minimums also apply to v2.0 but the check is now explicit and a compile-time |
| 309 | error is raised if the compiler does not meet the requirements: |
| 310 | |
| 311 | * GCC >= 4.8 |
| 312 | * clang >= 3.3 (appleclang >= 5.0) |
| 313 | * MSVC >= 2015u3 |
| 314 | * Intel C++ >= 15.0 |
| 315 | |
| 316 | |
| 317 | The ``py::metaclass`` attribute is not required for static properties |
| 318 | --------------------------------------------------------------------- |
| 319 | |
| 320 | Binding classes with static properties is now possible by default. The |
| 321 | zero-parameter version of ``py::metaclass()`` is deprecated. However, a new |
| 322 | one-parameter ``py::metaclass(python_type)`` version was added for rare |
| 323 | cases when a custom metaclass is needed to override pybind11's default. |
| 324 | |
| 325 | .. code-block:: cpp |
| 326 | |
| 327 | // old -- emits a deprecation warning |
| 328 | py::class_<Foo>(m, "Foo", py::metaclass()) |
| 329 | .def_property_readonly_static("foo", ...); |
| 330 | |
| 331 | // new -- static properties work without the attribute |
| 332 | py::class_<Foo>(m, "Foo") |
| 333 | .def_property_readonly_static("foo", ...); |
| 334 | |
| 335 | // new -- advanced feature, override pybind11's default metaclass |
| 336 | py::class_<Bar>(m, "Bar", py::metaclass(custom_python_type)) |
| 337 | ... |
| 338 | |
| 339 | |
| 340 | v2.0 |
| 341 | ==== |
| 342 | |
| 343 | Breaking changes in ``py::class_`` |
| 344 | ---------------------------------- |
| 345 | |
| 346 | These changes were necessary to make type definitions in pybind11 |
| 347 | future-proof, to support PyPy via its ``cpyext`` mechanism (`#527 |
| 348 | <https://github.com/pybind/pybind11/pull/527>`_), and to improve efficiency |
| 349 | (`rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_). |
| 350 | |
| 351 | 1. Declarations of types that provide access via the buffer protocol must |
| 352 | now include the ``py::buffer_protocol()`` annotation as an argument to |
| 353 | the ``py::class_`` constructor. |
| 354 | |
| 355 | .. code-block:: cpp |
| 356 | |
| 357 | py::class_<Matrix>("Matrix", py::buffer_protocol()) |
| 358 | .def(py::init<...>()) |
| 359 | .def_buffer(...); |
| 360 | |
| 361 | 2. Classes which include static properties (e.g. ``def_readwrite_static()``) |
| 362 | must now include the ``py::metaclass()`` attribute. Note: this requirement |
| 363 | has since been removed in v2.1. If you're upgrading from 1.x, it's |
| 364 | recommended to skip directly to v2.1 or newer. |
| 365 | |
| 366 | 3. This version of pybind11 uses a redesigned mechanism for instantiating |
| 367 | trampoline classes that are used to override virtual methods from within |
| 368 | Python. This led to the following user-visible syntax change: |
| 369 | |
| 370 | .. code-block:: cpp |
| 371 | |
| 372 | // old v1.x syntax |
| 373 | py::class_<TrampolineClass>("MyClass") |
| 374 | .alias<MyClass>() |
| 375 | ... |
| 376 | |
| 377 | // new v2.x syntax |
| 378 | py::class_<MyClass, TrampolineClass>("MyClass") |
| 379 | ... |
| 380 | |
| 381 | Importantly, both the original and the trampoline class are now specified |
| 382 | as arguments to the ``py::class_`` template, and the ``alias<..>()`` call |
| 383 | is gone. The new scheme has zero overhead in cases when Python doesn't |
| 384 | override any functions of the underlying C++ class. |
| 385 | `rev. 86d825 <https://github.com/pybind/pybind11/commit/86d825>`_. |
| 386 | |
| 387 | The class type must be the first template argument given to ``py::class_`` |
| 388 | while the trampoline can be mixed in arbitrary order with other arguments |
| 389 | (see the following section). |
| 390 | |
| 391 | |
| 392 | Deprecation of the ``py::base<T>()`` attribute |
| 393 | ---------------------------------------------- |
| 394 | |
| 395 | ``py::base<T>()`` was deprecated in favor of specifying ``T`` as a template |
| 396 | argument to ``py::class_``. This new syntax also supports multiple inheritance. |
| 397 | Note that, while the type being exported must be the first argument in the |
| 398 | ``py::class_<Class, ...>`` template, the order of the following types (bases, |
| 399 | holder and/or trampoline) is not important. |
| 400 | |
| 401 | .. code-block:: cpp |
| 402 | |
| 403 | // old v1.x |
| 404 | py::class_<Derived>("Derived", py::base<Base>()); |
| 405 | |
| 406 | // new v2.x |
| 407 | py::class_<Derived, Base>("Derived"); |
| 408 | |
| 409 | // new -- multiple inheritance |
| 410 | py::class_<Derived, Base1, Base2>("Derived"); |
| 411 | |
| 412 | // new -- apart from `Derived` the argument order can be arbitrary |
| 413 | py::class_<Derived, Base1, Holder, Base2, Trampoline>("Derived"); |
| 414 | |
| 415 | |
| 416 | Out-of-the-box support for ``std::shared_ptr`` |
| 417 | ---------------------------------------------- |
| 418 | |
| 419 | The relevant type caster is now built in, so it's no longer necessary to |
| 420 | include a declaration of the form: |
| 421 | |
| 422 | .. code-block:: cpp |
| 423 | |
| 424 | PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>) |
| 425 | |
| 426 | Continuing to do so won’t cause an error or even a deprecation warning, |
| 427 | but it's completely redundant. |
| 428 | |
| 429 | |
| 430 | Deprecation of a few ``py::object`` APIs |
| 431 | ---------------------------------------- |
| 432 | |
| 433 | All of the old-style calls emit deprecation warnings. |
| 434 | |
| 435 | +---------------------------------------+---------------------------------------------+ |
| 436 | | Old syntax | New syntax | |
| 437 | +=======================================+=============================================+ |
| 438 | | ``obj.call(args...)`` | ``obj(args...)`` | |
| 439 | +---------------------------------------+---------------------------------------------+ |
| 440 | | ``obj.str()`` | ``py::str(obj)`` | |
| 441 | +---------------------------------------+---------------------------------------------+ |
| 442 | | ``auto l = py::list(obj); l.check()`` | ``py::isinstance<py::list>(obj)`` | |
| 443 | +---------------------------------------+---------------------------------------------+ |
| 444 | | ``py::object(ptr, true)`` | ``py::reinterpret_borrow<py::object>(ptr)`` | |
| 445 | +---------------------------------------+---------------------------------------------+ |
| 446 | | ``py::object(ptr, false)`` | ``py::reinterpret_steal<py::object>(ptr)`` | |
| 447 | +---------------------------------------+---------------------------------------------+ |
| 448 | | ``if (obj.attr("foo"))`` | ``if (py::hasattr(obj, "foo"))`` | |
| 449 | +---------------------------------------+---------------------------------------------+ |
| 450 | | ``if (obj["bar"])`` | ``if (obj.contains("bar"))`` | |
| 451 | +---------------------------------------+---------------------------------------------+ |