upgrade.rst 23 KB

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