You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

311 lines
15 KiB

  1. Functions
  2. #########
  3. Before proceeding with this section, make sure that you are already familiar
  4. with the basics of binding functions and classes, as explained in :doc:`/basics`
  5. and :doc:`/classes`. The following guide is applicable to both free and member
  6. functions, i.e. *methods* in Python.
  7. Return value policies
  8. =====================
  9. Python and C++ use fundamentally different ways of managing the memory and
  10. lifetime of objects managed by them. This can lead to issues when creating
  11. bindings for functions that return a non-trivial type. Just by looking at the
  12. type information, it is not clear whether Python should take charge of the
  13. returned value and eventually free its resources, or if this is handled on the
  14. C++ side. For this reason, pybind11 provides a several `return value policy`
  15. annotations that can be passed to the :func:`module::def` and
  16. :func:`class_::def` functions. The default policy is
  17. :enum:`return_value_policy::automatic`.
  18. Return value policies are tricky, and it's very important to get them right.
  19. Just to illustrate what can go wrong, consider the following simple example:
  20. .. code-block:: cpp
  21. /* Function declaration */
  22. Data *get_data() { return _data; /* (pointer to a static data structure) */ }
  23. ...
  24. /* Binding code */
  25. m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
  26. What's going on here? When ``get_data()`` is called from Python, the return
  27. value (a native C++ type) must be wrapped to turn it into a usable Python type.
  28. In this case, the default return value policy (:enum:`return_value_policy::automatic`)
  29. causes pybind11 to assume ownership of the static ``_data`` instance.
  30. When Python's garbage collector eventually deletes the Python
  31. wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
  32. delete()``) due to the implied ownership. At this point, the entire application
  33. will come crashing down, though errors could also be more subtle and involve
  34. silent data corruption.
  35. In the above example, the policy :enum:`return_value_policy::reference` should have
  36. been specified so that the global data instance is only *referenced* without any
  37. implied transfer of ownership, i.e.:
  38. .. code-block:: cpp
  39. m.def("get_data", &get_data, return_value_policy::reference);
  40. On the other hand, this is not the right policy for many other situations,
  41. where ignoring ownership could lead to resource leaks.
  42. As a developer using pybind11, it's important to be familiar with the different
  43. return value policies, including which situation calls for which one of them.
  44. The following table provides an overview of available policies:
  45. .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
  46. +--------------------------------------------------+----------------------------------------------------------------------------+
  47. | Return value policy | Description |
  48. +==================================================+============================================================================+
  49. | :enum:`return_value_policy::take_ownership` | Reference an existing object (i.e. do not create a new copy) and take |
  50. | | ownership. Python will call the destructor and delete operator when the |
  51. | | object's reference count reaches zero. Undefined behavior ensues when the |
  52. | | C++ side does the same, or when the data was not dynamically allocated. |
  53. +--------------------------------------------------+----------------------------------------------------------------------------+
  54. | :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python. |
  55. | | This policy is comparably safe because the lifetimes of the two instances |
  56. | | are decoupled. |
  57. +--------------------------------------------------+----------------------------------------------------------------------------+
  58. | :enum:`return_value_policy::move` | Use ``std::move`` to move the return value contents into a new instance |
  59. | | that will be owned by Python. This policy is comparably safe because the |
  60. | | lifetimes of the two instances (move source and destination) are decoupled.|
  61. +--------------------------------------------------+----------------------------------------------------------------------------+
  62. | :enum:`return_value_policy::reference` | Reference an existing object, but do not take ownership. The C++ side is |
  63. | | responsible for managing the object's lifetime and deallocating it when |
  64. | | it is no longer used. Warning: undefined behavior will ensue when the C++ |
  65. | | side deletes an object that is still referenced and used by Python. |
  66. +--------------------------------------------------+----------------------------------------------------------------------------+
  67. | :enum:`return_value_policy::reference_internal` | Indicates that the lifetime of the return value is tied to the lifetime |
  68. | | of a parent object, namely the implicit ``this``, or ``self`` argument of |
  69. | | the called method or property. Internally, this policy works just like |
  70. | | :enum:`return_value_policy::reference` but additionally applies a |
  71. | | ``keep_alive<0, 1>`` *call policy* (described in the next section) that |
  72. | | prevents the parent object from being garbage collected as long as the |
  73. | | return value is referenced by Python. This is the default policy for |
  74. | | property getters created via ``def_property``, ``def_readwrite``, etc. |
  75. +--------------------------------------------------+----------------------------------------------------------------------------+
  76. | :enum:`return_value_policy::automatic` | This is the default return value policy, which falls back to the policy |
  77. | | :enum:`return_value_policy::take_ownership` when the return value is a |
  78. | | pointer. Otherwise, it uses :enum:`return_value::move` or |
  79. | | :enum:`return_value::copy` for rvalue and lvalue references, respectively. |
  80. | | See above for a description of what all of these different policies do. |
  81. +--------------------------------------------------+----------------------------------------------------------------------------+
  82. | :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
  83. | | return value is a pointer. This is the default conversion policy for |
  84. | | function arguments when calling Python functions manually from C++ code |
  85. | | (i.e. via handle::operator()). You probably won't need to use this. |
  86. +--------------------------------------------------+----------------------------------------------------------------------------+
  87. Return value policies can also be applied to properties:
  88. .. code-block:: cpp
  89. class_<MyClass>(m, "MyClass")
  90. .def_property("data", &MyClass::getData, &MyClass::setData,
  91. py::return_value_policy::copy);
  92. Technically, the code above applies the policy to both the getter and the
  93. setter function, however, the setter doesn't really care about *return*
  94. value policies which makes this a convenient terse syntax. Alternatively,
  95. targeted arguments can be passed through the :class:`cpp_function` constructor:
  96. .. code-block:: cpp
  97. class_<MyClass>(m, "MyClass")
  98. .def_property("data"
  99. py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
  100. py::cpp_function(&MyClass::setData)
  101. );
  102. .. warning::
  103. Code with invalid return value policies might access unitialized memory or
  104. free data structures multiple times, which can lead to hard-to-debug
  105. non-determinism and segmentation faults, hence it is worth spending the
  106. time to understand all the different options in the table above.
  107. .. note::
  108. One important aspect of the above policies is that they only apply to
  109. instances which pybind11 has *not* seen before, in which case the policy
  110. clarifies essential questions about the return value's lifetime and
  111. ownership. When pybind11 knows the instance already (as identified by its
  112. type and address in memory), it will return the existing Python object
  113. wrapper rather than creating a new copy.
  114. .. note::
  115. The next section on :ref:`call_policies` discusses *call policies* that can be
  116. specified *in addition* to a return value policy from the list above. Call
  117. policies indicate reference relationships that can involve both return values
  118. and parameters of functions.
  119. .. note::
  120. As an alternative to elaborate call policies and lifetime management logic,
  121. consider using smart pointers (see the section on :ref:`smart_pointers` for
  122. details). Smart pointers can tell whether an object is still referenced from
  123. C++ or Python, which generally eliminates the kinds of inconsistencies that
  124. can lead to crashes or undefined behavior. For functions returning smart
  125. pointers, it is not necessary to specify a return value policy.
  126. .. _call_policies:
  127. Additional call policies
  128. ========================
  129. In addition to the above return value policies, further `call policies` can be
  130. specified to indicate dependencies between parameters. There is currently just
  131. one policy named ``keep_alive<Nurse, Patient>``, which indicates that the
  132. argument with index ``Patient`` should be kept alive at least until the
  133. argument with index ``Nurse`` is freed by the garbage collector. Argument
  134. indices start at one, while zero refers to the return value. For methods, index
  135. ``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
  136. index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
  137. with value ``None`` is detected at runtime, the call policy does nothing.
  138. This feature internally relies on the ability to create a *weak reference* to
  139. the nurse object, which is permitted by all classes exposed via pybind11. When
  140. the nurse object does not support weak references, an exception will be thrown.
  141. Consider the following example: here, the binding code for a list append
  142. operation ties the lifetime of the newly added element to the underlying
  143. container:
  144. .. code-block:: cpp
  145. py::class_<List>(m, "List")
  146. .def("append", &List::append, py::keep_alive<1, 2>());
  147. .. note::
  148. ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
  149. Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
  150. 0) policies from Boost.Python.
  151. .. seealso::
  152. The file :file:`tests/test_keep_alive.cpp` contains a complete example
  153. that demonstrates using :class:`keep_alive` in more detail.
  154. .. _python_objects_as_args:
  155. Python objects as arguments
  156. ===========================
  157. pybind11 exposes all major Python types using thin C++ wrapper classes. These
  158. wrapper classes can also be used as parameters of functions in bindings, which
  159. makes it possible to directly work with native Python types on the C++ side.
  160. For instance, the following statement iterates over a Python ``dict``:
  161. .. code-block:: cpp
  162. void print_dict(py::dict dict) {
  163. /* Easily interact with Python types */
  164. for (auto item : dict)
  165. std::cout << "key=" << item.first << ", "
  166. << "value=" << item.second << std::endl;
  167. }
  168. It can be exported:
  169. .. code-block:: cpp
  170. m.def("print_dict", &print_dict);
  171. And used in Python as usual:
  172. .. code-block:: pycon
  173. >>> print_dict({'foo': 123, 'bar': 'hello'})
  174. key=foo, value=123
  175. key=bar, value=hello
  176. For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
  177. Accepting \*args and \*\*kwargs
  178. ===============================
  179. Python provides a useful mechanism to define functions that accept arbitrary
  180. numbers of arguments and keyword arguments:
  181. .. code-block:: python
  182. def generic(*args, **kwargs):
  183. ... # do something with args and kwargs
  184. Such functions can also be created using pybind11:
  185. .. code-block:: cpp
  186. void generic(py::args args, py::kwargs kwargs) {
  187. /// .. do something with args
  188. if (kwargs)
  189. /// .. do something with kwargs
  190. }
  191. /// Binding code
  192. m.def("generic", &generic);
  193. The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
  194. from ``py::dict``. Note that the ``kwargs`` argument is invalid if no keyword
  195. arguments were actually provided. Please refer to the other examples for
  196. details on how to iterate over these, and on how to cast their entries into
  197. C++ objects. A demonstration is also available in
  198. ``tests/test_kwargs_and_defaults.cpp``.
  199. .. warning::
  200. Unlike Python, pybind11 does not allow combining normal parameters with the
  201. ``args`` / ``kwargs`` special parameters.
  202. Default arguments revisited
  203. ===========================
  204. The section on :ref:`default_args` previously discussed basic usage of default
  205. arguments using pybind11. One noteworthy aspect of their implementation is that
  206. default arguments are converted to Python objects right at declaration time.
  207. Consider the following example:
  208. .. code-block:: cpp
  209. py::class_<MyClass>("MyClass")
  210. .def("myFunction", py::arg("arg") = SomeType(123));
  211. In this case, pybind11 must already be set up to deal with values of the type
  212. ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
  213. exception will be thrown.
  214. Another aspect worth highlighting is that the "preview" of the default argument
  215. in the function signature is generated using the object's ``__repr__`` method.
  216. If not available, the signature may not be very helpful, e.g.:
  217. .. code-block:: pycon
  218. FUNCTIONS
  219. ...
  220. | myFunction(...)
  221. | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
  222. ...
  223. The first way of addressing this is by defining ``SomeType.__repr__``.
  224. Alternatively, it is possible to specify the human-readable preview of the
  225. default argument manually using the ``arg_v`` notation:
  226. .. code-block:: cpp
  227. py::class_<MyClass>("MyClass")
  228. .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
  229. Sometimes it may be necessary to pass a null pointer value as a default
  230. argument. In this case, remember to cast it to the underlying type in question,
  231. like so:
  232. .. code-block:: cpp
  233. py::class_<MyClass>("MyClass")
  234. .def("myFunction", py::arg("arg") = (SomeType *) nullptr);