• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Python types
2############
3
4.. _wrappers:
5
6Available 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
18.. warning::
19
20    Be sure to review the :ref:`pytypes_gotchas` before using this heavily in
21    your C++ API.
22
23.. _casting_back_and_forth:
24
25Casting 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
45.. _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"
59    py::object Decimal = py::module_::import("decimal").attr("Decimal");
60
61.. code-block:: cpp
62
63    // Try to import scipy
64    py::object scipy = py::module_::import("scipy");
65    return scipy.attr("__version__");
66
67
68.. _calling_python_functions:
69
70Calling Python functions
71========================
72
73It is also possible to call Python classes, functions and methods
74via ``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
84    py::object os = py::module_::import("os");
85    py::object makedirs = os.attr("makedirs");
86    makedirs("/tmp/path/to/somewhere");
87
88One can convert the result obtained from Python to a pure C++ version
89if a ``py::class_`` or type conversion is defined.
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
97.. _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
112the 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``
114object 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
128Keyword 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
141    using namespace pybind11::literals; // to bring in the `_a` literal
142    f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
143
144Unpacking arguments
145===================
146
147Unpacking 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
175    The file :file:`tests/test_pytypes.cpp` contains a complete
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/
181
182.. _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
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'
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
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
223Handling 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.
230
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).
252