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 | |
Holger Kohr | fbc7563 | 2020-09-09 16:39:20 +0200 | [diff] [blame] | 23 | .. _casting_back_and_forth: |
| 24 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 25 | Casting back and forth |
| 26 | ====================== |
| 27 | |
| 28 | In this kind of mixed code, it is often necessary to convert arbitrary C++ |
| 29 | types to Python, which can be done using :func:`py::cast`: |
| 30 | |
| 31 | .. code-block:: cpp |
| 32 | |
| 33 | MyClass *cls = ..; |
| 34 | py::object obj = py::cast(cls); |
| 35 | |
| 36 | The reverse direction uses the following syntax: |
| 37 | |
| 38 | .. code-block:: cpp |
| 39 | |
| 40 | py::object obj = ...; |
| 41 | MyClass *cls = obj.cast<MyClass *>(); |
| 42 | |
| 43 | When conversion fails, both directions throw the exception :class:`cast_error`. |
| 44 | |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 45 | .. _python_libs: |
| 46 | |
| 47 | Accessing Python libraries from C++ |
| 48 | =================================== |
| 49 | |
| 50 | It is also possible to import objects defined in the Python standard |
| 51 | library or available in the current Python environment (``sys.path``) and work |
| 52 | with these in C++. |
| 53 | |
| 54 | This example obtains a reference to the Python ``Decimal`` class. |
| 55 | |
| 56 | .. code-block:: cpp |
| 57 | |
| 58 | // Equivalent to "from decimal import Decimal" |
Henry Schreiner | 6bcd220 | 2020-10-03 13:38:03 -0400 | [diff] [blame] | 59 | py::object Decimal = py::module_::import("decimal").attr("Decimal"); |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 60 | |
| 61 | .. code-block:: cpp |
| 62 | |
| 63 | // Try to import scipy |
Henry Schreiner | 6bcd220 | 2020-10-03 13:38:03 -0400 | [diff] [blame] | 64 | py::object scipy = py::module_::import("scipy"); |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 65 | return scipy.attr("__version__"); |
| 66 | |
Holger Kohr | fbc7563 | 2020-09-09 16:39:20 +0200 | [diff] [blame] | 67 | |
Dean Moldovan | 57a9bbc | 2017-01-31 16:54:08 +0100 | [diff] [blame] | 68 | .. _calling_python_functions: |
| 69 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 70 | Calling Python functions |
| 71 | ======================== |
| 72 | |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 73 | It is also possible to call Python classes, functions and methods |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 74 | via ``operator()``. |
| 75 | |
| 76 | .. code-block:: cpp |
| 77 | |
| 78 | // Construct a Python object of class Decimal |
| 79 | py::object pi = Decimal("3.14159"); |
| 80 | |
| 81 | .. code-block:: cpp |
| 82 | |
| 83 | // Use Python to make our directories |
Henry Schreiner | 6bcd220 | 2020-10-03 13:38:03 -0400 | [diff] [blame] | 84 | py::object os = py::module_::import("os"); |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 85 | py::object makedirs = os.attr("makedirs"); |
| 86 | makedirs("/tmp/path/to/somewhere"); |
| 87 | |
Henry Schreiner | d8c7ee0 | 2020-07-20 13:35:21 -0400 | [diff] [blame] | 88 | One can convert the result obtained from Python to a pure C++ version |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 89 | if a ``py::class_`` or type conversion is defined. |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 90 | |
| 91 | .. code-block:: cpp |
| 92 | |
| 93 | py::function f = <...>; |
| 94 | py::object result_py = f(1234, "hello", some_instance); |
| 95 | MyClass &result = result_py.cast<MyClass>(); |
| 96 | |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 97 | .. _calling_python_methods: |
| 98 | |
| 99 | Calling Python methods |
| 100 | ======================== |
| 101 | |
| 102 | To call an object's method, one can again use ``.attr`` to obtain access to the |
| 103 | Python method. |
| 104 | |
| 105 | .. code-block:: cpp |
| 106 | |
| 107 | // Calculate e^π in decimal |
| 108 | py::object exp_pi = pi.attr("exp")(); |
| 109 | py::print(py::str(exp_pi)); |
| 110 | |
| 111 | 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] | 112 | the method for that same instance of the class. Alternately one can create an |
| 113 | *unbound method* via the Python class (instead of instance) and pass the ``self`` |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 114 | object explicitly, followed by other arguments. |
| 115 | |
| 116 | .. code-block:: cpp |
| 117 | |
| 118 | py::object decimal_exp = Decimal.attr("exp"); |
| 119 | |
| 120 | // Compute the e^n for n=0..4 |
| 121 | for (int n = 0; n < 5; n++) { |
| 122 | py::print(decimal_exp(Decimal(n)); |
| 123 | } |
| 124 | |
| 125 | Keyword arguments |
| 126 | ================= |
| 127 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 128 | Keyword arguments are also supported. In Python, there is the usual call syntax: |
| 129 | |
| 130 | .. code-block:: python |
| 131 | |
| 132 | def f(number, say, to): |
| 133 | ... # function code |
| 134 | |
| 135 | f(1234, say="hello", to=some_instance) # keyword call in Python |
| 136 | |
| 137 | In C++, the same call can be made using: |
| 138 | |
| 139 | .. code-block:: cpp |
| 140 | |
myd7349 | 9b815ad | 2017-01-13 18:15:52 +0800 | [diff] [blame] | 141 | using namespace pybind11::literals; // to bring in the `_a` literal |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 142 | f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++ |
| 143 | |
jbarlow83 | 9f82370 | 2017-09-13 07:18:08 -0700 | [diff] [blame] | 144 | Unpacking arguments |
| 145 | =================== |
| 146 | |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 147 | Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with |
| 148 | other arguments: |
| 149 | |
| 150 | .. code-block:: cpp |
| 151 | |
| 152 | // * unpacking |
| 153 | py::tuple args = py::make_tuple(1234, "hello", some_instance); |
| 154 | f(*args); |
| 155 | |
| 156 | // ** unpacking |
| 157 | py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance); |
| 158 | f(**kwargs); |
| 159 | |
| 160 | // mixed keywords, * and ** unpacking |
| 161 | py::tuple args = py::make_tuple(1234); |
| 162 | py::dict kwargs = py::dict("to"_a=some_instance); |
| 163 | f(*args, "say"_a="hello", **kwargs); |
| 164 | |
| 165 | Generalized unpacking according to PEP448_ is also supported: |
| 166 | |
| 167 | .. code-block:: cpp |
| 168 | |
| 169 | py::dict kwargs1 = py::dict("number"_a=1234); |
| 170 | py::dict kwargs2 = py::dict("to"_a=some_instance); |
| 171 | f(**kwargs1, "say"_a="hello", **kwargs2); |
| 172 | |
| 173 | .. seealso:: |
| 174 | |
Dean Moldovan | 83e328f | 2017-06-09 00:44:49 +0200 | [diff] [blame] | 175 | The file :file:`tests/test_pytypes.cpp` contains a complete |
Dean Moldovan | 67b52d8 | 2016-10-16 19:12:43 +0200 | [diff] [blame] | 176 | example that demonstrates passing native Python types in more detail. The |
| 177 | file :file:`tests/test_callbacks.cpp` presents a few examples of calling |
| 178 | Python functions from C++, including keywords arguments and unpacking. |
| 179 | |
| 180 | .. _PEP448: https://www.python.org/dev/peps/pep-0448/ |
jbarlow83 | b886369 | 2020-08-22 15:11:09 -0700 | [diff] [blame] | 181 | |
Holger Kohr | fbc7563 | 2020-09-09 16:39:20 +0200 | [diff] [blame] | 182 | .. _implicit_casting: |
| 183 | |
| 184 | Implicit casting |
| 185 | ================ |
| 186 | |
| 187 | When using the C++ interface for Python types, or calling Python functions, |
| 188 | objects of type :class:`object` are returned. It is possible to invoke implicit |
| 189 | conversions to subclasses like :class:`dict`. The same holds for the proxy objects |
| 190 | returned by ``operator[]`` or ``obj.attr()``. |
| 191 | Casting to subtypes improves code readability and allows values to be passed to |
| 192 | C++ functions that require a specific subtype rather than a generic :class:`object`. |
| 193 | |
| 194 | .. code-block:: cpp |
| 195 | |
| 196 | #include <pybind11/numpy.h> |
| 197 | using namespace pybind11::literals; |
| 198 | |
Henry Schreiner | 6bcd220 | 2020-10-03 13:38:03 -0400 | [diff] [blame] | 199 | py::module_ os = py::module_::import("os"); |
| 200 | py::module_ path = py::module_::import("os.path"); // like 'import os.path as path' |
| 201 | py::module_ np = py::module_::import("numpy"); // like 'import numpy as np' |
Holger Kohr | fbc7563 | 2020-09-09 16:39:20 +0200 | [diff] [blame] | 202 | |
| 203 | py::str curdir_abs = path.attr("abspath")(path.attr("curdir")); |
| 204 | py::print(py::str("Current directory: ") + curdir_abs); |
| 205 | py::dict environ = os.attr("environ"); |
| 206 | py::print(environ["HOME"]); |
| 207 | py::array_t<float> arr = np.attr("ones")(3, "dtype"_a="float32"); |
| 208 | py::print(py::repr(arr + py::int_(1))); |
| 209 | |
| 210 | These implicit conversions are available for subclasses of :class:`object`; there |
| 211 | is no need to call ``obj.cast()`` explicitly as for custom classes, see |
| 212 | :ref:`casting_back_and_forth`. |
| 213 | |
| 214 | .. note:: |
| 215 | If a trivial conversion via move constructor is not possible, both implicit and |
| 216 | explicit casting (calling ``obj.cast()``) will attempt a "rich" conversion. |
| 217 | For instance, ``py::list env = os.attr("environ");`` will succeed and is |
| 218 | equivalent to the Python code ``env = list(os.environ)`` that produces a |
| 219 | list of the dict keys. |
| 220 | |
| 221 | .. TODO: Adapt text once PR #2349 has landed |
| 222 | |
jbarlow83 | b886369 | 2020-08-22 15:11:09 -0700 | [diff] [blame] | 223 | Handling exceptions |
| 224 | =================== |
| 225 | |
| 226 | Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``. |
| 227 | See :ref:`Handling exceptions from Python in C++ |
| 228 | <handling_python_exceptions_cpp>` for more information on handling exceptions |
| 229 | raised when calling C++ wrapper classes. |
Eric Cousineau | 44fa79c | 2020-09-04 19:26:57 -0400 | [diff] [blame] | 230 | |
| 231 | .. _pytypes_gotchas: |
| 232 | |
| 233 | Gotchas |
| 234 | ======= |
| 235 | |
| 236 | Default-Constructed Wrappers |
| 237 | ---------------------------- |
| 238 | |
| 239 | 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 |
| 240 | ``PyObject*`` null pointer. To check for this, use |
| 241 | ``static_cast<bool>(my_wrapper)``. |
| 242 | |
| 243 | Assigning py::none() to wrappers |
| 244 | -------------------------------- |
| 245 | |
| 246 | You may be tempted to use types like ``py::str`` and ``py::dict`` in C++ |
| 247 | signatures (either pure C++, or in bound signatures), and assign them default |
| 248 | values of ``py::none()``. However, in a best case scenario, it will fail fast |
| 249 | because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a |
| 250 | worse case scenario, it will silently work but corrupt the types you want to |
| 251 | work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python). |