upgrade.rst 17 KB

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