blob: a7807dcf0a0af913660157c267ad5f9bfbe760fc [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Functions
2#########
3
4Before proceeding with this section, make sure that you are already familiar
5with the basics of binding functions and classes, as explained in :doc:`/basics`
6and :doc:`/classes`. The following guide is applicable to both free and member
7functions, i.e. *methods* in Python.
8
Jason Rhinelander17d02832017-01-16 20:35:14 -05009.. _return_value_policies:
10
Dean Moldovan67b52d82016-10-16 19:12:43 +020011Return value policies
12=====================
13
Wenzel Jakob6ba98652016-10-24 23:48:20 +020014Python and C++ use fundamentally different ways of managing the memory and
15lifetime of objects managed by them. This can lead to issues when creating
16bindings for functions that return a non-trivial type. Just by looking at the
17type information, it is not clear whether Python should take charge of the
18returned value and eventually free its resources, or if this is handled on the
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010019C++ side. For this reason, pybind11 provides a several *return value policy*
Wenzel Jakob6ba98652016-10-24 23:48:20 +020020annotations that can be passed to the :func:`module::def` and
21:func:`class_::def` functions. The default policy is
22:enum:`return_value_policy::automatic`.
Dean Moldovan67b52d82016-10-16 19:12:43 +020023
Wenzel Jakob6ba98652016-10-24 23:48:20 +020024Return value policies are tricky, and it's very important to get them right.
25Just to illustrate what can go wrong, consider the following simple example:
Dean Moldovan67b52d82016-10-16 19:12:43 +020026
27.. code-block:: cpp
28
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010029 /* Function declaration */
Wenzel Jakob6ba98652016-10-24 23:48:20 +020030 Data *get_data() { return _data; /* (pointer to a static data structure) */ }
31 ...
Dean Moldovan67b52d82016-10-16 19:12:43 +020032
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010033 /* Binding code */
Wenzel Jakob6ba98652016-10-24 23:48:20 +020034 m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
35
36What's going on here? When ``get_data()`` is called from Python, the return
37value (a native C++ type) must be wrapped to turn it into a usable Python type.
38In this case, the default return value policy (:enum:`return_value_policy::automatic`)
39causes pybind11 to assume ownership of the static ``_data`` instance.
40
41When Python's garbage collector eventually deletes the Python
42wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
43delete()``) due to the implied ownership. At this point, the entire application
44will come crashing down, though errors could also be more subtle and involve
45silent data corruption.
46
47In the above example, the policy :enum:`return_value_policy::reference` should have
48been specified so that the global data instance is only *referenced* without any
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010049implied transfer of ownership, i.e.:
Wenzel Jakob6ba98652016-10-24 23:48:20 +020050
51.. code-block:: cpp
52
53 m.def("get_data", &get_data, return_value_policy::reference);
54
55On the other hand, this is not the right policy for many other situations,
56where ignoring ownership could lead to resource leaks.
57As a developer using pybind11, it's important to be familiar with the different
58return value policies, including which situation calls for which one of them.
59The following table provides an overview of available policies:
Dean Moldovan67b52d82016-10-16 19:12:43 +020060
61.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
62
63+--------------------------------------------------+----------------------------------------------------------------------------+
64| Return value policy | Description |
65+==================================================+============================================================================+
Dean Moldovan67b52d82016-10-16 19:12:43 +020066| :enum:`return_value_policy::take_ownership` | Reference an existing object (i.e. do not create a new copy) and take |
67| | ownership. Python will call the destructor and delete operator when the |
68| | object's reference count reaches zero. Undefined behavior ensues when the |
Wenzel Jakob6ba98652016-10-24 23:48:20 +020069| | C++ side does the same, or when the data was not dynamically allocated. |
Dean Moldovan67b52d82016-10-16 19:12:43 +020070+--------------------------------------------------+----------------------------------------------------------------------------+
71| :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python. |
72| | This policy is comparably safe because the lifetimes of the two instances |
73| | are decoupled. |
74+--------------------------------------------------+----------------------------------------------------------------------------+
75| :enum:`return_value_policy::move` | Use ``std::move`` to move the return value contents into a new instance |
76| | that will be owned by Python. This policy is comparably safe because the |
77| | lifetimes of the two instances (move source and destination) are decoupled.|
78+--------------------------------------------------+----------------------------------------------------------------------------+
79| :enum:`return_value_policy::reference` | Reference an existing object, but do not take ownership. The C++ side is |
80| | responsible for managing the object's lifetime and deallocating it when |
81| | it is no longer used. Warning: undefined behavior will ensue when the C++ |
82| | side deletes an object that is still referenced and used by Python. |
83+--------------------------------------------------+----------------------------------------------------------------------------+
84| :enum:`return_value_policy::reference_internal` | Indicates that the lifetime of the return value is tied to the lifetime |
85| | of a parent object, namely the implicit ``this``, or ``self`` argument of |
86| | the called method or property. Internally, this policy works just like |
87| | :enum:`return_value_policy::reference` but additionally applies a |
88| | ``keep_alive<0, 1>`` *call policy* (described in the next section) that |
89| | prevents the parent object from being garbage collected as long as the |
90| | return value is referenced by Python. This is the default policy for |
91| | property getters created via ``def_property``, ``def_readwrite``, etc. |
92+--------------------------------------------------+----------------------------------------------------------------------------+
jbarlow837830e852017-01-13 02:17:29 -080093| :enum:`return_value_policy::automatic` | **Default policy.** This policy falls back to the policy |
Wenzel Jakob6ba98652016-10-24 23:48:20 +020094| | :enum:`return_value_policy::take_ownership` when the return value is a |
thorinke72eaa42017-02-17 12:57:39 +010095| | pointer. Otherwise, it uses :enum:`return_value_policy::move` or |
96| | :enum:`return_value_policy::copy` for rvalue and lvalue references, |
97| | respectively. See above for a description of what all of these different |
98| | policies do. |
Wenzel Jakob6ba98652016-10-24 23:48:20 +020099+--------------------------------------------------+----------------------------------------------------------------------------+
100| :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
101| | return value is a pointer. This is the default conversion policy for |
102| | function arguments when calling Python functions manually from C++ code |
103| | (i.e. via handle::operator()). You probably won't need to use this. |
104+--------------------------------------------------+----------------------------------------------------------------------------+
105
Dean Moldovan03f627e2016-11-01 11:44:57 +0100106Return value policies can also be applied to properties:
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200107
108.. code-block:: cpp
109
110 class_<MyClass>(m, "MyClass")
Dean Moldovan03f627e2016-11-01 11:44:57 +0100111 .def_property("data", &MyClass::getData, &MyClass::setData,
112 py::return_value_policy::copy);
113
114Technically, the code above applies the policy to both the getter and the
115setter function, however, the setter doesn't really care about *return*
116value policies which makes this a convenient terse syntax. Alternatively,
117targeted arguments can be passed through the :class:`cpp_function` constructor:
118
119.. code-block:: cpp
120
121 class_<MyClass>(m, "MyClass")
122 .def_property("data"
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200123 py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
124 py::cpp_function(&MyClass::setData)
125 );
Dean Moldovan67b52d82016-10-16 19:12:43 +0200126
127.. warning::
128
129 Code with invalid return value policies might access unitialized memory or
130 free data structures multiple times, which can lead to hard-to-debug
131 non-determinism and segmentation faults, hence it is worth spending the
132 time to understand all the different options in the table above.
133
Wenzel Jakob6ba98652016-10-24 23:48:20 +0200134.. note::
135
136 One important aspect of the above policies is that they only apply to
137 instances which pybind11 has *not* seen before, in which case the policy
138 clarifies essential questions about the return value's lifetime and
139 ownership. When pybind11 knows the instance already (as identified by its
140 type and address in memory), it will return the existing Python object
141 wrapper rather than creating a new copy.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200142
143.. note::
144
145 The next section on :ref:`call_policies` discusses *call policies* that can be
146 specified *in addition* to a return value policy from the list above. Call
147 policies indicate reference relationships that can involve both return values
148 and parameters of functions.
149
150.. note::
151
152 As an alternative to elaborate call policies and lifetime management logic,
153 consider using smart pointers (see the section on :ref:`smart_pointers` for
154 details). Smart pointers can tell whether an object is still referenced from
155 C++ or Python, which generally eliminates the kinds of inconsistencies that
156 can lead to crashes or undefined behavior. For functions returning smart
157 pointers, it is not necessary to specify a return value policy.
158
159.. _call_policies:
160
161Additional call policies
162========================
163
Dean Moldovan57a9bbc2017-01-31 16:54:08 +0100164In addition to the above return value policies, further *call policies* can be
Dean Moldovan1ac19032017-03-16 11:22:26 +0100165specified to indicate dependencies between parameters or ensure a certain state
166for the function call.
jbarlow837830e852017-01-13 02:17:29 -0800167
Dean Moldovan1ac19032017-03-16 11:22:26 +0100168Keep alive
169----------
170
171In general, this policy is required when the C++ object is any kind of container
172and another object is being added to the container. ``keep_alive<Nurse, Patient>``
173indicates that the argument with index ``Patient`` should be kept alive at least
174until the argument with index ``Nurse`` is freed by the garbage collector. Argument
Dean Moldovan67b52d82016-10-16 19:12:43 +0200175indices start at one, while zero refers to the return value. For methods, index
176``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
177index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
178with value ``None`` is detected at runtime, the call policy does nothing.
179
180This feature internally relies on the ability to create a *weak reference* to
181the nurse object, which is permitted by all classes exposed via pybind11. When
182the nurse object does not support weak references, an exception will be thrown.
183
184Consider the following example: here, the binding code for a list append
185operation ties the lifetime of the newly added element to the underlying
186container:
187
188.. code-block:: cpp
189
190 py::class_<List>(m, "List")
191 .def("append", &List::append, py::keep_alive<1, 2>());
192
193.. note::
194
195 ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
196 Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
197 0) policies from Boost.Python.
198
Dean Moldovan1ac19032017-03-16 11:22:26 +0100199Call guard
200----------
201
202The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed
203around the function call. For example, this definition:
204
205.. code-block:: cpp
206
207 m.def("foo", foo, py::call_guard<T>());
208
209is equivalent to the following pseudocode:
210
211.. code-block:: cpp
212
213 m.def("foo", [](args...) {
214 T scope_guard;
215 return foo(args...); // forwarded arguments
216 });
217
218The only requirement is that ``T`` is default-constructible, but otherwise any
219scope guard will work. This is very useful in combination with `gil_scoped_release`.
220See :ref:`gil`.
221
222Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The
223constructor order is left to right and destruction happens in reverse.
224
Dean Moldovan67b52d82016-10-16 19:12:43 +0200225.. seealso::
226
Dean Moldovan1ac19032017-03-16 11:22:26 +0100227 The file :file:`tests/test_call_policies.cpp` contains a complete example
228 that demonstrates using `keep_alive` and `call_guard` in more detail.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200229
230.. _python_objects_as_args:
231
232Python objects as arguments
233===========================
234
235pybind11 exposes all major Python types using thin C++ wrapper classes. These
236wrapper classes can also be used as parameters of functions in bindings, which
237makes it possible to directly work with native Python types on the C++ side.
238For instance, the following statement iterates over a Python ``dict``:
239
240.. code-block:: cpp
241
242 void print_dict(py::dict dict) {
243 /* Easily interact with Python types */
244 for (auto item : dict)
myd73499b815ad2017-01-13 18:15:52 +0800245 std::cout << "key=" << std::string(py::str(item.first)) << ", "
246 << "value=" << std::string(py::str(item.second)) << std::endl;
Dean Moldovan67b52d82016-10-16 19:12:43 +0200247 }
248
249It can be exported:
250
251.. code-block:: cpp
252
253 m.def("print_dict", &print_dict);
254
255And used in Python as usual:
256
257.. code-block:: pycon
258
259 >>> print_dict({'foo': 123, 'bar': 'hello'})
260 key=foo, value=123
261 key=bar, value=hello
262
263For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
264
265Accepting \*args and \*\*kwargs
266===============================
267
268Python provides a useful mechanism to define functions that accept arbitrary
269numbers of arguments and keyword arguments:
270
271.. code-block:: python
272
273 def generic(*args, **kwargs):
274 ... # do something with args and kwargs
275
276Such functions can also be created using pybind11:
277
278.. code-block:: cpp
279
280 void generic(py::args args, py::kwargs kwargs) {
281 /// .. do something with args
282 if (kwargs)
283 /// .. do something with kwargs
284 }
285
286 /// Binding code
287 m.def("generic", &generic);
288
289The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
Jason Rhinelander2686da82017-01-21 23:42:14 -0500290from ``py::dict``.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200291
Jason Rhinelander2686da82017-01-21 23:42:14 -0500292You may also use just one or the other, and may combine these with other
293arguments as long as the ``py::args`` and ``py::kwargs`` arguments are the last
294arguments accepted by the function.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200295
Jason Rhinelander2686da82017-01-21 23:42:14 -0500296Please refer to the other examples for details on how to iterate over these,
297and on how to cast their entries into C++ objects. A demonstration is also
298available in ``tests/test_kwargs_and_defaults.cpp``.
299
300.. note::
301
302 When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
303 *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
304 arguments.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200305
306Default arguments revisited
307===========================
308
309The section on :ref:`default_args` previously discussed basic usage of default
310arguments using pybind11. One noteworthy aspect of their implementation is that
311default arguments are converted to Python objects right at declaration time.
312Consider the following example:
313
314.. code-block:: cpp
315
316 py::class_<MyClass>("MyClass")
317 .def("myFunction", py::arg("arg") = SomeType(123));
318
319In this case, pybind11 must already be set up to deal with values of the type
320``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
321exception will be thrown.
322
323Another aspect worth highlighting is that the "preview" of the default argument
324in the function signature is generated using the object's ``__repr__`` method.
325If not available, the signature may not be very helpful, e.g.:
326
327.. code-block:: pycon
328
329 FUNCTIONS
330 ...
331 | myFunction(...)
332 | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
333 ...
334
335The first way of addressing this is by defining ``SomeType.__repr__``.
336Alternatively, it is possible to specify the human-readable preview of the
337default argument manually using the ``arg_v`` notation:
338
339.. code-block:: cpp
340
341 py::class_<MyClass>("MyClass")
342 .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
343
344Sometimes it may be necessary to pass a null pointer value as a default
345argument. In this case, remember to cast it to the underlying type in question,
346like so:
347
348.. code-block:: cpp
349
350 py::class_<MyClass>("MyClass")
351 .def("myFunction", py::arg("arg") = (SomeType *) nullptr);
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500352
Jason Rhinelander17d02832017-01-16 20:35:14 -0500353.. _nonconverting_arguments:
354
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500355Non-converting arguments
356========================
357
358Certain argument types may support conversion from one type to another. Some
359examples of conversions are:
360
361* :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
362* Calling a method accepting a double with an integer argument
363* Calling a ``std::complex<float>`` argument with a non-complex python type
364 (for example, with a float). (Requires the optional ``pybind11/complex.h``
365 header).
366* Calling a function taking an Eigen matrix reference with a numpy array of the
367 wrong type or of an incompatible data layout. (Requires the optional
368 ``pybind11/eigen.h`` header).
369
370This behaviour is sometimes undesirable: the binding code may prefer to raise
371an error rather than convert the argument. This behaviour can be obtained
372through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
373object, such as:
374
375.. code-block:: cpp
376
377 m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
378 m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
379
380Attempting the call the second function (the one without ``.noconvert()``) with
381an integer will succeed, but attempting to call the ``.noconvert()`` version
382will fail with a ``TypeError``:
383
384.. code-block:: pycon
385
386 >>> floats_preferred(4)
387 2.0
388 >>> floats_only(4)
389 Traceback (most recent call last):
390 File "<stdin>", line 1, in <module>
391 TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
392 1. (f: float) -> float
393
394 Invoked with: 4
395
396You may, of course, combine this with the :var:`_a` shorthand notation (see
397:ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit
398the argument name by using the ``py::arg()`` constructor without an argument
399name, i.e. by specifying ``py::arg().noconvert()``.
400
401.. note::
402
403 When specifying ``py::arg`` options it is necessary to provide the same
404 number of options as the bound function has arguments. Thus if you want to
405 enable no-convert behaviour for just one of several arguments, you will
406 need to specify a ``py::arg()`` annotation for each argument with the
407 no-convert argument modified to ``py::arg().noconvert()``.
Jason Rhinelandere5505892017-02-03 18:25:34 -0500408
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400409Allow/Prohibiting None arguments
410================================
411
412When a C++ type registered with :class:`py::class_` is passed as an argument to
413a function taking the instance as pointer or shared holder (e.g. ``shared_ptr``
414or a custom, copyable holder as described in :ref:`smart_pointers`), pybind
415allows ``None`` to be passed from Python which results in calling the C++
416function with ``nullptr`` (or an empty holder) for the argument.
417
418To explicitly enable or disable this behaviour, using the
419``.none`` method of the :class:`py::arg` object:
420
421.. code-block:: cpp
422
423 py::class_<Dog>(m, "Dog").def(py::init<>());
424 py::class_<Cat>(m, "Cat").def(py::init<>());
425 m.def("bark", [](Dog *dog) -> std::string {
426 if (dog) return "woof!"; /* Called with a Dog instance */
427 else return "(no dog)"; /* Called with None, d == nullptr */
428 }, py::arg("dog").none(true));
429 m.def("meow", [](Cat *cat) -> std::string {
430 // Can't be called with None argument
431 return "meow";
432 }, py::arg("cat").none(false));
433
434With the above, the Python call ``bark(None)`` will return the string ``"(no
Jason Rhinelander4f9ee6e2017-05-26 23:20:48 -0400435dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400436
437.. code-block:: pycon
438
439 >>> from animals import Dog, Cat, bark, meow
440 >>> bark(Dog())
441 'woof!'
442 >>> meow(Cat())
443 'meow'
444 >>> bark(None)
445 '(no dog)'
446 >>> meow(None)
447 Traceback (most recent call last):
448 File "<stdin>", line 1, in <module>
449 TypeError: meow(): incompatible function arguments. The following argument types are supported:
450 1. (cat: animals.Cat) -> str
451
452 Invoked with: None
453
454The default behaviour when the tag is unspecified is to allow ``None``.
455
Jason Rhinelandere5505892017-02-03 18:25:34 -0500456Overload resolution order
457=========================
458
459When a function or method with multiple overloads is called from Python,
460pybind11 determines which overload to call in two passes. The first pass
461attempts to call each overload without allowing argument conversion (as if
462every argument had been specified as ``py::arg().noconvert()`` as decribed
463above).
464
465If no overload succeeds in the no-conversion first pass, a second pass is
466attempted in which argument conversion is allowed (except where prohibited via
467an explicit ``py::arg().noconvert()`` attribute in the function definition).
468
469If the second pass also fails a ``TypeError`` is raised.
470
471Within each pass, overloads are tried in the order they were registered with
472pybind11.
473
474What this means in practice is that pybind11 will prefer any overload that does
475not require conversion of arguments to an overload that does, but otherwise prefers
476earlier-defined overloads to later-defined ones.
477
478.. note::
479
480 pybind11 does *not* further prioritize based on the number/pattern of
481 overloaded arguments. That is, pybind11 does not prioritize a function
482 requiring one conversion over one requiring three, but only prioritizes
483 overloads requiring no conversion at all to overloads that require
484 conversion of at least one argument.