Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 1 | Functions |
| 2 | ######### |
| 3 | |
| 4 | Before proceeding with this section, make sure that you are already familiar |
| 5 | with the basics of binding functions and classes, as explained in :doc:`/basics` |
| 6 | and :doc:`/classes`. The following guide is applicable to both free and member |
| 7 | functions, i.e. *methods* in Python. |
| 8 | |
| 9 | Return value policies |
| 10 | ===================== |
| 11 | |
| 12 | Python and C++ use wildly different ways of managing the memory and lifetime of |
| 13 | objects managed by them. This can lead to issues when creating bindings for |
| 14 | functions that return a non-trivial type. Just by looking at the type |
| 15 | information, it is not clear whether Python should take charge of the returned |
| 16 | value and eventually free its resources, or if this is handled on the C++ side. |
| 17 | For this reason, pybind11 provides a several `return value policy` annotations |
| 18 | that can be passed to the :func:`module::def` and :func:`class_::def` |
| 19 | functions. The default policy is :enum:`return_value_policy::automatic`. |
| 20 | |
| 21 | Return value policies can also be applied to properties, in which case the |
| 22 | arguments 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 | |
| 32 | The 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 | |
| 85 | One important aspect of the above policies is that they only apply to instances |
| 86 | which pybind11 has *not* seen before, in which case the policy clarifies |
| 87 | essential questions about the return value's lifetime and ownership. When |
| 88 | pybind11 knows the instance already (as identified by its type and address in |
| 89 | memory), it will return the existing Python object wrapper rather than creating |
| 90 | a 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 | |
| 110 | Additional call policies |
| 111 | ======================== |
| 112 | |
| 113 | In addition to the above return value policies, further `call policies` can be |
| 114 | specified to indicate dependencies between parameters. There is currently just |
| 115 | one policy named ``keep_alive<Nurse, Patient>``, which indicates that the |
| 116 | argument with index ``Patient`` should be kept alive at least until the |
| 117 | argument with index ``Nurse`` is freed by the garbage collector. Argument |
| 118 | indices 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 |
| 120 | index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse`` |
| 121 | with value ``None`` is detected at runtime, the call policy does nothing. |
| 122 | |
| 123 | This feature internally relies on the ability to create a *weak reference* to |
| 124 | the nurse object, which is permitted by all classes exposed via pybind11. When |
| 125 | the nurse object does not support weak references, an exception will be thrown. |
| 126 | |
| 127 | Consider the following example: here, the binding code for a list append |
| 128 | operation ties the lifetime of the newly added element to the underlying |
| 129 | container: |
| 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 | |
| 149 | Python objects as arguments |
| 150 | =========================== |
| 151 | |
| 152 | pybind11 exposes all major Python types using thin C++ wrapper classes. These |
| 153 | wrapper classes can also be used as parameters of functions in bindings, which |
| 154 | makes it possible to directly work with native Python types on the C++ side. |
| 155 | For 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 | |
| 166 | It can be exported: |
| 167 | |
| 168 | .. code-block:: cpp |
| 169 | |
| 170 | m.def("print_dict", &print_dict); |
| 171 | |
| 172 | And 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 | |
| 180 | For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`. |
| 181 | |
| 182 | Accepting \*args and \*\*kwargs |
| 183 | =============================== |
| 184 | |
| 185 | Python provides a useful mechanism to define functions that accept arbitrary |
| 186 | numbers of arguments and keyword arguments: |
| 187 | |
| 188 | .. code-block:: python |
| 189 | |
| 190 | def generic(*args, **kwargs): |
| 191 | ... # do something with args and kwargs |
| 192 | |
| 193 | Such 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 | |
| 206 | The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives |
| 207 | from ``py::dict``. Note that the ``kwargs`` argument is invalid if no keyword |
| 208 | arguments were actually provided. Please refer to the other examples for |
| 209 | details on how to iterate over these, and on how to cast their entries into |
| 210 | C++ 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 | |
| 218 | Default arguments revisited |
| 219 | =========================== |
| 220 | |
| 221 | The section on :ref:`default_args` previously discussed basic usage of default |
| 222 | arguments using pybind11. One noteworthy aspect of their implementation is that |
| 223 | default arguments are converted to Python objects right at declaration time. |
| 224 | Consider the following example: |
| 225 | |
| 226 | .. code-block:: cpp |
| 227 | |
| 228 | py::class_<MyClass>("MyClass") |
| 229 | .def("myFunction", py::arg("arg") = SomeType(123)); |
| 230 | |
| 231 | In 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 |
| 233 | exception will be thrown. |
| 234 | |
| 235 | Another aspect worth highlighting is that the "preview" of the default argument |
| 236 | in the function signature is generated using the object's ``__repr__`` method. |
| 237 | If 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 | |
| 247 | The first way of addressing this is by defining ``SomeType.__repr__``. |
| 248 | Alternatively, it is possible to specify the human-readable preview of the |
| 249 | default 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 | |
| 256 | Sometimes it may be necessary to pass a null pointer value as a default |
| 257 | argument. In this case, remember to cast it to the underlying type in question, |
| 258 | like so: |
| 259 | |
| 260 | .. code-block:: cpp |
| 261 | |
| 262 | py::class_<MyClass>("MyClass") |
| 263 | .def("myFunction", py::arg("arg") = (SomeType *) nullptr); |