blob: 6c7525ceaf1842f73e8990aceacfae75a7bbe3b2 [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
Holger Kohrfbc75632020-09-09 16:39:20 +020023.. _casting_back_and_forth:
24
Dean Moldovan67b52d82016-10-16 19:12:43 +020025Casting back and forth
26======================
27
28In this kind of mixed code, it is often necessary to convert arbitrary C++
29types 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
36The reverse direction uses the following syntax:
37
38.. code-block:: cpp
39
40 py::object obj = ...;
41 MyClass *cls = obj.cast<MyClass *>();
42
43When conversion fails, both directions throw the exception :class:`cast_error`.
44
jbarlow839f823702017-09-13 07:18:08 -070045.. _python_libs:
46
47Accessing Python libraries from C++
48===================================
49
50It is also possible to import objects defined in the Python standard
51library or available in the current Python environment (``sys.path``) and work
52with these in C++.
53
54This example obtains a reference to the Python ``Decimal`` class.
55
56.. code-block:: cpp
57
58 // Equivalent to "from decimal import Decimal"
Henry Schreiner6bcd2202020-10-03 13:38:03 -040059 py::object Decimal = py::module_::import("decimal").attr("Decimal");
jbarlow839f823702017-09-13 07:18:08 -070060
61.. code-block:: cpp
62
63 // Try to import scipy
Henry Schreiner6bcd2202020-10-03 13:38:03 -040064 py::object scipy = py::module_::import("scipy");
jbarlow839f823702017-09-13 07:18:08 -070065 return scipy.attr("__version__");
66
Holger Kohrfbc75632020-09-09 16:39:20 +020067
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010068.. _calling_python_functions:
69
Dean Moldovan67b52d82016-10-16 19:12:43 +020070Calling Python functions
71========================
72
Henry Schreinerd8c7ee02020-07-20 13:35:21 -040073It is also possible to call Python classes, functions and methods
jbarlow839f823702017-09-13 07:18:08 -070074via ``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 Schreiner6bcd2202020-10-03 13:38:03 -040084 py::object os = py::module_::import("os");
jbarlow839f823702017-09-13 07:18:08 -070085 py::object makedirs = os.attr("makedirs");
86 makedirs("/tmp/path/to/somewhere");
87
Henry Schreinerd8c7ee02020-07-20 13:35:21 -040088One can convert the result obtained from Python to a pure C++ version
jbarlow839f823702017-09-13 07:18:08 -070089if a ``py::class_`` or type conversion is defined.
Dean Moldovan67b52d82016-10-16 19:12:43 +020090
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
jbarlow839f823702017-09-13 07:18:08 -070097.. _calling_python_methods:
98
99Calling Python methods
100========================
101
102To call an object's method, one can again use ``.attr`` to obtain access to the
103Python 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
111In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
Henry Schreinerd8c7ee02020-07-20 13:35:21 -0400112the 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``
jbarlow839f823702017-09-13 07:18:08 -0700114object 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
125Keyword arguments
126=================
127
Dean Moldovan67b52d82016-10-16 19:12:43 +0200128Keyword 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
137In C++, the same call can be made using:
138
139.. code-block:: cpp
140
myd73499b815ad2017-01-13 18:15:52 +0800141 using namespace pybind11::literals; // to bring in the `_a` literal
Dean Moldovan67b52d82016-10-16 19:12:43 +0200142 f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
143
jbarlow839f823702017-09-13 07:18:08 -0700144Unpacking arguments
145===================
146
Dean Moldovan67b52d82016-10-16 19:12:43 +0200147Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
148other 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
165Generalized 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 Moldovan83e328f2017-06-09 00:44:49 +0200175 The file :file:`tests/test_pytypes.cpp` contains a complete
Dean Moldovan67b52d82016-10-16 19:12:43 +0200176 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/
jbarlow83b8863692020-08-22 15:11:09 -0700181
Holger Kohrfbc75632020-09-09 16:39:20 +0200182.. _implicit_casting:
183
184Implicit casting
185================
186
187When using the C++ interface for Python types, or calling Python functions,
188objects of type :class:`object` are returned. It is possible to invoke implicit
189conversions to subclasses like :class:`dict`. The same holds for the proxy objects
190returned by ``operator[]`` or ``obj.attr()``.
191Casting to subtypes improves code readability and allows values to be passed to
192C++ 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 Schreiner6bcd2202020-10-03 13:38:03 -0400199 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 Kohrfbc75632020-09-09 16:39:20 +0200202
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
210These implicit conversions are available for subclasses of :class:`object`; there
211is 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
jbarlow83b8863692020-08-22 15:11:09 -0700223Handling exceptions
224===================
225
226Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
227See :ref:`Handling exceptions from Python in C++
228<handling_python_exceptions_cpp>` for more information on handling exceptions
229raised when calling C++ wrapper classes.
Eric Cousineau44fa79c2020-09-04 19:26:57 -0400230
231.. _pytypes_gotchas:
232
233Gotchas
234=======
235
236Default-Constructed Wrappers
237----------------------------
238
239When 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
243Assigning py::none() to wrappers
244--------------------------------
245
246You may be tempted to use types like ``py::str`` and ``py::dict`` in C++
247signatures (either pure C++, or in bound signatures), and assign them default
248values of ``py::none()``. However, in a best case scenario, it will fail fast
249because ``None`` is not convertible to that type (e.g. ``py::dict``), or in a
250worse case scenario, it will silently work but corrupt the types you want to
251work with (e.g. ``py::str(py::none())`` will yield ``"None"`` in Python).