@@ -1589,24 +1589,56 @@ It is also possible to call python functions via ``operator()``.
1589
1589
py::object result_py = f(1234, "hello", some_instance);
1590
1590
MyClass &result = result_py.cast<MyClass>();
1591
1591
1592
- The special ``f(*args) `` and ``f(*args, **kwargs) `` syntax is also supported to
1593
- supply arbitrary argument and keyword lists, although these cannot be mixed
1594
- with other parameters.
1592
+ Keyword arguments are also supported. In Python, there is the usual call syntax:
1593
+
1594
+ .. code-block :: python
1595
+
1596
+ def f (number , say , to ):
1597
+ ... # function code
1598
+
1599
+ f(1234 , say = " hello" , to = some_instance) # keyword call in Python
1600
+
1601
+ In C++, the same call can be made using:
1595
1602
1596
1603
.. code-block :: cpp
1597
1604
1598
- py::function f = <...>;
1605
+ using pybind11::literals; // to bring in the `_a` literal
1606
+ f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
1607
+
1608
+ Unpacking of ``*args `` and ``**kwargs `` is also possible and can be mixed with
1609
+ other arguments:
1610
+
1611
+ .. code-block :: cpp
1612
+
1613
+ // * unpacking
1614
+ py::tuple args = py::make_tuple(1234, "hello", some_instance);
1615
+ f(*args);
1616
+
1617
+ // ** unpacking
1618
+ py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
1619
+ f(**kwargs);
1620
+
1621
+ // mixed keywords, * and ** unpacking
1599
1622
py::tuple args = py::make_tuple(1234);
1600
- py::dict kwargs;
1601
- kwargs["y"] = py::cast(5678);
1602
- py::object result = f(*args, **kwargs);
1623
+ py::dict kwargs = py::dict("to"_a=some_instance);
1624
+ f(*args, "say"_a="hello", **kwargs);
1625
+
1626
+ Generalized unpacking according to PEP448 _ is also supported:
1627
+
1628
+ .. code-block :: cpp
1629
+
1630
+ py::dict kwargs1 = py::dict("number"_a=1234);
1631
+ py::dict kwargs2 = py::dict("to"_a=some_instance);
1632
+ f(**kwargs1, "say"_a="hello", **kwargs2);
1603
1633
1604
1634
.. seealso ::
1605
1635
1606
1636
The file :file: `tests/test_python_types.cpp ` contains a complete
1607
1637
example that demonstrates passing native Python types in more detail. The
1608
- file :file: `tests/test_kwargs_and_defaults.cpp ` discusses usage
1609
- of ``args `` and ``kwargs ``.
1638
+ file :file: `tests/test_callbacks.cpp ` presents a few examples of calling
1639
+ Python functions from C++, including keywords arguments and unpacking.
1640
+
1641
+ .. _PEP448 : https://www.python.org/dev/peps/pep-0448/
1610
1642
1611
1643
Default arguments revisited
1612
1644
===========================
0 commit comments