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