Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 1 | Python types |
| 2 | ############ |
| 3 | |
| 4 | Available wrappers |
| 5 | ================== |
| 6 | |
| 7 | All major Python types are available as thin C++ wrapper classes. These |
| 8 | can also be used as function parameters -- see :ref:`python_objects_as_args`. |
| 9 | |
| 10 | Available types include :class:`handle`, :class:`object`, :class:`bool_`, |
| 11 | :class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`, |
| 12 | :class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`, |
| 13 | :class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`, |
| 14 | :class:`array`, and :class:`array_t`. |
| 15 | |
| 16 | Casting back and forth |
| 17 | ====================== |
| 18 | |
| 19 | In this kind of mixed code, it is often necessary to convert arbitrary C++ |
| 20 | types to Python, which can be done using :func:`py::cast`: |
| 21 | |
| 22 | .. code-block:: cpp |
| 23 | |
| 24 | MyClass *cls = ..; |
| 25 | py::object obj = py::cast(cls); |
| 26 | |
| 27 | The reverse direction uses the following syntax: |
| 28 | |
| 29 | .. code-block:: cpp |
| 30 | |
| 31 | py::object obj = ...; |
| 32 | MyClass *cls = obj.cast<MyClass *>(); |
| 33 | |
| 34 | When conversion fails, both directions throw the exception :class:`cast_error`. |
| 35 | |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 36 | .. _python_libs: |
| 37 | |
| 38 | Accessing Python libraries from C++ |
| 39 | =================================== |
| 40 | |
| 41 | It is also possible to import objects defined in the Python standard |
| 42 | library or available in the current Python environment (``sys.path``) and work |
| 43 | with these in C++. |
| 44 | |
| 45 | This example obtains a reference to the Python ``Decimal`` class. |
| 46 | |
| 47 | .. code-block:: cpp |
| 48 | |
| 49 | // Equivalent to "from decimal import Decimal" |
| 50 | py::object Decimal = py::module::import("decimal").attr("Decimal"); |
| 51 | |
| 52 | .. code-block:: cpp |
| 53 | |
| 54 | // Try to import scipy |
| 55 | py::object scipy = py::module::import("scipy"); |
| 56 | return scipy.attr("__version__"); |
| 57 | |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 58 | .. _calling_python_functions: |
| 59 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 60 | Calling Python functions |
| 61 | ======================== |
| 62 | |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 63 | It is also possible to call Python classes, functions and methods |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 64 | via ``operator()``. |
| 65 | |
| 66 | .. code-block:: cpp |
| 67 | |
| 68 | // Construct a Python object of class Decimal |
| 69 | py::object pi = Decimal("3.14159"); |
| 70 | |
| 71 | .. code-block:: cpp |
| 72 | |
| 73 | // Use Python to make our directories |
| 74 | py::object os = py::module::import("os"); |
| 75 | py::object makedirs = os.attr("makedirs"); |
| 76 | makedirs("/tmp/path/to/somewhere"); |
| 77 | |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 78 | One can convert the result obtained from Python to a pure C++ version |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 79 | if a ``py::class_`` or type conversion is defined. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 80 | |
| 81 | .. code-block:: cpp |
| 82 | |
| 83 | py::function f = <...>; |
| 84 | py::object result_py = f(1234, "hello", some_instance); |
| 85 | MyClass &result = result_py.cast<MyClass>(); |
| 86 | |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 87 | .. _calling_python_methods: |
| 88 | |
| 89 | Calling Python methods |
| 90 | ======================== |
| 91 | |
| 92 | To call an object's method, one can again use ``.attr`` to obtain access to the |
| 93 | Python method. |
| 94 | |
| 95 | .. code-block:: cpp |
| 96 | |
| 97 | // Calculate e^π in decimal |
| 98 | py::object exp_pi = pi.attr("exp")(); |
| 99 | py::print(py::str(exp_pi)); |
| 100 | |
| 101 | In the example above ``pi.attr("exp")`` is a *bound method*: it will always call |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 102 | the method for that same instance of the class. Alternately one can create an |
| 103 | *unbound method* via the Python class (instead of instance) and pass the ``self`` |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 104 | object explicitly, followed by other arguments. |
| 105 | |
| 106 | .. code-block:: cpp |
| 107 | |
| 108 | py::object decimal_exp = Decimal.attr("exp"); |
| 109 | |
| 110 | // Compute the e^n for n=0..4 |
| 111 | for (int n = 0; n < 5; n++) { |
| 112 | py::print(decimal_exp(Decimal(n)); |
| 113 | } |
| 114 | |
| 115 | Keyword arguments |
| 116 | ================= |
| 117 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 118 | Keyword arguments are also supported. In Python, there is the usual call syntax: |
| 119 | |
| 120 | .. code-block:: python |
| 121 | |
| 122 | def f(number, say, to): |
| 123 | ... # function code |
| 124 | |
| 125 | f(1234, say="hello", to=some_instance) # keyword call in Python |
| 126 | |
| 127 | In C++, the same call can be made using: |
| 128 | |
| 129 | .. code-block:: cpp |
| 130 | |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 131 | using namespace pybind11::literals; // to bring in the `_a` literal |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 132 | f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++ |
| 133 | |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 134 | Unpacking arguments |
| 135 | =================== |
| 136 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 137 | Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with |
| 138 | other arguments: |
| 139 | |
| 140 | .. code-block:: cpp |
| 141 | |
| 142 | // * unpacking |
| 143 | py::tuple args = py::make_tuple(1234, "hello", some_instance); |
| 144 | f(*args); |
| 145 | |
| 146 | // ** unpacking |
| 147 | py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance); |
| 148 | f(**kwargs); |
| 149 | |
| 150 | // mixed keywords, * and ** unpacking |
| 151 | py::tuple args = py::make_tuple(1234); |
| 152 | py::dict kwargs = py::dict("to"_a=some_instance); |
| 153 | f(*args, "say"_a="hello", **kwargs); |
| 154 | |
| 155 | Generalized unpacking according to PEP448_ is also supported: |
| 156 | |
| 157 | .. code-block:: cpp |
| 158 | |
| 159 | py::dict kwargs1 = py::dict("number"_a=1234); |
| 160 | py::dict kwargs2 = py::dict("to"_a=some_instance); |
| 161 | f(**kwargs1, "say"_a="hello", **kwargs2); |
| 162 | |
| 163 | .. seealso:: |
| 164 | |
Dean Moldovan | 83e328f | 2017-06-09 00:44:49 +0200 | [diff] [blame] | 165 | The file :file:`tests/test_pytypes.cpp` contains a complete |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 166 | example that demonstrates passing native Python types in more detail. The |
| 167 | file :file:`tests/test_callbacks.cpp` presents a few examples of calling |
| 168 | Python functions from C++, including keywords arguments and unpacking. |
| 169 | |
| 170 | .. _PEP448: https://www.python.org/dev/peps/pep-0448/ |