blob: 5c697b12c18fbf977fed1ea4113f472e56bcd249 [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
9Return value policies
10=====================
11
12Python and C++ use wildly different ways of managing the memory and lifetime of
13objects managed by them. This can lead to issues when creating bindings for
14functions that return a non-trivial type. Just by looking at the type
15information, it is not clear whether Python should take charge of the returned
16value and eventually free its resources, or if this is handled on the C++ side.
17For this reason, pybind11 provides a several `return value policy` annotations
18that can be passed to the :func:`module::def` and :func:`class_::def`
19functions. The default policy is :enum:`return_value_policy::automatic`.
20
21Return value policies can also be applied to properties, in which case the
22arguments must be passed through the :class:`cpp_function` constructor:
23
24.. code-block:: cpp
25
26 class_<MyClass>(m, "MyClass")
27 def_property("data"
28 py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
29 py::cpp_function(&MyClass::setData)
30 );
31
32The following table provides an overview of the available return value policies:
33
34.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
35
36+--------------------------------------------------+----------------------------------------------------------------------------+
37| Return value policy | Description |
38+==================================================+============================================================================+
39| :enum:`return_value_policy::automatic` | This is the default return value policy, which falls back to the policy |
40| | :enum:`return_value_policy::take_ownership` when the return value is a |
41| | pointer. Otherwise, it uses :enum:`return_value::move` or |
42| | :enum:`return_value::copy` for rvalue and lvalue references, respectively. |
43| | See below for a description of what all of these different policies do. |
44+--------------------------------------------------+----------------------------------------------------------------------------+
45| :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
46| | return value is a pointer. This is the default conversion policy for |
47| | function arguments when calling Python functions manually from C++ code |
48| | (i.e. via handle::operator()). You probably won't need to use this. |
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. |
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
78.. warning::
79
80 Code with invalid return value policies might access unitialized memory or
81 free data structures multiple times, which can lead to hard-to-debug
82 non-determinism and segmentation faults, hence it is worth spending the
83 time to understand all the different options in the table above.
84
85One important aspect of the above policies is that they only apply to instances
86which pybind11 has *not* seen before, in which case the policy clarifies
87essential questions about the return value's lifetime and ownership. When
88pybind11 knows the instance already (as identified by its type and address in
89memory), it will return the existing Python object wrapper rather than creating
90a new copy.
91
92.. note::
93
94 The next section on :ref:`call_policies` discusses *call policies* that can be
95 specified *in addition* to a return value policy from the list above. Call
96 policies indicate reference relationships that can involve both return values
97 and parameters of functions.
98
99.. note::
100
101 As an alternative to elaborate call policies and lifetime management logic,
102 consider using smart pointers (see the section on :ref:`smart_pointers` for
103 details). Smart pointers can tell whether an object is still referenced from
104 C++ or Python, which generally eliminates the kinds of inconsistencies that
105 can lead to crashes or undefined behavior. For functions returning smart
106 pointers, it is not necessary to specify a return value policy.
107
108.. _call_policies:
109
110Additional call policies
111========================
112
113In addition to the above return value policies, further `call policies` can be
114specified to indicate dependencies between parameters. There is currently just
115one policy named ``keep_alive<Nurse, Patient>``, which indicates that the
116argument with index ``Patient`` should be kept alive at least until the
117argument with index ``Nurse`` is freed by the garbage collector. Argument
118indices start at one, while zero refers to the return value. For methods, index
119``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
120index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
121with value ``None`` is detected at runtime, the call policy does nothing.
122
123This feature internally relies on the ability to create a *weak reference* to
124the nurse object, which is permitted by all classes exposed via pybind11. When
125the nurse object does not support weak references, an exception will be thrown.
126
127Consider the following example: here, the binding code for a list append
128operation ties the lifetime of the newly added element to the underlying
129container:
130
131.. code-block:: cpp
132
133 py::class_<List>(m, "List")
134 .def("append", &List::append, py::keep_alive<1, 2>());
135
136.. note::
137
138 ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
139 Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
140 0) policies from Boost.Python.
141
142.. seealso::
143
144 The file :file:`tests/test_keep_alive.cpp` contains a complete example
145 that demonstrates using :class:`keep_alive` in more detail.
146
147.. _python_objects_as_args:
148
149Python objects as arguments
150===========================
151
152pybind11 exposes all major Python types using thin C++ wrapper classes. These
153wrapper classes can also be used as parameters of functions in bindings, which
154makes it possible to directly work with native Python types on the C++ side.
155For instance, the following statement iterates over a Python ``dict``:
156
157.. code-block:: cpp
158
159 void print_dict(py::dict dict) {
160 /* Easily interact with Python types */
161 for (auto item : dict)
162 std::cout << "key=" << item.first << ", "
163 << "value=" << item.second << std::endl;
164 }
165
166It can be exported:
167
168.. code-block:: cpp
169
170 m.def("print_dict", &print_dict);
171
172And used in Python as usual:
173
174.. code-block:: pycon
175
176 >>> print_dict({'foo': 123, 'bar': 'hello'})
177 key=foo, value=123
178 key=bar, value=hello
179
180For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
181
182Accepting \*args and \*\*kwargs
183===============================
184
185Python provides a useful mechanism to define functions that accept arbitrary
186numbers of arguments and keyword arguments:
187
188.. code-block:: python
189
190 def generic(*args, **kwargs):
191 ... # do something with args and kwargs
192
193Such functions can also be created using pybind11:
194
195.. code-block:: cpp
196
197 void generic(py::args args, py::kwargs kwargs) {
198 /// .. do something with args
199 if (kwargs)
200 /// .. do something with kwargs
201 }
202
203 /// Binding code
204 m.def("generic", &generic);
205
206The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
207from ``py::dict``. Note that the ``kwargs`` argument is invalid if no keyword
208arguments were actually provided. Please refer to the other examples for
209details on how to iterate over these, and on how to cast their entries into
210C++ objects. A demonstration is also available in
211``tests/test_kwargs_and_defaults.cpp``.
212
213.. warning::
214
215 Unlike Python, pybind11 does not allow combining normal parameters with the
216 ``args`` / ``kwargs`` special parameters.
217
218Default arguments revisited
219===========================
220
221The section on :ref:`default_args` previously discussed basic usage of default
222arguments using pybind11. One noteworthy aspect of their implementation is that
223default arguments are converted to Python objects right at declaration time.
224Consider the following example:
225
226.. code-block:: cpp
227
228 py::class_<MyClass>("MyClass")
229 .def("myFunction", py::arg("arg") = SomeType(123));
230
231In this case, pybind11 must already be set up to deal with values of the type
232``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
233exception will be thrown.
234
235Another aspect worth highlighting is that the "preview" of the default argument
236in the function signature is generated using the object's ``__repr__`` method.
237If not available, the signature may not be very helpful, e.g.:
238
239.. code-block:: pycon
240
241 FUNCTIONS
242 ...
243 | myFunction(...)
244 | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
245 ...
246
247The first way of addressing this is by defining ``SomeType.__repr__``.
248Alternatively, it is possible to specify the human-readable preview of the
249default argument manually using the ``arg_v`` notation:
250
251.. code-block:: cpp
252
253 py::class_<MyClass>("MyClass")
254 .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
255
256Sometimes it may be necessary to pass a null pointer value as a default
257argument. In this case, remember to cast it to the underlying type in question,
258like so:
259
260.. code-block:: cpp
261
262 py::class_<MyClass>("MyClass")
263 .def("myFunction", py::arg("arg") = (SomeType *) nullptr);