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 | |
Jason Rhinelander | 17d0283 | 2017-01-16 20:35:14 -0500 | [diff] [blame] | 9 | .. _return_value_policies: |
| 10 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 11 | Return value policies |
| 12 | ===================== |
| 13 | |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 14 | Python and C++ use fundamentally different ways of managing the memory and |
| 15 | lifetime of objects managed by them. This can lead to issues when creating |
| 16 | bindings for functions that return a non-trivial type. Just by looking at the |
| 17 | type information, it is not clear whether Python should take charge of the |
| 18 | returned value and eventually free its resources, or if this is handled on the |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 19 | C++ side. For this reason, pybind11 provides a several *return value policy* |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 20 | annotations 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 Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 23 | |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 24 | Return value policies are tricky, and it's very important to get them right. |
| 25 | Just to illustrate what can go wrong, consider the following simple example: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 26 | |
| 27 | .. code-block:: cpp |
| 28 | |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 29 | /* Function declaration */ |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 30 | Data *get_data() { return _data; /* (pointer to a static data structure) */ } |
| 31 | ... |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 32 | |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 33 | /* Binding code */ |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 34 | m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python |
| 35 | |
| 36 | What's going on here? When ``get_data()`` is called from Python, the return |
| 37 | value (a native C++ type) must be wrapped to turn it into a usable Python type. |
| 38 | In this case, the default return value policy (:enum:`return_value_policy::automatic`) |
| 39 | causes pybind11 to assume ownership of the static ``_data`` instance. |
| 40 | |
| 41 | When Python's garbage collector eventually deletes the Python |
| 42 | wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator |
| 43 | delete()``) due to the implied ownership. At this point, the entire application |
| 44 | will come crashing down, though errors could also be more subtle and involve |
| 45 | silent data corruption. |
| 46 | |
| 47 | In the above example, the policy :enum:`return_value_policy::reference` should have |
| 48 | been specified so that the global data instance is only *referenced* without any |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 49 | implied transfer of ownership, i.e.: |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 50 | |
| 51 | .. code-block:: cpp |
| 52 | |
| 53 | m.def("get_data", &get_data, return_value_policy::reference); |
| 54 | |
| 55 | On the other hand, this is not the right policy for many other situations, |
| 56 | where ignoring ownership could lead to resource leaks. |
| 57 | As a developer using pybind11, it's important to be familiar with the different |
| 58 | return value policies, including which situation calls for which one of them. |
| 59 | The following table provides an overview of available policies: |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 60 | |
| 61 | .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}| |
| 62 | |
| 63 | +--------------------------------------------------+----------------------------------------------------------------------------+ |
| 64 | | Return value policy | Description | |
| 65 | +==================================================+============================================================================+ |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 66 | | :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 Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 69 | | | C++ side does the same, or when the data was not dynamically allocated. | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 70 | +--------------------------------------------------+----------------------------------------------------------------------------+ |
| 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 | +--------------------------------------------------+----------------------------------------------------------------------------+ |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 93 | | :enum:`return_value_policy::automatic` | **Default policy.** This policy falls back to the policy | |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 94 | | | :enum:`return_value_policy::take_ownership` when the return value is a | |
thorink | e72eaa4 | 2017-02-17 12:57:39 +0100 | [diff] [blame] | 95 | | | 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 Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 99 | +--------------------------------------------------+----------------------------------------------------------------------------+ |
| 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 Moldovan | 03f627e | 2016-11-01 11:44:57 +0100 | [diff] [blame] | 106 | Return value policies can also be applied to properties: |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 107 | |
| 108 | .. code-block:: cpp |
| 109 | |
| 110 | class_<MyClass>(m, "MyClass") |
Dean Moldovan | 03f627e | 2016-11-01 11:44:57 +0100 | [diff] [blame] | 111 | .def_property("data", &MyClass::getData, &MyClass::setData, |
| 112 | py::return_value_policy::copy); |
| 113 | |
| 114 | Technically, the code above applies the policy to both the getter and the |
| 115 | setter function, however, the setter doesn't really care about *return* |
| 116 | value policies which makes this a convenient terse syntax. Alternatively, |
| 117 | targeted 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 Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 123 | py::cpp_function(&MyClass::getData, py::return_value_policy::copy), |
| 124 | py::cpp_function(&MyClass::setData) |
| 125 | ); |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 126 | |
| 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 Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 134 | .. 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 Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 142 | |
| 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 | |
| 161 | Additional call policies |
| 162 | ======================== |
| 163 | |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 164 | In addition to the above return value policies, further *call policies* can be |
Dean Moldovan | 1ac1903 | 2017-03-16 11:22:26 +0100 | [diff] [blame] | 165 | specified to indicate dependencies between parameters or ensure a certain state |
| 166 | for the function call. |
jbarlow83 | 7830e85 | 2017-01-13 02:17:29 -0800 | [diff] [blame] | 167 | |
Dean Moldovan | 1ac1903 | 2017-03-16 11:22:26 +0100 | [diff] [blame] | 168 | Keep alive |
| 169 | ---------- |
| 170 | |
| 171 | In general, this policy is required when the C++ object is any kind of container |
| 172 | and another object is being added to the container. ``keep_alive<Nurse, Patient>`` |
| 173 | indicates that the argument with index ``Patient`` should be kept alive at least |
| 174 | until the argument with index ``Nurse`` is freed by the garbage collector. Argument |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 175 | indices 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 |
| 177 | index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse`` |
| 178 | with value ``None`` is detected at runtime, the call policy does nothing. |
| 179 | |
| 180 | This feature internally relies on the ability to create a *weak reference* to |
| 181 | the nurse object, which is permitted by all classes exposed via pybind11. When |
| 182 | the nurse object does not support weak references, an exception will be thrown. |
| 183 | |
| 184 | Consider the following example: here, the binding code for a list append |
| 185 | operation ties the lifetime of the newly added element to the underlying |
| 186 | container: |
| 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 Moldovan | 1ac1903 | 2017-03-16 11:22:26 +0100 | [diff] [blame] | 199 | Call guard |
| 200 | ---------- |
| 201 | |
| 202 | The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed |
| 203 | around the function call. For example, this definition: |
| 204 | |
| 205 | .. code-block:: cpp |
| 206 | |
| 207 | m.def("foo", foo, py::call_guard<T>()); |
| 208 | |
| 209 | is 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 | |
| 218 | The only requirement is that ``T`` is default-constructible, but otherwise any |
| 219 | scope guard will work. This is very useful in combination with `gil_scoped_release`. |
| 220 | See :ref:`gil`. |
| 221 | |
| 222 | Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The |
| 223 | constructor order is left to right and destruction happens in reverse. |
| 224 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 225 | .. seealso:: |
| 226 | |
Dean Moldovan | 1ac1903 | 2017-03-16 11:22:26 +0100 | [diff] [blame] | 227 | 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 Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 229 | |
| 230 | .. _python_objects_as_args: |
| 231 | |
| 232 | Python objects as arguments |
| 233 | =========================== |
| 234 | |
| 235 | pybind11 exposes all major Python types using thin C++ wrapper classes. These |
| 236 | wrapper classes can also be used as parameters of functions in bindings, which |
| 237 | makes it possible to directly work with native Python types on the C++ side. |
| 238 | For 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) |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 245 | std::cout << "key=" << std::string(py::str(item.first)) << ", " |
| 246 | << "value=" << std::string(py::str(item.second)) << std::endl; |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 247 | } |
| 248 | |
| 249 | It can be exported: |
| 250 | |
| 251 | .. code-block:: cpp |
| 252 | |
| 253 | m.def("print_dict", &print_dict); |
| 254 | |
| 255 | And 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 | |
| 263 | For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`. |
| 264 | |
| 265 | Accepting \*args and \*\*kwargs |
| 266 | =============================== |
| 267 | |
| 268 | Python provides a useful mechanism to define functions that accept arbitrary |
| 269 | numbers of arguments and keyword arguments: |
| 270 | |
| 271 | .. code-block:: python |
| 272 | |
| 273 | def generic(*args, **kwargs): |
| 274 | ... # do something with args and kwargs |
| 275 | |
| 276 | Such 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 | |
| 289 | The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives |
Jason Rhinelander | 2686da8 | 2017-01-21 23:42:14 -0500 | [diff] [blame] | 290 | from ``py::dict``. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 291 | |
Jason Rhinelander | 2686da8 | 2017-01-21 23:42:14 -0500 | [diff] [blame] | 292 | You may also use just one or the other, and may combine these with other |
| 293 | arguments as long as the ``py::args`` and ``py::kwargs`` arguments are the last |
| 294 | arguments accepted by the function. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 295 | |
Jason Rhinelander | 2686da8 | 2017-01-21 23:42:14 -0500 | [diff] [blame] | 296 | Please refer to the other examples for details on how to iterate over these, |
| 297 | and on how to cast their entries into C++ objects. A demonstration is also |
| 298 | available 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 Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 305 | |
| 306 | Default arguments revisited |
| 307 | =========================== |
| 308 | |
| 309 | The section on :ref:`default_args` previously discussed basic usage of default |
| 310 | arguments using pybind11. One noteworthy aspect of their implementation is that |
| 311 | default arguments are converted to Python objects right at declaration time. |
| 312 | Consider the following example: |
| 313 | |
| 314 | .. code-block:: cpp |
| 315 | |
| 316 | py::class_<MyClass>("MyClass") |
| 317 | .def("myFunction", py::arg("arg") = SomeType(123)); |
| 318 | |
| 319 | In 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 |
| 321 | exception will be thrown. |
| 322 | |
| 323 | Another aspect worth highlighting is that the "preview" of the default argument |
| 324 | in the function signature is generated using the object's ``__repr__`` method. |
| 325 | If 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 | |
| 335 | The first way of addressing this is by defining ``SomeType.__repr__``. |
| 336 | Alternatively, it is possible to specify the human-readable preview of the |
| 337 | default 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 | |
| 344 | Sometimes it may be necessary to pass a null pointer value as a default |
| 345 | argument. In this case, remember to cast it to the underlying type in question, |
| 346 | like so: |
| 347 | |
| 348 | .. code-block:: cpp |
| 349 | |
| 350 | py::class_<MyClass>("MyClass") |
| 351 | .def("myFunction", py::arg("arg") = (SomeType *) nullptr); |
Jason Rhinelander | abc29ca | 2017-01-23 03:50:00 -0500 | [diff] [blame] | 352 | |
Jason Rhinelander | 17d0283 | 2017-01-16 20:35:14 -0500 | [diff] [blame] | 353 | .. _nonconverting_arguments: |
| 354 | |
Jason Rhinelander | abc29ca | 2017-01-23 03:50:00 -0500 | [diff] [blame] | 355 | Non-converting arguments |
| 356 | ======================== |
| 357 | |
| 358 | Certain argument types may support conversion from one type to another. Some |
| 359 | examples 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 | |
| 370 | This behaviour is sometimes undesirable: the binding code may prefer to raise |
| 371 | an error rather than convert the argument. This behaviour can be obtained |
| 372 | through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg`` |
| 373 | object, 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 | |
| 380 | Attempting the call the second function (the one without ``.noconvert()``) with |
| 381 | an integer will succeed, but attempting to call the ``.noconvert()`` version |
| 382 | will 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 | |
| 396 | You 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 |
| 398 | the argument name by using the ``py::arg()`` constructor without an argument |
| 399 | name, 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 Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 408 | |
Jason Rhinelander | 4e1e4a5 | 2017-05-17 11:55:43 -0400 | [diff] [blame] | 409 | Allow/Prohibiting None arguments |
| 410 | ================================ |
| 411 | |
| 412 | When a C++ type registered with :class:`py::class_` is passed as an argument to |
| 413 | a function taking the instance as pointer or shared holder (e.g. ``shared_ptr`` |
| 414 | or a custom, copyable holder as described in :ref:`smart_pointers`), pybind |
| 415 | allows ``None`` to be passed from Python which results in calling the C++ |
| 416 | function with ``nullptr`` (or an empty holder) for the argument. |
| 417 | |
| 418 | To 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 | |
| 434 | With the above, the Python call ``bark(None)`` will return the string ``"(no |
Jason Rhinelander | 4f9ee6e | 2017-05-26 23:20:48 -0400 | [diff] [blame] | 435 | dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``: |
Jason Rhinelander | 4e1e4a5 | 2017-05-17 11:55:43 -0400 | [diff] [blame] | 436 | |
| 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 | |
| 454 | The default behaviour when the tag is unspecified is to allow ``None``. |
| 455 | |
Jason Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 456 | Overload resolution order |
| 457 | ========================= |
| 458 | |
| 459 | When a function or method with multiple overloads is called from Python, |
| 460 | pybind11 determines which overload to call in two passes. The first pass |
| 461 | attempts to call each overload without allowing argument conversion (as if |
| 462 | every argument had been specified as ``py::arg().noconvert()`` as decribed |
| 463 | above). |
| 464 | |
| 465 | If no overload succeeds in the no-conversion first pass, a second pass is |
| 466 | attempted in which argument conversion is allowed (except where prohibited via |
| 467 | an explicit ``py::arg().noconvert()`` attribute in the function definition). |
| 468 | |
| 469 | If the second pass also fails a ``TypeError`` is raised. |
| 470 | |
| 471 | Within each pass, overloads are tried in the order they were registered with |
| 472 | pybind11. |
| 473 | |
| 474 | What this means in practice is that pybind11 will prefer any overload that does |
| 475 | not require conversion of arguments to an overload that does, but otherwise prefers |
| 476 | earlier-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. |