blob: c6c3b1b75b7b532e2456198dd7f2bdc61242264c [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Python types
2############
3
jbarlow83b8863692020-08-22 15:11:09 -07004.. _wrappers:
5
Dean Moldovan67b52d82016-10-16 19:12:43 +02006Available wrappers
7==================
8
9All major Python types are available as thin C++ wrapper classes. These
10can also be used as function parameters -- see :ref:`python_objects_as_args`.
11
12Available 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 Cousineau44fa79c2020-09-04 19:26:57 -040018.. warning::
19
20 Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
21 your C++ API.
22
Dean Moldovan67b52d82016-10-16 19:12:43 +020023Casting back and forth
24======================
25
26In this kind of mixed code, it is often necessary to convert arbitrary C++
27types 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
34The reverse direction uses the following syntax:
35
36.. code-block:: cpp
37
38 py::object obj = ...;
39 MyClass *cls = obj.cast<MyClass *>();
40
41When conversion fails, both directions throw the exception :class:`cast_error`.
42
jbarlow839f823702017-09-13 07:18:08 -070043.. _python_libs:
44
45Accessing Python libraries from C++
46===================================
47
48It is also possible to import objects defined in the Python standard
49library or available in the current Python environment (``sys.path``) and work
50with these in C++.
51
52This 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 Moldovan57a9bbc2017-01-31 16:54:08 +010065.. _calling_python_functions:
66
Dean Moldovan67b52d82016-10-16 19:12:43 +020067Calling Python functions
68========================
69
Henry Schreinerd8c7ee02020-07-20 13:35:21 -040070It is also possible to call Python classes, functions and methods
jbarlow839f823702017-09-13 07:18:08 -070071via ``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 Schreinerd8c7ee02020-07-20 13:35:21 -040085One can convert the result obtained from Python to a pure C++ version
jbarlow839f823702017-09-13 07:18:08 -070086if a ``py::class_`` or type conversion is defined.
Dean Moldovan67b52d82016-10-16 19:12:43 +020087
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
jbarlow839f823702017-09-13 07:18:08 -070094.. _calling_python_methods:
95
96Calling Python methods
97========================
98
99To call an object's method, one can again use ``.attr`` to obtain access to the
100Python 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
108In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
Henry Schreinerd8c7ee02020-07-20 13:35:21 -0400109the 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``
jbarlow839f823702017-09-13 07:18:08 -0700111object 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
122Keyword arguments
123=================
124
Dean Moldovan67b52d82016-10-16 19:12:43 +0200125Keyword 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
134In C++, the same call can be made using:
135
136.. code-block:: cpp
137
myd73499b815ad2017-01-13 18:15:52 +0800138 using namespace pybind11::literals; // to bring in the `_a` literal
Dean Moldovan67b52d82016-10-16 19:12:43 +0200139 f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
140
jbarlow839f823702017-09-13 07:18:08 -0700141Unpacking arguments
142===================
143
Dean Moldovan67b52d82016-10-16 19:12:43 +0200144Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
145other 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
162Generalized 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 Moldovan83e328f2017-06-09 00:44:49 +0200172 The file :file:`tests/test_pytypes.cpp` contains a complete
Dean Moldovan67b52d82016-10-16 19:12:43 +0200173 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/
jbarlow83b8863692020-08-22 15:11:09 -0700178
179Handling exceptions
180===================
181
182Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
183See :ref:`Handling exceptions from Python in C++
184<handling_python_exceptions_cpp>` for more information on handling exceptions
185raised when calling C++ wrapper classes.
Eric Cousineau44fa79c2020-09-04 19:26:57 -0400186
187.. _pytypes_gotchas:
188
189Gotchas
190=======
191
192Default-Constructed Wrappers
193----------------------------
194
195When 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
199Assigning py::none() to wrappers
200--------------------------------
201
202You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
203signatures (either pure C++, or in bound signatures), and assign them default
204values of ``py::none()``. However, in a best case scenario, it will fail fast
205because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
206worse case scenario, it will silently work but corrupt the types you want to
207work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).