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