Back to home page

EIC code displayed by LXR

 
 

    


Warning, /jana2/src/python/externals/pybind11-2.10.3/docs/advanced/functions.rst is written in an unsupported language. File is not indexed.

0001 Functions
0002 #########
0003 
0004 Before proceeding with this section, make sure that you are already familiar
0005 with the basics of binding functions and classes, as explained in :doc:`/basics`
0006 and :doc:`/classes`. The following guide is applicable to both free and member
0007 functions, i.e. *methods* in Python.
0008 
0009 .. _return_value_policies:
0010 
0011 Return value policies
0012 =====================
0013 
0014 Python and C++ use fundamentally different ways of managing the memory and
0015 lifetime of objects managed by them. This can lead to issues when creating
0016 bindings for functions that return a non-trivial type. Just by looking at the
0017 type information, it is not clear whether Python should take charge of the
0018 returned value and eventually free its resources, or if this is handled on the
0019 C++ side. For this reason, pybind11 provides a several *return value policy*
0020 annotations that can be passed to the :func:`module_::def` and
0021 :func:`class_::def` functions. The default policy is
0022 :enum:`return_value_policy::automatic`.
0023 
0024 Return value policies are tricky, and it's very important to get them right.
0025 Just to illustrate what can go wrong, consider the following simple example:
0026 
0027 .. code-block:: cpp
0028 
0029     /* Function declaration */
0030     Data *get_data() { return _data; /* (pointer to a static data structure) */ }
0031     ...
0032 
0033     /* Binding code */
0034     m.def("get_data", &get_data); // <-- KABOOM, will cause crash when called from Python
0035 
0036 What's going on here? When ``get_data()`` is called from Python, the return
0037 value (a native C++ type) must be wrapped to turn it into a usable Python type.
0038 In this case, the default return value policy (:enum:`return_value_policy::automatic`)
0039 causes pybind11 to assume ownership of the static ``_data`` instance.
0040 
0041 When Python's garbage collector eventually deletes the Python
0042 wrapper, pybind11 will also attempt to delete the C++ instance (via ``operator
0043 delete()``) due to the implied ownership. At this point, the entire application
0044 will come crashing down, though errors could also be more subtle and involve
0045 silent data corruption.
0046 
0047 In the above example, the policy :enum:`return_value_policy::reference` should have
0048 been specified so that the global data instance is only *referenced* without any
0049 implied transfer of ownership, i.e.:
0050 
0051 .. code-block:: cpp
0052 
0053     m.def("get_data", &get_data, py::return_value_policy::reference);
0054 
0055 On the other hand, this is not the right policy for many other situations,
0056 where ignoring ownership could lead to resource leaks.
0057 As a developer using pybind11, it's important to be familiar with the different
0058 return value policies, including which situation calls for which one of them.
0059 The following table provides an overview of available policies:
0060 
0061 .. tabularcolumns:: |p{0.5\textwidth}|p{0.45\textwidth}|
0062 
0063 +--------------------------------------------------+----------------------------------------------------------------------------+
0064 | Return value policy                              | Description                                                                |
0065 +==================================================+============================================================================+
0066 | :enum:`return_value_policy::take_ownership`      | Reference an existing object (i.e. do not create a new copy) and take      |
0067 |                                                  | ownership. Python will call the destructor and delete operator when the    |
0068 |                                                  | object's reference count reaches zero. Undefined behavior ensues when the  |
0069 |                                                  | C++ side does the same, or when the data was not dynamically allocated.    |
0070 +--------------------------------------------------+----------------------------------------------------------------------------+
0071 | :enum:`return_value_policy::copy`                | Create a new copy of the returned object, which will be owned by Python.   |
0072 |                                                  | This policy is comparably safe because the lifetimes of the two instances  |
0073 |                                                  | are decoupled.                                                             |
0074 +--------------------------------------------------+----------------------------------------------------------------------------+
0075 | :enum:`return_value_policy::move`                | Use ``std::move`` to move the return value contents into a new instance    |
0076 |                                                  | that will be owned by Python. This policy is comparably safe because the   |
0077 |                                                  | lifetimes of the two instances (move source and destination) are decoupled.|
0078 +--------------------------------------------------+----------------------------------------------------------------------------+
0079 | :enum:`return_value_policy::reference`           | Reference an existing object, but do not take ownership. The C++ side is   |
0080 |                                                  | responsible for managing the object's lifetime and deallocating it when    |
0081 |                                                  | it is no longer used. Warning: undefined behavior will ensue when the C++  |
0082 |                                                  | side deletes an object that is still referenced and used by Python.        |
0083 +--------------------------------------------------+----------------------------------------------------------------------------+
0084 | :enum:`return_value_policy::reference_internal`  | Indicates that the lifetime of the return value is tied to the lifetime    |
0085 |                                                  | of a parent object, namely the implicit ``this``, or ``self`` argument of  |
0086 |                                                  | the called method or property. Internally, this policy works just like     |
0087 |                                                  | :enum:`return_value_policy::reference` but additionally applies a          |
0088 |                                                  | ``keep_alive<0, 1>`` *call policy* (described in the next section) that    |
0089 |                                                  | prevents the parent object from being garbage collected as long as the     |
0090 |                                                  | return value is referenced by Python. This is the default policy for       |
0091 |                                                  | property getters created via ``def_property``, ``def_readwrite``, etc.     |
0092 +--------------------------------------------------+----------------------------------------------------------------------------+
0093 | :enum:`return_value_policy::automatic`           | This policy falls back to the policy                                       |
0094 |                                                  | :enum:`return_value_policy::take_ownership` when the return value is a     |
0095 |                                                  | pointer. Otherwise, it uses :enum:`return_value_policy::move` or           |
0096 |                                                  | :enum:`return_value_policy::copy` for rvalue and lvalue references,        |
0097 |                                                  | respectively. See above for a description of what all of these different   |
0098 |                                                  | policies do. This is the default policy for ``py::class_``-wrapped types.  |
0099 +--------------------------------------------------+----------------------------------------------------------------------------+
0100 | :enum:`return_value_policy::automatic_reference` | As above, but use policy :enum:`return_value_policy::reference` when the   |
0101 |                                                  | return value is a pointer. This is the default conversion policy for       |
0102 |                                                  | function arguments when calling Python functions manually from C++ code    |
0103 |                                                  | (i.e. via ``handle::operator()``) and the casters in ``pybind11/stl.h``.   |
0104 |                                                  | You probably won't need to use this explicitly.                            |
0105 +--------------------------------------------------+----------------------------------------------------------------------------+
0106 
0107 Return value policies can also be applied to properties:
0108 
0109 .. code-block:: cpp
0110 
0111     class_<MyClass>(m, "MyClass")
0112         .def_property("data", &MyClass::getData, &MyClass::setData,
0113                       py::return_value_policy::copy);
0114 
0115 Technically, the code above applies the policy to both the getter and the
0116 setter function, however, the setter doesn't really care about *return*
0117 value policies which makes this a convenient terse syntax. Alternatively,
0118 targeted arguments can be passed through the :class:`cpp_function` constructor:
0119 
0120 .. code-block:: cpp
0121 
0122     class_<MyClass>(m, "MyClass")
0123         .def_property("data",
0124             py::cpp_function(&MyClass::getData, py::return_value_policy::copy),
0125             py::cpp_function(&MyClass::setData)
0126         );
0127 
0128 .. warning::
0129 
0130     Code with invalid return value policies might access uninitialized memory or
0131     free data structures multiple times, which can lead to hard-to-debug
0132     non-determinism and segmentation faults, hence it is worth spending the
0133     time to understand all the different options in the table above.
0134 
0135 .. note::
0136 
0137     One important aspect of the above policies is that they only apply to
0138     instances which pybind11 has *not* seen before, in which case the policy
0139     clarifies essential questions about the return value's lifetime and
0140     ownership.  When pybind11 knows the instance already (as identified by its
0141     type and address in memory), it will return the existing Python object
0142     wrapper rather than creating a new copy.
0143 
0144 .. note::
0145 
0146     The next section on :ref:`call_policies` discusses *call policies* that can be
0147     specified *in addition* to a return value policy from the list above. Call
0148     policies indicate reference relationships that can involve both return values
0149     and parameters of functions.
0150 
0151 .. note::
0152 
0153    As an alternative to elaborate call policies and lifetime management logic,
0154    consider using smart pointers (see the section on :ref:`smart_pointers` for
0155    details). Smart pointers can tell whether an object is still referenced from
0156    C++ or Python, which generally eliminates the kinds of inconsistencies that
0157    can lead to crashes or undefined behavior. For functions returning smart
0158    pointers, it is not necessary to specify a return value policy.
0159 
0160 .. _call_policies:
0161 
0162 Additional call policies
0163 ========================
0164 
0165 In addition to the above return value policies, further *call policies* can be
0166 specified to indicate dependencies between parameters or ensure a certain state
0167 for the function call.
0168 
0169 Keep alive
0170 ----------
0171 
0172 In general, this policy is required when the C++ object is any kind of container
0173 and another object is being added to the container. ``keep_alive<Nurse, Patient>``
0174 indicates that the argument with index ``Patient`` should be kept alive at least
0175 until the argument with index ``Nurse`` is freed by the garbage collector. Argument
0176 indices start at one, while zero refers to the return value. For methods, index
0177 ``1`` refers to the implicit ``this`` pointer, while regular arguments begin at
0178 index ``2``. Arbitrarily many call policies can be specified. When a ``Nurse``
0179 with value ``None`` is detected at runtime, the call policy does nothing.
0180 
0181 When the nurse is not a pybind11-registered type, the implementation internally
0182 relies on the ability to create a *weak reference* to the nurse object. When
0183 the nurse object is not a pybind11-registered type and does not support weak
0184 references, an exception will be thrown.
0185 
0186 If you use an incorrect argument index, you will get a ``RuntimeError`` saying
0187 ``Could not activate keep_alive!``. You should review the indices you're using.
0188 
0189 Consider the following example: here, the binding code for a list append
0190 operation ties the lifetime of the newly added element to the underlying
0191 container:
0192 
0193 .. code-block:: cpp
0194 
0195     py::class_<List>(m, "List")
0196         .def("append", &List::append, py::keep_alive<1, 2>());
0197 
0198 For consistency, the argument indexing is identical for constructors. Index
0199 ``1`` still refers to the implicit ``this`` pointer, i.e. the object which is
0200 being constructed. Index ``0`` refers to the return type which is presumed to
0201 be ``void`` when a constructor is viewed like a function. The following example
0202 ties the lifetime of the constructor element to the constructed object:
0203 
0204 .. code-block:: cpp
0205 
0206     py::class_<Nurse>(m, "Nurse")
0207         .def(py::init<Patient &>(), py::keep_alive<1, 2>());
0208 
0209 .. note::
0210 
0211     ``keep_alive`` is analogous to the ``with_custodian_and_ward`` (if Nurse,
0212     Patient != 0) and ``with_custodian_and_ward_postcall`` (if Nurse/Patient ==
0213     0) policies from Boost.Python.
0214 
0215 Call guard
0216 ----------
0217 
0218 The ``call_guard<T>`` policy allows any scope guard type ``T`` to be placed
0219 around the function call. For example, this definition:
0220 
0221 .. code-block:: cpp
0222 
0223     m.def("foo", foo, py::call_guard<T>());
0224 
0225 is equivalent to the following pseudocode:
0226 
0227 .. code-block:: cpp
0228 
0229     m.def("foo", [](args...) {
0230         T scope_guard;
0231         return foo(args...); // forwarded arguments
0232     });
0233 
0234 The only requirement is that ``T`` is default-constructible, but otherwise any
0235 scope guard will work. This is very useful in combination with ``gil_scoped_release``.
0236 See :ref:`gil`.
0237 
0238 Multiple guards can also be specified as ``py::call_guard<T1, T2, T3...>``. The
0239 constructor order is left to right and destruction happens in reverse.
0240 
0241 .. seealso::
0242 
0243     The file :file:`tests/test_call_policies.cpp` contains a complete example
0244     that demonstrates using `keep_alive` and `call_guard` in more detail.
0245 
0246 .. _python_objects_as_args:
0247 
0248 Python objects as arguments
0249 ===========================
0250 
0251 pybind11 exposes all major Python types using thin C++ wrapper classes. These
0252 wrapper classes can also be used as parameters of functions in bindings, which
0253 makes it possible to directly work with native Python types on the C++ side.
0254 For instance, the following statement iterates over a Python ``dict``:
0255 
0256 .. code-block:: cpp
0257 
0258     void print_dict(const py::dict& dict) {
0259         /* Easily interact with Python types */
0260         for (auto item : dict)
0261             std::cout << "key=" << std::string(py::str(item.first)) << ", "
0262                       << "value=" << std::string(py::str(item.second)) << std::endl;
0263     }
0264 
0265 It can be exported:
0266 
0267 .. code-block:: cpp
0268 
0269     m.def("print_dict", &print_dict);
0270 
0271 And used in Python as usual:
0272 
0273 .. code-block:: pycon
0274 
0275     >>> print_dict({"foo": 123, "bar": "hello"})
0276     key=foo, value=123
0277     key=bar, value=hello
0278 
0279 For more information on using Python objects in C++, see :doc:`/advanced/pycpp/index`.
0280 
0281 Accepting \*args and \*\*kwargs
0282 ===============================
0283 
0284 Python provides a useful mechanism to define functions that accept arbitrary
0285 numbers of arguments and keyword arguments:
0286 
0287 .. code-block:: python
0288 
0289    def generic(*args, **kwargs):
0290        ...  # do something with args and kwargs
0291 
0292 Such functions can also be created using pybind11:
0293 
0294 .. code-block:: cpp
0295 
0296    void generic(py::args args, const py::kwargs& kwargs) {
0297        /// .. do something with args
0298        if (kwargs)
0299            /// .. do something with kwargs
0300    }
0301 
0302    /// Binding code
0303    m.def("generic", &generic);
0304 
0305 The class ``py::args`` derives from ``py::tuple`` and ``py::kwargs`` derives
0306 from ``py::dict``.
0307 
0308 You may also use just one or the other, and may combine these with other
0309 arguments.  Note, however, that ``py::kwargs`` must always be the last argument
0310 of the function, and ``py::args`` implies that any further arguments are
0311 keyword-only (see :ref:`keyword_only_arguments`).
0312 
0313 Please refer to the other examples for details on how to iterate over these,
0314 and on how to cast their entries into C++ objects. A demonstration is also
0315 available in ``tests/test_kwargs_and_defaults.cpp``.
0316 
0317 .. note::
0318 
0319     When combining \*args or \*\*kwargs with :ref:`keyword_args` you should
0320     *not* include ``py::arg`` tags for the ``py::args`` and ``py::kwargs``
0321     arguments.
0322 
0323 Default arguments revisited
0324 ===========================
0325 
0326 The section on :ref:`default_args` previously discussed basic usage of default
0327 arguments using pybind11. One noteworthy aspect of their implementation is that
0328 default arguments are converted to Python objects right at declaration time.
0329 Consider the following example:
0330 
0331 .. code-block:: cpp
0332 
0333     py::class_<MyClass>("MyClass")
0334         .def("myFunction", py::arg("arg") = SomeType(123));
0335 
0336 In this case, pybind11 must already be set up to deal with values of the type
0337 ``SomeType`` (via a prior instantiation of ``py::class_<SomeType>``), or an
0338 exception will be thrown.
0339 
0340 Another aspect worth highlighting is that the "preview" of the default argument
0341 in the function signature is generated using the object's ``__repr__`` method.
0342 If not available, the signature may not be very helpful, e.g.:
0343 
0344 .. code-block:: pycon
0345 
0346     FUNCTIONS
0347     ...
0348     |  myFunction(...)
0349     |      Signature : (MyClass, arg : SomeType = <SomeType object at 0x101b7b080>) -> NoneType
0350     ...
0351 
0352 The first way of addressing this is by defining ``SomeType.__repr__``.
0353 Alternatively, it is possible to specify the human-readable preview of the
0354 default argument manually using the ``arg_v`` notation:
0355 
0356 .. code-block:: cpp
0357 
0358     py::class_<MyClass>("MyClass")
0359         .def("myFunction", py::arg_v("arg", SomeType(123), "SomeType(123)"));
0360 
0361 Sometimes it may be necessary to pass a null pointer value as a default
0362 argument. In this case, remember to cast it to the underlying type in question,
0363 like so:
0364 
0365 .. code-block:: cpp
0366 
0367     py::class_<MyClass>("MyClass")
0368         .def("myFunction", py::arg("arg") = static_cast<SomeType *>(nullptr));
0369 
0370 .. _keyword_only_arguments:
0371 
0372 Keyword-only arguments
0373 ======================
0374 
0375 Python implements keyword-only arguments by specifying an unnamed ``*``
0376 argument in a function definition:
0377 
0378 .. code-block:: python
0379 
0380     def f(a, *, b):  # a can be positional or via keyword; b must be via keyword
0381         pass
0382 
0383 
0384     f(a=1, b=2)  # good
0385     f(b=2, a=1)  # good
0386     f(1, b=2)  # good
0387     f(1, 2)  # TypeError: f() takes 1 positional argument but 2 were given
0388 
0389 Pybind11 provides a ``py::kw_only`` object that allows you to implement
0390 the same behaviour by specifying the object between positional and keyword-only
0391 argument annotations when registering the function:
0392 
0393 .. code-block:: cpp
0394 
0395     m.def("f", [](int a, int b) { /* ... */ },
0396           py::arg("a"), py::kw_only(), py::arg("b"));
0397 
0398 .. versionadded:: 2.6
0399 
0400 A ``py::args`` argument implies that any following arguments are keyword-only,
0401 as if ``py::kw_only()`` had been specified in the same relative location of the
0402 argument list as the ``py::args`` argument.  The ``py::kw_only()`` may be
0403 included to be explicit about this, but is not required.
0404 
0405 .. versionchanged:: 2.9
0406    This can now be combined with ``py::args``. Before, ``py::args`` could only
0407    occur at the end of the argument list, or immediately before a ``py::kwargs``
0408    argument at the end.
0409 
0410 
0411 Positional-only arguments
0412 =========================
0413 
0414 Python 3.8 introduced a new positional-only argument syntax, using ``/`` in the
0415 function definition (note that this has been a convention for CPython
0416 positional arguments, such as in ``pow()``, since Python 2). You can
0417 do the same thing in any version of Python using ``py::pos_only()``:
0418 
0419 .. code-block:: cpp
0420 
0421    m.def("f", [](int a, int b) { /* ... */ },
0422           py::arg("a"), py::pos_only(), py::arg("b"));
0423 
0424 You now cannot give argument ``a`` by keyword. This can be combined with
0425 keyword-only arguments, as well.
0426 
0427 .. versionadded:: 2.6
0428 
0429 .. _nonconverting_arguments:
0430 
0431 Non-converting arguments
0432 ========================
0433 
0434 Certain argument types may support conversion from one type to another.  Some
0435 examples of conversions are:
0436 
0437 * :ref:`implicit_conversions` declared using ``py::implicitly_convertible<A,B>()``
0438 * Calling a method accepting a double with an integer argument
0439 * Calling a ``std::complex<float>`` argument with a non-complex python type
0440   (for example, with a float).  (Requires the optional ``pybind11/complex.h``
0441   header).
0442 * Calling a function taking an Eigen matrix reference with a numpy array of the
0443   wrong type or of an incompatible data layout.  (Requires the optional
0444   ``pybind11/eigen.h`` header).
0445 
0446 This behaviour is sometimes undesirable: the binding code may prefer to raise
0447 an error rather than convert the argument.  This behaviour can be obtained
0448 through ``py::arg`` by calling the ``.noconvert()`` method of the ``py::arg``
0449 object, such as:
0450 
0451 .. code-block:: cpp
0452 
0453     m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
0454     m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
0455 
0456 Attempting the call the second function (the one without ``.noconvert()``) with
0457 an integer will succeed, but attempting to call the ``.noconvert()`` version
0458 will fail with a ``TypeError``:
0459 
0460 .. code-block:: pycon
0461 
0462     >>> floats_preferred(4)
0463     2.0
0464     >>> floats_only(4)
0465     Traceback (most recent call last):
0466       File "<stdin>", line 1, in <module>
0467     TypeError: floats_only(): incompatible function arguments. The following argument types are supported:
0468         1. (f: float) -> float
0469 
0470     Invoked with: 4
0471 
0472 You may, of course, combine this with the :var:`_a` shorthand notation (see
0473 :ref:`keyword_args`) and/or :ref:`default_args`.  It is also permitted to omit
0474 the argument name by using the ``py::arg()`` constructor without an argument
0475 name, i.e. by specifying ``py::arg().noconvert()``.
0476 
0477 .. note::
0478 
0479     When specifying ``py::arg`` options it is necessary to provide the same
0480     number of options as the bound function has arguments.  Thus if you want to
0481     enable no-convert behaviour for just one of several arguments, you will
0482     need to specify a ``py::arg()`` annotation for each argument with the
0483     no-convert argument modified to ``py::arg().noconvert()``.
0484 
0485 .. _none_arguments:
0486 
0487 Allow/Prohibiting None arguments
0488 ================================
0489 
0490 When a C++ type registered with :class:`py::class_` is passed as an argument to
0491 a function taking the instance as pointer or shared holder (e.g. ``shared_ptr``
0492 or a custom, copyable holder as described in :ref:`smart_pointers`), pybind
0493 allows ``None`` to be passed from Python which results in calling the C++
0494 function with ``nullptr`` (or an empty holder) for the argument.
0495 
0496 To explicitly enable or disable this behaviour, using the
0497 ``.none`` method of the :class:`py::arg` object:
0498 
0499 .. code-block:: cpp
0500 
0501     py::class_<Dog>(m, "Dog").def(py::init<>());
0502     py::class_<Cat>(m, "Cat").def(py::init<>());
0503     m.def("bark", [](Dog *dog) -> std::string {
0504         if (dog) return "woof!"; /* Called with a Dog instance */
0505         else return "(no dog)"; /* Called with None, dog == nullptr */
0506     }, py::arg("dog").none(true));
0507     m.def("meow", [](Cat *cat) -> std::string {
0508         // Can't be called with None argument
0509         return "meow";
0510     }, py::arg("cat").none(false));
0511 
0512 With the above, the Python call ``bark(None)`` will return the string ``"(no
0513 dog)"``, while attempting to call ``meow(None)`` will raise a ``TypeError``:
0514 
0515 .. code-block:: pycon
0516 
0517     >>> from animals import Dog, Cat, bark, meow
0518     >>> bark(Dog())
0519     'woof!'
0520     >>> meow(Cat())
0521     'meow'
0522     >>> bark(None)
0523     '(no dog)'
0524     >>> meow(None)
0525     Traceback (most recent call last):
0526       File "<stdin>", line 1, in <module>
0527     TypeError: meow(): incompatible function arguments. The following argument types are supported:
0528         1. (cat: animals.Cat) -> str
0529 
0530     Invoked with: None
0531 
0532 The default behaviour when the tag is unspecified is to allow ``None``.
0533 
0534 .. note::
0535 
0536     Even when ``.none(true)`` is specified for an argument, ``None`` will be converted to a
0537     ``nullptr`` *only* for custom and :ref:`opaque <opaque>` types. Pointers to built-in types
0538     (``double *``, ``int *``, ...) and STL types (``std::vector<T> *``, ...; if ``pybind11/stl.h``
0539     is included) are copied when converted to C++ (see :doc:`/advanced/cast/overview`) and will
0540     not allow ``None`` as argument.  To pass optional argument of these copied types consider
0541     using ``std::optional<T>``
0542 
0543 .. _overload_resolution:
0544 
0545 Overload resolution order
0546 =========================
0547 
0548 When a function or method with multiple overloads is called from Python,
0549 pybind11 determines which overload to call in two passes.  The first pass
0550 attempts to call each overload without allowing argument conversion (as if
0551 every argument had been specified as ``py::arg().noconvert()`` as described
0552 above).
0553 
0554 If no overload succeeds in the no-conversion first pass, a second pass is
0555 attempted in which argument conversion is allowed (except where prohibited via
0556 an explicit ``py::arg().noconvert()`` attribute in the function definition).
0557 
0558 If the second pass also fails a ``TypeError`` is raised.
0559 
0560 Within each pass, overloads are tried in the order they were registered with
0561 pybind11. If the ``py::prepend()`` tag is added to the definition, a function
0562 can be placed at the beginning of the overload sequence instead, allowing user
0563 overloads to proceed built in functions.
0564 
0565 What this means in practice is that pybind11 will prefer any overload that does
0566 not require conversion of arguments to an overload that does, but otherwise
0567 prefers earlier-defined overloads to later-defined ones.
0568 
0569 .. note::
0570 
0571     pybind11 does *not* further prioritize based on the number/pattern of
0572     overloaded arguments.  That is, pybind11 does not prioritize a function
0573     requiring one conversion over one requiring three, but only prioritizes
0574     overloads requiring no conversion at all to overloads that require
0575     conversion of at least one argument.
0576 
0577 .. versionadded:: 2.6
0578 
0579     The ``py::prepend()`` tag.
0580 
0581 Binding functions with template parameters
0582 ==========================================
0583 
0584 You can bind functions that have template parameters. Here's a function:
0585 
0586 .. code-block:: cpp
0587 
0588     template <typename T>
0589     void set(T t);
0590 
0591 C++ templates cannot be instantiated at runtime, so you cannot bind the
0592 non-instantiated function:
0593 
0594 .. code-block:: cpp
0595 
0596     // BROKEN (this will not compile)
0597     m.def("set", &set);
0598 
0599 You must bind each instantiated function template separately. You may bind
0600 each instantiation with the same name, which will be treated the same as
0601 an overloaded function:
0602 
0603 .. code-block:: cpp
0604 
0605     m.def("set", &set<int>);
0606     m.def("set", &set<std::string>);
0607 
0608 Sometimes it's more clear to bind them with separate names, which is also
0609 an option:
0610 
0611 .. code-block:: cpp
0612 
0613     m.def("setInt", &set<int>);
0614     m.def("setString", &set<std::string>);