|
Packit |
534379 |
Functions
|
|
Packit |
534379 |
#########
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Before proceeding with this section, make sure that you are already familiar
|
|
Packit |
534379 |
with the basics of binding functions and classes, as explained in :doc:`/basics`
|
|
Packit |
534379 |
and :doc:`/classes`. The following guide is applicable to both free and member
|
|
Packit |
534379 |
functions, i.e. *methods* in Python.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. _return_value_policies:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Return value policies
|
|
Packit |
534379 |
=====================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Python and C++ use fundamentally different ways of managing the memory and
|
|
Packit |
534379 |
lifetime of objects managed by them. This can lead to issues when creating
|
|
Packit |
534379 |
bindings for functions that return a non-trivial type. Just by looking at the
|
|
Packit |
534379 |
type information, it is not clear whether Python should take charge of the
|
|
Packit |
534379 |
returned value and eventually free its resources, or if this is handled on the
|
|
Packit |
534379 |
C++ side. For this reason, pybind11 provides a several *return value policy*
|
|
Packit |
534379 |
annotations that can be passed to the :func:`module::def` and
|
|
Packit |
534379 |
:func:`class_::def` functions. The default policy is
|
|
Packit |
534379 |
:enum:`return_value_policy::automatic`.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Return value policies are tricky, and it's very important to get them right.
|
|
Packit |
534379 |
Just to illustrate what can go wrong, consider the following simple example:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
/* Function declaration */
|
|
Packit |
534379 |
Data *get_data() { return _data; /* (pointer to a static data structure) */ }
|
|
Packit |
534379 |
...
|
|
Packit |
534379 |
|
|
Packit |
534379 |
/* Binding code */
|
|
Packit |
534379 |
m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
|
|
Packit |
534379 |
|
|
Packit |
534379 |
What's going on here? When ``get_data()`` is called from Python, the return
|
|
Packit |
534379 |
value (a native C++ type) must be wrapped to turn it into a usable Python type.
|
|
Packit |
534379 |
In this case, the default return value policy (:enum:`return_value_policy::automatic`)
|
|
Packit |
534379 |
causes pybind11 to assume ownership of the static ``_data`` instance.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
When Python's garbage collector eventually deletes the Python
|
|
Packit |
534379 |
wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
|
|
Packit |
534379 |
delete()``) due to the implied ownership. At this point, the entire application
|
|
Packit |
534379 |
will come crashing down, though errors could also be more subtle and involve
|
|
Packit |
534379 |
silent data corruption.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
In the above example, the policy :enum:`return_value_policy::reference` should have
|
|
Packit |
534379 |
been specified so that the global data instance is only *referenced* without any
|
|
Packit |
534379 |
implied transfer of ownership, i.e.:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
m.def("get_data", &get_data, return_value_policy::reference);
|
|
Packit |
534379 |
|
|
Packit |
534379 |
On the other hand, this is not the right policy for many other situations,
|
|
Packit |
534379 |
where ignoring ownership could lead to resource leaks.
|
|
Packit |
534379 |
As a developer using pybind11, it's important to be familiar with the different
|
|
Packit |
534379 |
return value policies, including which situation calls for which one of them.
|
|
Packit |
534379 |
The following table provides an overview of available policies:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
|
|
Packit |
534379 |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| Return value policy | Description |
|
|
Packit |
534379 |
+==================================================+============================================================================+
|
|
Packit |
534379 |
| :enum:`return_value_policy::take_ownership` | Reference an existing object (i.e. do not create a new copy) and take |
|
|
Packit |
534379 |
| | ownership. Python will call the destructor and delete operator when the |
|
|
Packit |
534379 |
| | object's reference count reaches zero. Undefined behavior ensues when the |
|
|
Packit |
534379 |
| | C++ side does the same, or when the data was not dynamically allocated. |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| :enum:`return_value_policy::copy` | Create a new copy of the returned object, which will be owned by Python. |
|
|
Packit |
534379 |
| | This policy is comparably safe because the lifetimes of the two instances |
|
|
Packit |
534379 |
| | are decoupled. |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| :enum:`return_value_policy::move` | Use ``std::move`` to move the return value contents into a new instance |
|
|
Packit |
534379 |
| | that will be owned by Python. This policy is comparably safe because the |
|
|
Packit |
534379 |
| | lifetimes of the two instances (move source and destination) are decoupled.|
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| :enum:`return_value_policy::reference` | Reference an existing object, but do not take ownership. The C++ side is |
|
|
Packit |
534379 |
| | responsible for managing the object's lifetime and deallocating it when |
|
|
Packit |
534379 |
| | it is no longer used. Warning: undefined behavior will ensue when the C++ |
|
|
Packit |
534379 |
| | side deletes an object that is still referenced and used by Python. |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| :enum:`return_value_policy::reference_internal` | Indicates that the lifetime of the return value is tied to the lifetime |
|
|
Packit |
534379 |
| | of a parent object, namely the implicit ``this``, or ``self`` argument of |
|
|
Packit |
534379 |
| | the called method or property. Internally, this policy works just like |
|
|
Packit |
534379 |
| | :enum:`return_value_policy::reference` but additionally applies a |
|
|
Packit |
534379 |
| | ``keep_alive<0, 1>`` *call policy* (described in the next section) that |
|
|
Packit |
534379 |
| | prevents the parent object from being garbage collected as long as the |
|
|
Packit |
534379 |
| | return value is referenced by Python. This is the default policy for |
|
|
Packit |
534379 |
| | property getters created via ``def_property``, ``def_readwrite``, etc. |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| :enum:`return_value_policy::automatic` | **Default policy.** This policy falls back to the policy |
|
|
Packit |
534379 |
| | :enum:`return_value_policy::take_ownership` when the return value is a |
|
|
Packit |
534379 |
| | pointer. Otherwise, it uses :enum:`return_value_policy::move` or |
|
|
Packit |
534379 |
| | :enum:`return_value_policy::copy` for rvalue and lvalue references, |
|
|
Packit |
534379 |
| | respectively. See above for a description of what all of these different |
|
|
Packit |
534379 |
| | policies do. |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
| :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the |
|
|
Packit |
534379 |
| | return value is a pointer. This is the default conversion policy for |
|
|
Packit |
534379 |
| | function arguments when calling Python functions manually from C++ code |
|
|
Packit |
534379 |
| | (i.e. via handle::operator()). You probably won't need to use this. |
|
|
Packit |
534379 |
+--------------------------------------------------+----------------------------------------------------------------------------+
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Return value policies can also be applied to properties:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
class_<MyClass>(m, "MyClass")
|
|
Packit |
534379 |
.def_property("data", &MyClass::getData, &MyClass::setData,
|
|
Packit |
534379 |
py::return_value_policy::copy);
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Technically, the code above applies the policy to both the getter and the
|
|
Packit |
534379 |
setter function, however, the setter doesn't really care about *return*
|
|
Packit |
534379 |
value policies which makes this a convenient terse syntax. Alternatively,
|
|
Packit |
534379 |
targeted arguments can be passed through the :class:`cpp_function` constructor:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
class_<MyClass>(m, "MyClass")
|
|
Packit |
534379 |
.def_property("data"
|
|
Packit |
534379 |
py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
|
|
Packit |
534379 |
py::cpp_function(&MyClass::setData)
|
|
Packit |
534379 |
);
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. warning::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Code with invalid return value policies might access uninitialized memory or
|
|
Packit |
534379 |
free data structures multiple times, which can lead to hard-to-debug
|
|
Packit |
534379 |
non-determinism and segmentation faults, hence it is worth spending the
|
|
Packit |
534379 |
time to understand all the different options in the table above.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
One important aspect of the above policies is that they only apply to
|
|
Packit |
534379 |
instances which pybind11 has *not* seen before, in which case the policy
|
|
Packit |
534379 |
clarifies essential questions about the return value's lifetime and
|
|
Packit |
534379 |
ownership. When pybind11 knows the instance already (as identified by its
|
|
Packit |
534379 |
type and address in memory), it will return the existing Python object
|
|
Packit |
534379 |
wrapper rather than creating a new copy.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The next section on :ref:`call_policies` discusses *call policies* that can be
|
|
Packit |
534379 |
specified *in addition* to a return value policy from the list above. Call
|
|
Packit |
534379 |
policies indicate reference relationships that can involve both return values
|
|
Packit |
534379 |
and parameters of functions.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
As an alternative to elaborate call policies and lifetime management logic,
|
|
Packit |
534379 |
consider using smart pointers (see the section on :ref:`smart_pointers` for
|
|
Packit |
534379 |
details). Smart pointers can tell whether an object is still referenced from
|
|
Packit |
534379 |
C++ or Python, which generally eliminates the kinds of inconsistencies that
|
|
Packit |
534379 |
can lead to crashes or undefined behavior. For functions returning smart
|
|
Packit |
534379 |
pointers, it is not necessary to specify a return value policy.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. _call_policies:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Additional call policies
|
|
Packit |
534379 |
========================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
In addition to the above return value policies, further *call policies* can be
|
|
Packit |
534379 |
specified to indicate dependencies between parameters or ensure a certain state
|
|
Packit |
534379 |
for the function call.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Keep alive
|
|
Packit |
534379 |
----------
|
|
Packit |
534379 |
|
|
Packit |
534379 |
In general, this policy is required when the C++ object is any kind of container
|
|
Packit |
534379 |
and another object is being added to the container. ``keep_alive<Nurse, Patient>``
|
|
Packit |
534379 |
indicates that the argument with index ``Patient`` should be kept alive at least
|
|
Packit |
534379 |
until the argument with index ``Nurse`` is freed by the garbage collector. Argument
|
|
Packit |
534379 |
indices start at one, while zero refers to the return value. For methods, index
|
|
Packit |
534379 |
``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
|
|
Packit |
534379 |
index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
|
|
Packit |
534379 |
with value ``None`` is detected at runtime, the call policy does nothing.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
When the nurse is not a pybind11-registered type, the implementation internally
|
|
Packit |
534379 |
relies on the ability to create a *weak reference* to the nurse object. When
|
|
Packit |
534379 |
the nurse object is not a pybind11-registered type and does not support weak
|
|
Packit |
534379 |
references, an exception will be thrown.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Consider the following example: here, the binding code for a list append
|
|
Packit |
534379 |
operation ties the lifetime of the newly added element to the underlying
|
|
Packit |
534379 |
container:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
py::class_<List>(m, "List")
|
|
Packit |
534379 |
.def("append", &List::append, py::keep_alive<1, 2>());
|
|
Packit |
534379 |
|
|
Packit |
534379 |
For consistency, the argument indexing is identical for constructors. Index
|
|
Packit |
534379 |
``1`` still refers to the implicit ``this`` pointer, i.e. the object which is
|
|
Packit |
534379 |
being constructed. Index ``0`` refers to the return type which is presumed to
|
|
Packit |
534379 |
be ``void`` when a constructor is viewed like a function. The following example
|
|
Packit |
534379 |
ties the lifetime of the constructor element to the constructed object:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
py::class_<Nurse>(m, "Nurse")
|
|
Packit |
534379 |
.def(py::init<Patient &>(), py::keep_alive<1, 2>());
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
|
|
Packit |
534379 |
Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
|
|
Packit |
534379 |
0) policies from Boost.Python.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Call guard
|
|
Packit |
534379 |
----------
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed
|
|
Packit |
534379 |
around the function call. For example, this definition:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
m.def("foo", foo, py::call_guard<T>());
|
|
Packit |
534379 |
|
|
Packit |
534379 |
is equivalent to the following pseudocode:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
m.def("foo", [](args...) {
|
|
Packit |
534379 |
T scope_guard;
|
|
Packit |
534379 |
return foo(args...); // forwarded arguments
|
|
Packit |
534379 |
});
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The only requirement is that ``T`` is default-constructible, but otherwise any
|
|
Packit |
534379 |
scope guard will work. This is very useful in combination with `gil_scoped_release`.
|
|
Packit |
534379 |
See :ref:`gil`.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The
|
|
Packit |
534379 |
constructor order is left to right and destruction happens in reverse.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. seealso::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The file :file:`tests/test_call_policies.cpp` contains a complete example
|
|
Packit |
534379 |
that demonstrates using `keep_alive` and `call_guard` in more detail.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. _python_objects_as_args:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Python objects as arguments
|
|
Packit |
534379 |
===========================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
pybind11 exposes all major Python types using thin C++ wrapper classes. These
|
|
Packit |
534379 |
wrapper classes can also be used as parameters of functions in bindings, which
|
|
Packit |
534379 |
makes it possible to directly work with native Python types on the C++ side.
|
|
Packit |
534379 |
For instance, the following statement iterates over a Python ``dict``:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
void print_dict(py::dict dict) {
|
|
Packit |
534379 |
/* Easily interact with Python types */
|
|
Packit |
534379 |
for (auto item : dict)
|
|
Packit |
534379 |
std::cout << "key=" << std::string(py::str(item.first)) << ", "
|
|
Packit |
534379 |
<< "value=" << std::string(py::str(item.second)) << std::endl;
|
|
Packit |
534379 |
}
|
|
Packit |
534379 |
|
|
Packit |
534379 |
It can be exported:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
m.def("print_dict", &print_dict);
|
|
Packit |
534379 |
|
|
Packit |
534379 |
And used in Python as usual:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: pycon
|
|
Packit |
534379 |
|
|
Packit |
534379 |
>>> print_dict({'foo': 123, 'bar': 'hello'})
|
|
Packit |
534379 |
key=foo, value=123
|
|
Packit |
534379 |
key=bar, value=hello
|
|
Packit |
534379 |
|
|
Packit |
534379 |
For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Accepting \*args and \*\*kwargs
|
|
Packit |
534379 |
===============================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Python provides a useful mechanism to define functions that accept arbitrary
|
|
Packit |
534379 |
numbers of arguments and keyword arguments:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: python
|
|
Packit |
534379 |
|
|
Packit |
534379 |
def generic(*args, **kwargs):
|
|
Packit |
534379 |
... # do something with args and kwargs
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Such functions can also be created using pybind11:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
void generic(py::args args, py::kwargs kwargs) {
|
|
Packit |
534379 |
/// .. do something with args
|
|
Packit |
534379 |
if (kwargs)
|
|
Packit |
534379 |
/// .. do something with kwargs
|
|
Packit |
534379 |
}
|
|
Packit |
534379 |
|
|
Packit |
534379 |
/// Binding code
|
|
Packit |
534379 |
m.def("generic", &generic);
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
|
|
Packit |
534379 |
from ``py::dict``.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
You may also use just one or the other, and may combine these with other
|
|
Packit |
534379 |
arguments as long as the ``py::args`` and ``py::kwargs`` arguments are the last
|
|
Packit |
534379 |
arguments accepted by the function.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Please refer to the other examples for details on how to iterate over these,
|
|
Packit |
534379 |
and on how to cast their entries into C++ objects. A demonstration is also
|
|
Packit |
534379 |
available in ``tests/test_kwargs_and_defaults.cpp``.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
|
|
Packit |
534379 |
*not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
|
|
Packit |
534379 |
arguments.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Default arguments revisited
|
|
Packit |
534379 |
===========================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The section on :ref:`default_args` previously discussed basic usage of default
|
|
Packit |
534379 |
arguments using pybind11. One noteworthy aspect of their implementation is that
|
|
Packit |
534379 |
default arguments are converted to Python objects right at declaration time.
|
|
Packit |
534379 |
Consider the following example:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
py::class_<MyClass>("MyClass")
|
|
Packit |
534379 |
.def("myFunction", py::arg("arg") = SomeType(123));
|
|
Packit |
534379 |
|
|
Packit |
534379 |
In this case, pybind11 must already be set up to deal with values of the type
|
|
Packit |
534379 |
``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
|
|
Packit |
534379 |
exception will be thrown.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Another aspect worth highlighting is that the "preview" of the default argument
|
|
Packit |
534379 |
in the function signature is generated using the object's ``__repr__`` method.
|
|
Packit |
534379 |
If not available, the signature may not be very helpful, e.g.:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: pycon
|
|
Packit |
534379 |
|
|
Packit |
534379 |
FUNCTIONS
|
|
Packit |
534379 |
...
|
|
Packit |
534379 |
| myFunction(...)
|
|
Packit |
534379 |
| Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
|
|
Packit |
534379 |
...
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The first way of addressing this is by defining ``SomeType.__repr__``.
|
|
Packit |
534379 |
Alternatively, it is possible to specify the human-readable preview of the
|
|
Packit |
534379 |
default argument manually using the ``arg_v`` notation:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
py::class_<MyClass>("MyClass")
|
|
Packit |
534379 |
.def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Sometimes it may be necessary to pass a null pointer value as a default
|
|
Packit |
534379 |
argument. In this case, remember to cast it to the underlying type in question,
|
|
Packit |
534379 |
like so:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
py::class_<MyClass>("MyClass")
|
|
Packit |
534379 |
.def("myFunction", py::arg("arg") = (SomeType *) nullptr);
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. _nonconverting_arguments:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Non-converting arguments
|
|
Packit |
534379 |
========================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Certain argument types may support conversion from one type to another. Some
|
|
Packit |
534379 |
examples of conversions are:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
* :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
|
|
Packit |
534379 |
* Calling a method accepting a double with an integer argument
|
|
Packit |
534379 |
* Calling a ``std::complex<float>`` argument with a non-complex python type
|
|
Packit |
534379 |
(for example, with a float). (Requires the optional ``pybind11/complex.h``
|
|
Packit |
534379 |
header).
|
|
Packit |
534379 |
* Calling a function taking an Eigen matrix reference with a numpy array of the
|
|
Packit |
534379 |
wrong type or of an incompatible data layout. (Requires the optional
|
|
Packit |
534379 |
``pybind11/eigen.h`` header).
|
|
Packit |
534379 |
|
|
Packit |
534379 |
This behaviour is sometimes undesirable: the binding code may prefer to raise
|
|
Packit |
534379 |
an error rather than convert the argument. This behaviour can be obtained
|
|
Packit |
534379 |
through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
|
|
Packit |
534379 |
object, such as:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
|
|
Packit |
534379 |
m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Attempting the call the second function (the one without ``.noconvert()``) with
|
|
Packit |
534379 |
an integer will succeed, but attempting to call the ``.noconvert()`` version
|
|
Packit |
534379 |
will fail with a ``TypeError``:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: pycon
|
|
Packit |
534379 |
|
|
Packit |
534379 |
>>> floats_preferred(4)
|
|
Packit |
534379 |
2.0
|
|
Packit |
534379 |
>>> floats_only(4)
|
|
Packit |
534379 |
Traceback (most recent call last):
|
|
Packit |
534379 |
File "<stdin>", line 1, in <module>
|
|
Packit |
534379 |
TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
|
|
Packit |
534379 |
1. (f: float) -> float
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Invoked with: 4
|
|
Packit |
534379 |
|
|
Packit |
534379 |
You may, of course, combine this with the :var:`_a` shorthand notation (see
|
|
Packit |
534379 |
:ref:`keyword_args`) and/or :ref:`default_args`. It is also permitted to omit
|
|
Packit |
534379 |
the argument name by using the ``py::arg()`` constructor without an argument
|
|
Packit |
534379 |
name, i.e. by specifying ``py::arg().noconvert()``.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
When specifying ``py::arg`` options it is necessary to provide the same
|
|
Packit |
534379 |
number of options as the bound function has arguments. Thus if you want to
|
|
Packit |
534379 |
enable no-convert behaviour for just one of several arguments, you will
|
|
Packit |
534379 |
need to specify a ``py::arg()`` annotation for each argument with the
|
|
Packit |
534379 |
no-convert argument modified to ``py::arg().noconvert()``.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. _none_arguments:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Allow/Prohibiting None arguments
|
|
Packit |
534379 |
================================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
When a C++ type registered with :class:`py::class_` is passed as an argument to
|
|
Packit |
534379 |
a function taking the instance as pointer or shared holder (e.g. ``shared_ptr``
|
|
Packit |
534379 |
or a custom, copyable holder as described in :ref:`smart_pointers`), pybind
|
|
Packit |
534379 |
allows ``None`` to be passed from Python which results in calling the C++
|
|
Packit |
534379 |
function with ``nullptr`` (or an empty holder) for the argument.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
To explicitly enable or disable this behaviour, using the
|
|
Packit |
534379 |
``.none`` method of the :class:`py::arg` object:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: cpp
|
|
Packit |
534379 |
|
|
Packit |
534379 |
py::class_<Dog>(m, "Dog").def(py::init<>());
|
|
Packit |
534379 |
py::class_<Cat>(m, "Cat").def(py::init<>());
|
|
Packit |
534379 |
m.def("bark", [](Dog *dog) -> std::string {
|
|
Packit |
534379 |
if (dog) return "woof!"; /* Called with a Dog instance */
|
|
Packit |
534379 |
else return "(no dog)"; /* Called with None, dog == nullptr */
|
|
Packit |
534379 |
}, py::arg("dog").none(true));
|
|
Packit |
534379 |
m.def("meow", [](Cat *cat) -> std::string {
|
|
Packit |
534379 |
// Can't be called with None argument
|
|
Packit |
534379 |
return "meow";
|
|
Packit |
534379 |
}, py::arg("cat").none(false));
|
|
Packit |
534379 |
|
|
Packit |
534379 |
With the above, the Python call ``bark(None)`` will return the string ``"(no
|
|
Packit |
534379 |
dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. code-block:: pycon
|
|
Packit |
534379 |
|
|
Packit |
534379 |
>>> from animals import Dog, Cat, bark, meow
|
|
Packit |
534379 |
>>> bark(Dog())
|
|
Packit |
534379 |
'woof!'
|
|
Packit |
534379 |
>>> meow(Cat())
|
|
Packit |
534379 |
'meow'
|
|
Packit |
534379 |
>>> bark(None)
|
|
Packit |
534379 |
'(no dog)'
|
|
Packit |
534379 |
>>> meow(None)
|
|
Packit |
534379 |
Traceback (most recent call last):
|
|
Packit |
534379 |
File "<stdin>", line 1, in <module>
|
|
Packit |
534379 |
TypeError: meow(): incompatible function arguments. The following argument types are supported:
|
|
Packit |
534379 |
1. (cat: animals.Cat) -> str
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Invoked with: None
|
|
Packit |
534379 |
|
|
Packit |
534379 |
The default behaviour when the tag is unspecified is to allow ``None``.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a
|
|
Packit |
534379 |
``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types
|
|
Packit |
534379 |
(``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h``
|
|
Packit |
534379 |
is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will
|
|
Packit |
534379 |
not allow ``None`` as argument. To pass optional argument of these copied types consider
|
|
Packit |
534379 |
using ``std::optional<T>``
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Overload resolution order
|
|
Packit |
534379 |
=========================
|
|
Packit |
534379 |
|
|
Packit |
534379 |
When a function or method with multiple overloads is called from Python,
|
|
Packit |
534379 |
pybind11 determines which overload to call in two passes. The first pass
|
|
Packit |
534379 |
attempts to call each overload without allowing argument conversion (as if
|
|
Packit |
534379 |
every argument had been specified as ``py::arg().noconvert()`` as described
|
|
Packit |
534379 |
above).
|
|
Packit |
534379 |
|
|
Packit |
534379 |
If no overload succeeds in the no-conversion first pass, a second pass is
|
|
Packit |
534379 |
attempted in which argument conversion is allowed (except where prohibited via
|
|
Packit |
534379 |
an explicit ``py::arg().noconvert()`` attribute in the function definition).
|
|
Packit |
534379 |
|
|
Packit |
534379 |
If the second pass also fails a ``TypeError`` is raised.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
Within each pass, overloads are tried in the order they were registered with
|
|
Packit |
534379 |
pybind11.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
What this means in practice is that pybind11 will prefer any overload that does
|
|
Packit |
534379 |
not require conversion of arguments to an overload that does, but otherwise prefers
|
|
Packit |
534379 |
earlier-defined overloads to later-defined ones.
|
|
Packit |
534379 |
|
|
Packit |
534379 |
.. note::
|
|
Packit |
534379 |
|
|
Packit |
534379 |
pybind11 does *not* further prioritize based on the number/pattern of
|
|
Packit |
534379 |
overloaded arguments. That is, pybind11 does not prioritize a function
|
|
Packit |
534379 |
requiring one conversion over one requiring three, but only prioritizes
|
|
Packit |
534379 |
overloads requiring no conversion at all to overloads that require
|
|
Packit |
534379 |
conversion of at least one argument.
|