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.

409 lines
19 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  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. Return value policies
  9. =====================
  10. Python and C++ use fundamentally different ways of managing the memory and
  11. lifetime of objects managed by them. This can lead to issues when creating
  12. bindings for functions that return a non-trivial type. Just by looking at the
  13. type information, it is not clear whether Python should take charge of the
  14. returned value and eventually free its resources, or if this is handled on the
  15. C++ side. For this reason, pybind11 provides a several *return value policy*
  16. annotations that can be passed to the :func:`module::def` and
  17. :func:`class_::def` functions. The default policy is
  18. :enum:`return_value_policy::automatic`.
  19. Return value policies are tricky, and it's very important to get them right.
  20. Just to illustrate what can go wrong, consider the following simple example:
  21. .. code-block:: cpp
  22. /* Function declaration */
  23. Data *get_data() { return _data; /* (pointer to a static data structure) */ }
  24. ...
  25. /* Binding code */
  26. m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
  27. What's going on here? When ``get_data()`` is called from Python, the return
  28. value (a native C++ type) must be wrapped to turn it into a usable Python type.
  29. In this case, the default return value policy (:enum:`return_value_policy::automatic`)
  30. causes pybind11 to assume ownership of the static ``_data`` instance.
  31. When Python's garbage collector eventually deletes the Python
  32. wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
  33. delete()``) due to the implied ownership. At this point, the entire application
  34. will come crashing down, though errors could also be more subtle and involve
  35. silent data corruption.
  36. In the above example, the policy :enum:`return_value_policy::reference` should have
  37. been specified so that the global data instance is only *referenced* without any
  38. implied transfer of ownership, i.e.:
  39. .. code-block:: cpp
  40. m.def("get_data", &get_data, return_value_policy::reference);
  41. On the other hand, this is not the right policy for many other situations,
  42. where ignoring ownership could lead to resource leaks.
  43. As a developer using pybind11, it's important to be familiar with the different
  44. return value policies, including which situation calls for which one of them.
  45. The following table provides an overview of available policies:
  46. .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
  47. +--------------------------------------------------+----------------------------------------------------------------------------+
  48. | Return value policy | Description |
  49. +==================================================+============================================================================+
  50. | :enum:`return_value_policy::take_ownership` | Reference an existing object (i.e. do not create a new copy) and take |
  51. | | ownership. Python will call the destructor and delete operator when the |
  52. | | object's reference count reaches zero. Undefined behavior ensues when the |
  53. | | C++ side does the same, or when the data was not dynamically allocated. |
  54. +--------------------------------------------------+----------------------------------------------------------------------------+
  55. | :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python. |
  56. | | This policy is comparably safe because the lifetimes of the two instances |
  57. | | are decoupled. |
  58. +--------------------------------------------------+----------------------------------------------------------------------------+
  59. | :enum:`return_value_policy::move` | Use ``std::move`` to move the return value contents into a new instance |
  60. | | that will be owned by Python. This policy is comparably safe because the |
  61. | | lifetimes of the two instances (move source and destination) are decoupled.|
  62. +--------------------------------------------------+----------------------------------------------------------------------------+
  63. | :enum:`return_value_policy::reference` | Reference an existing object, but do not take ownership. The C++ side is |
  64. | | responsible for managing the object's lifetime and deallocating it when |
  65. | | it is no longer used. Warning: undefined behavior will ensue when the C++ |
  66. | | side deletes an object that is still referenced and used by Python. |
  67. +--------------------------------------------------+----------------------------------------------------------------------------+
  68. | :enum:`return_value_policy::reference_internal` | Indicates that the lifetime of the return value is tied to the lifetime |
  69. | | of a parent object, namely the implicit ``this``, or ``self`` argument of |
  70. | | the called method or property. Internally, this policy works just like |
  71. | | :enum:`return_value_policy::reference` but additionally applies a |
  72. | | ``keep_alive<0, 1>`` *call policy* (described in the next section) that |
  73. | | prevents the parent object from being garbage collected as long as the |
  74. | | return value is referenced by Python. This is the default policy for |
  75. | | property getters created via ``def_property``, ``def_readwrite``, etc. |
  76. +--------------------------------------------------+----------------------------------------------------------------------------+
  77. | :enum:`return_value_policy::automatic` | **Default policy.** This policy falls back to the policy |
  78. | | :enum:`return_value_policy::take_ownership` when the return value is a |
  79. | | pointer. Otherwise, it uses :enum:`return_value_policy::move` or |
  80. | | :enum:`return_value_policy::copy` for rvalue and lvalue references, |
  81. | | respectively. See above for a description of what all of these different |
  82. | | policies do. |
  83. +--------------------------------------------------+----------------------------------------------------------------------------+
  84. | :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
  85. | | return value is a pointer. This is the default conversion policy for |
  86. | | function arguments when calling Python functions manually from C++ code |
  87. | | (i.e. via handle::operator()). You probably won't need to use this. |
  88. +--------------------------------------------------+----------------------------------------------------------------------------+
  89. Return value policies can also be applied to properties:
  90. .. code-block:: cpp
  91. class_<MyClass>(m, "MyClass")
  92. .def_property("data", &MyClass::getData, &MyClass::setData,
  93. py::return_value_policy::copy);
  94. Technically, the code above applies the policy to both the getter and the
  95. setter function, however, the setter doesn't really care about *return*
  96. value policies which makes this a convenient terse syntax. Alternatively,
  97. targeted arguments can be passed through the :class:`cpp_function` constructor:
  98. .. code-block:: cpp
  99. class_<MyClass>(m, "MyClass")
  100. .def_property("data"
  101. py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
  102. py::cpp_function(&MyClass::setData)
  103. );
  104. .. warning::
  105. Code with invalid return value policies might access unitialized memory or
  106. free data structures multiple times, which can lead to hard-to-debug
  107. non-determinism and segmentation faults, hence it is worth spending the
  108. time to understand all the different options in the table above.
  109. .. note::
  110. One important aspect of the above policies is that they only apply to
  111. instances which pybind11 has *not* seen before, in which case the policy
  112. clarifies essential questions about the return value's lifetime and
  113. ownership. When pybind11 knows the instance already (as identified by its
  114. type and address in memory), it will return the existing Python object
  115. wrapper rather than creating a new copy.
  116. .. note::
  117. The next section on :ref:`call_policies` discusses *call policies* that can be
  118. specified *in addition* to a return value policy from the list above. Call
  119. policies indicate reference relationships that can involve both return values
  120. and parameters of functions.
  121. .. note::
  122. As an alternative to elaborate call policies and lifetime management logic,
  123. consider using smart pointers (see the section on :ref:`smart_pointers` for
  124. details). Smart pointers can tell whether an object is still referenced from
  125. C++ or Python, which generally eliminates the kinds of inconsistencies that
  126. can lead to crashes or undefined behavior. For functions returning smart
  127. pointers, it is not necessary to specify a return value policy.
  128. .. _call_policies:
  129. Additional call policies
  130. ========================
  131. In addition to the above return value policies, further *call policies* can be
  132. specified to indicate dependencies between parameters. In general, call policies
  133. are required when the C++ object is any kind of container and another object is being
  134. added to the container.
  135. There is currently just
  136. one policy named ``keep_alive<Nurse, Patient>``, which indicates that the
  137. argument with index ``Patient`` should be kept alive at least until the
  138. argument with index ``Nurse`` is freed by the garbage collector. Argument
  139. indices start at one, while zero refers to the return value. For methods, index
  140. ``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
  141. index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
  142. with value ``None`` is detected at runtime, the call policy does nothing.
  143. This feature internally relies on the ability to create a *weak reference* to
  144. the nurse object, which is permitted by all classes exposed via pybind11. When
  145. the nurse object does not support weak references, an exception will be thrown.
  146. Consider the following example: here, the binding code for a list append
  147. operation ties the lifetime of the newly added element to the underlying
  148. container:
  149. .. code-block:: cpp
  150. py::class_<List>(m, "List")
  151. .def("append", &List::append, py::keep_alive<1, 2>());
  152. .. note::
  153. ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
  154. Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
  155. 0) policies from Boost.Python.
  156. .. seealso::
  157. The file :file:`tests/test_keep_alive.cpp` contains a complete example
  158. that demonstrates using :class:`keep_alive` in more detail.
  159. .. _python_objects_as_args:
  160. Python objects as arguments
  161. ===========================
  162. pybind11 exposes all major Python types using thin C++ wrapper classes. These
  163. wrapper classes can also be used as parameters of functions in bindings, which
  164. makes it possible to directly work with native Python types on the C++ side.
  165. For instance, the following statement iterates over a Python ``dict``:
  166. .. code-block:: cpp
  167. void print_dict(py::dict dict) {
  168. /* Easily interact with Python types */
  169. for (auto item : dict)
  170. std::cout << "key=" << std::string(py::str(item.first)) << ", "
  171. << "value=" << std::string(py::str(item.second)) << std::endl;
  172. }
  173. It can be exported:
  174. .. code-block:: cpp
  175. m.def("print_dict", &print_dict);
  176. And used in Python as usual:
  177. .. code-block:: pycon
  178. >>> print_dict({'foo': 123, 'bar': 'hello'})
  179. key=foo, value=123
  180. key=bar, value=hello
  181. For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
  182. Accepting \*args and \*\*kwargs
  183. ===============================
  184. Python provides a useful mechanism to define functions that accept arbitrary
  185. numbers of arguments and keyword arguments:
  186. .. code-block:: python
  187. def generic(*args, **kwargs):
  188. ... # do something with args and kwargs
  189. Such functions can also be created using pybind11:
  190. .. code-block:: cpp
  191. void generic(py::args args, py::kwargs kwargs) {
  192. /// .. do something with args
  193. if (kwargs)
  194. /// .. do something with kwargs
  195. }
  196. /// Binding code
  197. m.def("generic", &generic);
  198. The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
  199. from ``py::dict``.
  200. You may also use just one or the other, and may combine these with other
  201. arguments as long as the ``py::args`` and ``py::kwargs`` arguments are the last
  202. arguments accepted by the function.
  203. Please refer to the other examples for details on how to iterate over these,
  204. and on how to cast their entries into C++ objects. A demonstration is also
  205. available in ``tests/test_kwargs_and_defaults.cpp``.
  206. .. note::
  207. When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
  208. *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
  209. arguments.
  210. Default arguments revisited
  211. ===========================
  212. The section on :ref:`default_args` previously discussed basic usage of default
  213. arguments using pybind11. One noteworthy aspect of their implementation is that
  214. default arguments are converted to Python objects right at declaration time.
  215. Consider the following example:
  216. .. code-block:: cpp
  217. py::class_<MyClass>("MyClass")
  218. .def("myFunction", py::arg("arg") = SomeType(123));
  219. In this case, pybind11 must already be set up to deal with values of the type
  220. ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
  221. exception will be thrown.
  222. Another aspect worth highlighting is that the "preview" of the default argument
  223. in the function signature is generated using the object's ``__repr__`` method.
  224. If not available, the signature may not be very helpful, e.g.:
  225. .. code-block:: pycon
  226. FUNCTIONS
  227. ...
  228. | myFunction(...)
  229. | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
  230. ...
  231. The first way of addressing this is by defining ``SomeType.__repr__``.
  232. Alternatively, it is possible to specify the human-readable preview of the
  233. default argument manually using the ``arg_v`` notation:
  234. .. code-block:: cpp
  235. py::class_<MyClass>("MyClass")
  236. .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
  237. Sometimes it may be necessary to pass a null pointer value as a default
  238. argument. In this case, remember to cast it to the underlying type in question,
  239. like so:
  240. .. code-block:: cpp
  241. py::class_<MyClass>("MyClass")
  242. .def("myFunction", py::arg("arg") = (SomeType *) nullptr);
  243. .. _nonconverting_arguments:
  244. Non-converting arguments
  245. ========================
  246. Certain argument types may support conversion from one type to another. Some
  247. examples of conversions are:
  248. * :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
  249. * Calling a method accepting a double with an integer argument
  250. * Calling a ``std::complex<float>`` argument with a non-complex python type
  251. (for example, with a float). (Requires the optional ``pybind11/complex.h``
  252. header).
  253. * Calling a function taking an Eigen matrix reference with a numpy array of the
  254. wrong type or of an incompatible data layout. (Requires the optional
  255. ``pybind11/eigen.h`` header).
  256. This behaviour is sometimes undesirable: the binding code may prefer to raise
  257. an error rather than convert the argument. This behaviour can be obtained
  258. through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
  259. object, such as:
  260. .. code-block:: cpp
  261. m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
  262. m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
  263. Attempting the call the second function (the one without ``.noconvert()``) with
  264. an integer will succeed, but attempting to call the ``.noconvert()`` version
  265. will fail with a ``TypeError``:
  266. .. code-block:: pycon
  267. >>> floats_preferred(4)
  268. 2.0
  269. >>> floats_only(4)
  270. Traceback (most recent call last):
  271. File "<stdin>", line 1, in <module>
  272. TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
  273. 1. (f: float) -> float
  274. Invoked with: 4
  275. You may, of course, combine this with the :var:`_a` shorthand notation (see
  276. :ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit
  277. the argument name by using the ``py::arg()`` constructor without an argument
  278. name, i.e. by specifying ``py::arg().noconvert()``.
  279. .. note::
  280. When specifying ``py::arg`` options it is necessary to provide the same
  281. number of options as the bound function has arguments. Thus if you want to
  282. enable no-convert behaviour for just one of several arguments, you will
  283. need to specify a ``py::arg()`` annotation for each argument with the
  284. no-convert argument modified to ``py::arg().noconvert()``.
  285. Overload resolution order
  286. =========================
  287. When a function or method with multiple overloads is called from Python,
  288. pybind11 determines which overload to call in two passes. The first pass
  289. attempts to call each overload without allowing argument conversion (as if
  290. every argument had been specified as ``py::arg().noconvert()`` as decribed
  291. above).
  292. If no overload succeeds in the no-conversion first pass, a second pass is
  293. attempted in which argument conversion is allowed (except where prohibited via
  294. an explicit ``py::arg().noconvert()`` attribute in the function definition).
  295. If the second pass also fails a ``TypeError`` is raised.
  296. Within each pass, overloads are tried in the order they were registered with
  297. pybind11.
  298. What this means in practice is that pybind11 will prefer any overload that does
  299. not require conversion of arguments to an overload that does, but otherwise prefers
  300. earlier-defined overloads to later-defined ones.
  301. .. note::
  302. pybind11 does *not* further prioritize based on the number/pattern of
  303. overloaded arguments. That is, pybind11 does not prioritize a function
  304. requiring one conversion over one requiring three, but only prioritizes
  305. overloads requiring no conversion at all to overloads that require
  306. conversion of at least one argument.