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* |
Henry Schreiner | 6bcd220 | 2020-10-03 13:38:03 -0400 | [diff] [blame] | 20 | annotations that can be passed to the :func:`module_::def` and |
Wenzel Jakob | 6ba9865 | 2016-10-24 23:48:20 +0200 | [diff] [blame] | 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 | |
luz.paz | 28cb676 | 2018-01-09 12:30:19 -0500 | [diff] [blame] | 129 | Code with invalid return value policies might access uninitialized memory or |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 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 | |
Bruce Merry | b490b44 | 2017-09-01 09:27:00 +0200 | [diff] [blame] | 180 | When the nurse is not a pybind11-registered type, the implementation internally |
| 181 | relies on the ability to create a *weak reference* to the nurse object. When |
| 182 | the nurse object is not a pybind11-registered type and does not support weak |
| 183 | references, an exception will be thrown. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 184 | |
| 185 | Consider the following example: here, the binding code for a list append |
| 186 | operation ties the lifetime of the newly added element to the underlying |
| 187 | container: |
| 188 | |
| 189 | .. code-block:: cpp |
| 190 | |
| 191 | py::class_<List>(m, "List") |
| 192 | .def("append", &List::append, py::keep_alive<1, 2>()); |
| 193 | |
Dean Moldovan | 7939f4b | 2017-09-04 13:49:19 +0200 | [diff] [blame] | 194 | For consistency, the argument indexing is identical for constructors. Index |
| 195 | ``1`` still refers to the implicit ``this`` pointer, i.e. the object which is |
| 196 | being constructed. Index ``0`` refers to the return type which is presumed to |
| 197 | be ``void`` when a constructor is viewed like a function. The following example |
| 198 | ties the lifetime of the constructor element to the constructed object: |
| 199 | |
| 200 | .. code-block:: cpp |
| 201 | |
| 202 | py::class_<Nurse>(m, "Nurse") |
| 203 | .def(py::init<Patient &>(), py::keep_alive<1, 2>()); |
| 204 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 205 | .. note:: |
| 206 | |
| 207 | ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse, |
| 208 | Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient == |
| 209 | 0) policies from Boost.Python. |
| 210 | |
Dean Moldovan | 1ac1903 | 2017-03-16 11:22:26 +0100 | [diff] [blame] | 211 | Call guard |
| 212 | ---------- |
| 213 | |
| 214 | The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed |
| 215 | around the function call. For example, this definition: |
| 216 | |
| 217 | .. code-block:: cpp |
| 218 | |
| 219 | m.def("foo", foo, py::call_guard<T>()); |
| 220 | |
| 221 | is equivalent to the following pseudocode: |
| 222 | |
| 223 | .. code-block:: cpp |
| 224 | |
| 225 | m.def("foo", [](args...) { |
| 226 | T scope_guard; |
| 227 | return foo(args...); // forwarded arguments |
| 228 | }); |
| 229 | |
| 230 | The only requirement is that ``T`` is default-constructible, but otherwise any |
| 231 | scope guard will work. This is very useful in combination with `gil_scoped_release`. |
| 232 | See :ref:`gil`. |
| 233 | |
| 234 | Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The |
| 235 | constructor order is left to right and destruction happens in reverse. |
| 236 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 237 | .. seealso:: |
| 238 | |
Dean Moldovan | 1ac1903 | 2017-03-16 11:22:26 +0100 | [diff] [blame] | 239 | The file :file:`tests/test_call_policies.cpp` contains a complete example |
| 240 | that demonstrates using `keep_alive` and `call_guard` in more detail. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 241 | |
| 242 | .. _python_objects_as_args: |
| 243 | |
| 244 | Python objects as arguments |
| 245 | =========================== |
| 246 | |
| 247 | pybind11 exposes all major Python types using thin C++ wrapper classes. These |
| 248 | wrapper classes can also be used as parameters of functions in bindings, which |
| 249 | makes it possible to directly work with native Python types on the C++ side. |
| 250 | For instance, the following statement iterates over a Python ``dict``: |
| 251 | |
| 252 | .. code-block:: cpp |
| 253 | |
| 254 | void print_dict(py::dict dict) { |
| 255 | /* Easily interact with Python types */ |
| 256 | for (auto item : dict) |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 257 | std::cout << "key=" << std::string(py::str(item.first)) << ", " |
| 258 | << "value=" << std::string(py::str(item.second)) << std::endl; |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 259 | } |
| 260 | |
| 261 | It can be exported: |
| 262 | |
| 263 | .. code-block:: cpp |
| 264 | |
| 265 | m.def("print_dict", &print_dict); |
| 266 | |
| 267 | And used in Python as usual: |
| 268 | |
| 269 | .. code-block:: pycon |
| 270 | |
| 271 | >>> print_dict({'foo': 123, 'bar': 'hello'}) |
| 272 | key=foo, value=123 |
| 273 | key=bar, value=hello |
| 274 | |
| 275 | For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`. |
| 276 | |
| 277 | Accepting \*args and \*\*kwargs |
| 278 | =============================== |
| 279 | |
| 280 | Python provides a useful mechanism to define functions that accept arbitrary |
| 281 | numbers of arguments and keyword arguments: |
| 282 | |
| 283 | .. code-block:: python |
| 284 | |
| 285 | def generic(*args, **kwargs): |
| 286 | ... # do something with args and kwargs |
| 287 | |
| 288 | Such functions can also be created using pybind11: |
| 289 | |
| 290 | .. code-block:: cpp |
| 291 | |
| 292 | void generic(py::args args, py::kwargs kwargs) { |
| 293 | /// .. do something with args |
| 294 | if (kwargs) |
| 295 | /// .. do something with kwargs |
| 296 | } |
| 297 | |
| 298 | /// Binding code |
| 299 | m.def("generic", &generic); |
| 300 | |
| 301 | The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives |
Jason Rhinelander | 2686da8 | 2017-01-21 23:42:14 -0500 | [diff] [blame] | 302 | from ``py::dict``. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 303 | |
Jason Rhinelander | 2686da8 | 2017-01-21 23:42:14 -0500 | [diff] [blame] | 304 | You may also use just one or the other, and may combine these with other |
| 305 | arguments as long as the ``py::args`` and ``py::kwargs`` arguments are the last |
| 306 | arguments accepted by the function. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 307 | |
Jason Rhinelander | 2686da8 | 2017-01-21 23:42:14 -0500 | [diff] [blame] | 308 | Please refer to the other examples for details on how to iterate over these, |
| 309 | and on how to cast their entries into C++ objects. A demonstration is also |
| 310 | available in ``tests/test_kwargs_and_defaults.cpp``. |
| 311 | |
| 312 | .. note:: |
| 313 | |
| 314 | When combining \*args or \*\*kwargs with :ref:`keyword_args` you should |
| 315 | *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs`` |
| 316 | arguments. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 317 | |
| 318 | Default arguments revisited |
| 319 | =========================== |
| 320 | |
| 321 | The section on :ref:`default_args` previously discussed basic usage of default |
| 322 | arguments using pybind11. One noteworthy aspect of their implementation is that |
| 323 | default arguments are converted to Python objects right at declaration time. |
| 324 | Consider the following example: |
| 325 | |
| 326 | .. code-block:: cpp |
| 327 | |
| 328 | py::class_<MyClass>("MyClass") |
| 329 | .def("myFunction", py::arg("arg") = SomeType(123)); |
| 330 | |
| 331 | In this case, pybind11 must already be set up to deal with values of the type |
| 332 | ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an |
| 333 | exception will be thrown. |
| 334 | |
| 335 | Another aspect worth highlighting is that the "preview" of the default argument |
| 336 | in the function signature is generated using the object's ``__repr__`` method. |
| 337 | If not available, the signature may not be very helpful, e.g.: |
| 338 | |
| 339 | .. code-block:: pycon |
| 340 | |
| 341 | FUNCTIONS |
| 342 | ... |
| 343 | | myFunction(...) |
| 344 | | Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType |
| 345 | ... |
| 346 | |
| 347 | The first way of addressing this is by defining ``SomeType.__repr__``. |
| 348 | Alternatively, it is possible to specify the human-readable preview of the |
| 349 | default argument manually using the ``arg_v`` notation: |
| 350 | |
| 351 | .. code-block:: cpp |
| 352 | |
| 353 | py::class_<MyClass>("MyClass") |
| 354 | .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)")); |
| 355 | |
| 356 | Sometimes it may be necessary to pass a null pointer value as a default |
| 357 | argument. In this case, remember to cast it to the underlying type in question, |
| 358 | like so: |
| 359 | |
| 360 | .. code-block:: cpp |
| 361 | |
| 362 | py::class_<MyClass>("MyClass") |
Boris Staletic | 32bb907 | 2020-09-14 20:07:29 +0200 | [diff] [blame] | 363 | .def("myFunction", py::arg("arg") = static_cast<SomeType *>(nullptr)); |
Jason Rhinelander | abc29ca | 2017-01-23 03:50:00 -0500 | [diff] [blame] | 364 | |
Jason Rhinelander | be0d804 | 2017-12-23 18:56:07 -0400 | [diff] [blame] | 365 | Keyword-only arguments |
| 366 | ====================== |
| 367 | |
| 368 | Python 3 introduced keyword-only arguments by specifying an unnamed ``*`` |
| 369 | argument in a function definition: |
| 370 | |
| 371 | .. code-block:: python |
| 372 | |
| 373 | def f(a, *, b): # a can be positional or via keyword; b must be via keyword |
| 374 | pass |
| 375 | |
| 376 | f(a=1, b=2) # good |
| 377 | f(b=2, a=1) # good |
| 378 | f(1, b=2) # good |
| 379 | f(1, 2) # TypeError: f() takes 1 positional argument but 2 were given |
| 380 | |
Henry Schreiner | 0dbda6e | 2020-09-04 20:02:05 -0400 | [diff] [blame] | 381 | Pybind11 provides a ``py::kw_only`` object that allows you to implement |
Jason Rhinelander | be0d804 | 2017-12-23 18:56:07 -0400 | [diff] [blame] | 382 | the same behaviour by specifying the object between positional and keyword-only |
| 383 | argument annotations when registering the function: |
| 384 | |
| 385 | .. code-block:: cpp |
| 386 | |
| 387 | m.def("f", [](int a, int b) { /* ... */ }, |
Henry Schreiner | 0dbda6e | 2020-09-04 20:02:05 -0400 | [diff] [blame] | 388 | py::arg("a"), py::kw_only(), py::arg("b")); |
Jason Rhinelander | be0d804 | 2017-12-23 18:56:07 -0400 | [diff] [blame] | 389 | |
Henry Schreiner | 0dbda6e | 2020-09-04 20:02:05 -0400 | [diff] [blame] | 390 | Note that you currently cannot combine this with a ``py::args`` argument. This |
| 391 | feature does *not* require Python 3 to work. |
| 392 | |
| 393 | .. versionadded:: 2.6 |
| 394 | |
| 395 | Positional-only arguments |
| 396 | ========================= |
| 397 | |
| 398 | Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the |
| 399 | function definition (note that this has been a convention for CPython |
| 400 | positional arguments, such as in ``pow()``, since Python 2). You can |
| 401 | do the same thing in any version of Python using ``py::pos_only()``: |
| 402 | |
| 403 | .. code-block:: cpp |
| 404 | |
| 405 | m.def("f", [](int a, int b) { /* ... */ }, |
| 406 | py::arg("a"), py::pos_only(), py::arg("b")); |
| 407 | |
| 408 | You now cannot give argument ``a`` by keyword. This can be combined with |
| 409 | keyword-only arguments, as well. |
Jason Rhinelander | be0d804 | 2017-12-23 18:56:07 -0400 | [diff] [blame] | 410 | |
Henry Schreiner | a6887b6 | 2020-08-19 14:53:59 -0400 | [diff] [blame] | 411 | .. versionadded:: 2.6 |
| 412 | |
Jason Rhinelander | 17d0283 | 2017-01-16 20:35:14 -0500 | [diff] [blame] | 413 | .. _nonconverting_arguments: |
| 414 | |
Jason Rhinelander | abc29ca | 2017-01-23 03:50:00 -0500 | [diff] [blame] | 415 | Non-converting arguments |
| 416 | ======================== |
| 417 | |
| 418 | Certain argument types may support conversion from one type to another. Some |
| 419 | examples of conversions are: |
| 420 | |
| 421 | * :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()`` |
| 422 | * Calling a method accepting a double with an integer argument |
| 423 | * Calling a ``std::complex<float>`` argument with a non-complex python type |
| 424 | (for example, with a float). (Requires the optional ``pybind11/complex.h`` |
| 425 | header). |
| 426 | * Calling a function taking an Eigen matrix reference with a numpy array of the |
| 427 | wrong type or of an incompatible data layout. (Requires the optional |
| 428 | ``pybind11/eigen.h`` header). |
| 429 | |
| 430 | This behaviour is sometimes undesirable: the binding code may prefer to raise |
| 431 | an error rather than convert the argument. This behaviour can be obtained |
| 432 | through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg`` |
| 433 | object, such as: |
| 434 | |
| 435 | .. code-block:: cpp |
| 436 | |
| 437 | m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert()); |
| 438 | m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f")); |
| 439 | |
| 440 | Attempting the call the second function (the one without ``.noconvert()``) with |
| 441 | an integer will succeed, but attempting to call the ``.noconvert()`` version |
| 442 | will fail with a ``TypeError``: |
| 443 | |
| 444 | .. code-block:: pycon |
| 445 | |
| 446 | >>> floats_preferred(4) |
| 447 | 2.0 |
| 448 | >>> floats_only(4) |
| 449 | Traceback (most recent call last): |
| 450 | File "<stdin>", line 1, in <module> |
| 451 | TypeError: floats_only(): incompatible function arguments. The following argument types are supported: |
| 452 | 1. (f: float) -> float |
| 453 | |
| 454 | Invoked with: 4 |
| 455 | |
| 456 | You may, of course, combine this with the :var:`_a` shorthand notation (see |
| 457 | :ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit |
| 458 | the argument name by using the ``py::arg()`` constructor without an argument |
| 459 | name, i.e. by specifying ``py::arg().noconvert()``. |
| 460 | |
| 461 | .. note:: |
| 462 | |
| 463 | When specifying ``py::arg`` options it is necessary to provide the same |
| 464 | number of options as the bound function has arguments. Thus if you want to |
| 465 | enable no-convert behaviour for just one of several arguments, you will |
| 466 | need to specify a ``py::arg()`` annotation for each argument with the |
| 467 | no-convert argument modified to ``py::arg().noconvert()``. |
Jason Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 468 | |
Dean Moldovan | db46a89 | 2017-08-13 22:25:15 +0200 | [diff] [blame] | 469 | .. _none_arguments: |
| 470 | |
Jason Rhinelander | 4e1e4a5 | 2017-05-17 11:55:43 -0400 | [diff] [blame] | 471 | Allow/Prohibiting None arguments |
| 472 | ================================ |
| 473 | |
| 474 | When a C++ type registered with :class:`py::class_` is passed as an argument to |
| 475 | a function taking the instance as pointer or shared holder (e.g. ``shared_ptr`` |
| 476 | or a custom, copyable holder as described in :ref:`smart_pointers`), pybind |
| 477 | allows ``None`` to be passed from Python which results in calling the C++ |
| 478 | function with ``nullptr`` (or an empty holder) for the argument. |
| 479 | |
| 480 | To explicitly enable or disable this behaviour, using the |
| 481 | ``.none`` method of the :class:`py::arg` object: |
| 482 | |
| 483 | .. code-block:: cpp |
| 484 | |
| 485 | py::class_<Dog>(m, "Dog").def(py::init<>()); |
| 486 | py::class_<Cat>(m, "Cat").def(py::init<>()); |
| 487 | m.def("bark", [](Dog *dog) -> std::string { |
| 488 | if (dog) return "woof!"; /* Called with a Dog instance */ |
Tomas Babej | 01fada7 | 2018-01-28 10:16:27 -0500 | [diff] [blame] | 489 | else return "(no dog)"; /* Called with None, dog == nullptr */ |
Jason Rhinelander | 4e1e4a5 | 2017-05-17 11:55:43 -0400 | [diff] [blame] | 490 | }, py::arg("dog").none(true)); |
| 491 | m.def("meow", [](Cat *cat) -> std::string { |
| 492 | // Can't be called with None argument |
| 493 | return "meow"; |
| 494 | }, py::arg("cat").none(false)); |
| 495 | |
| 496 | 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] | 497 | dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``: |
Jason Rhinelander | 4e1e4a5 | 2017-05-17 11:55:43 -0400 | [diff] [blame] | 498 | |
| 499 | .. code-block:: pycon |
| 500 | |
| 501 | >>> from animals import Dog, Cat, bark, meow |
| 502 | >>> bark(Dog()) |
| 503 | 'woof!' |
| 504 | >>> meow(Cat()) |
| 505 | 'meow' |
| 506 | >>> bark(None) |
| 507 | '(no dog)' |
| 508 | >>> meow(None) |
| 509 | Traceback (most recent call last): |
| 510 | File "<stdin>", line 1, in <module> |
| 511 | TypeError: meow(): incompatible function arguments. The following argument types are supported: |
| 512 | 1. (cat: animals.Cat) -> str |
| 513 | |
| 514 | Invoked with: None |
| 515 | |
| 516 | The default behaviour when the tag is unspecified is to allow ``None``. |
| 517 | |
Sergei Izmailov | 979d75d | 2019-06-10 22:03:17 +0300 | [diff] [blame] | 518 | .. note:: |
| 519 | |
| 520 | Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a |
| 521 | ``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types |
| 522 | (``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h`` |
| 523 | is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will |
| 524 | not allow ``None`` as argument. To pass optional argument of these copied types consider |
| 525 | using ``std::optional<T>`` |
| 526 | |
Jason Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 527 | Overload resolution order |
| 528 | ========================= |
| 529 | |
| 530 | When a function or method with multiple overloads is called from Python, |
| 531 | pybind11 determines which overload to call in two passes. The first pass |
| 532 | attempts to call each overload without allowing argument conversion (as if |
Unknown | 0b3f44e | 2017-11-01 21:08:06 -0400 | [diff] [blame] | 533 | every argument had been specified as ``py::arg().noconvert()`` as described |
Jason Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 534 | above). |
| 535 | |
| 536 | If no overload succeeds in the no-conversion first pass, a second pass is |
| 537 | attempted in which argument conversion is allowed (except where prohibited via |
| 538 | an explicit ``py::arg().noconvert()`` attribute in the function definition). |
| 539 | |
| 540 | If the second pass also fails a ``TypeError`` is raised. |
| 541 | |
| 542 | Within each pass, overloads are tried in the order they were registered with |
Henry Schreiner | 9a0c96d | 2020-10-05 22:36:33 -0400 | [diff] [blame] | 543 | pybind11. If the ``py::prepend()`` tag is added to the definition, a function |
| 544 | can be placed at the beginning of the overload sequence instead, allowing user |
| 545 | overloads to proceed built in functions. |
Jason Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 546 | |
| 547 | What this means in practice is that pybind11 will prefer any overload that does |
Henry Schreiner | 9a0c96d | 2020-10-05 22:36:33 -0400 | [diff] [blame] | 548 | not require conversion of arguments to an overload that does, but otherwise |
| 549 | prefers earlier-defined overloads to later-defined ones. |
Jason Rhinelander | e550589 | 2017-02-03 18:25:34 -0500 | [diff] [blame] | 550 | |
| 551 | .. note:: |
| 552 | |
| 553 | pybind11 does *not* further prioritize based on the number/pattern of |
| 554 | overloaded arguments. That is, pybind11 does not prioritize a function |
| 555 | requiring one conversion over one requiring three, but only prioritizes |
| 556 | overloads requiring no conversion at all to overloads that require |
| 557 | conversion of at least one argument. |
Henry Schreiner | 9a0c96d | 2020-10-05 22:36:33 -0400 | [diff] [blame] | 558 | |
| 559 | .. versionadded:: 2.6 |
| 560 | |
| 561 | The ``py::prepend()`` tag. |