blob: 07525d0dc78f5e2ff2f83cd57bdb616413104341 [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
18Casting back and forth
19======================
20
21In this kind of mixed code, it is often necessary to convert arbitrary C++
22types 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
29The reverse direction uses the following syntax:
30
31.. code-block:: cpp
32
33 py::object obj = ...;
34 MyClass *cls = obj.cast<MyClass *>();
35
36When conversion fails, both directions throw the exception :class:`cast_error`.
37
jbarlow839f823702017-09-13 07:18:08 -070038.. _python_libs:
39
40Accessing Python libraries from C++
41===================================
42
43It is also possible to import objects defined in the Python standard
44library or available in the current Python environment (``sys.path``) and work
45with these in C++.
46
47This 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 Moldovan57a9bbc2017-01-31 16:54:08 +010060.. _calling_python_functions:
61
Dean Moldovan67b52d82016-10-16 19:12:43 +020062Calling Python functions
63========================
64
Henry Schreinerd8c7ee02020-07-20 13:35:21 -040065It is also possible to call Python classes, functions and methods
jbarlow839f823702017-09-13 07:18:08 -070066via ``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 Schreinerd8c7ee02020-07-20 13:35:21 -040080One can convert the result obtained from Python to a pure C++ version
jbarlow839f823702017-09-13 07:18:08 -070081if a ``py::class_`` or type conversion is defined.
Dean Moldovan67b52d82016-10-16 19:12:43 +020082
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
jbarlow839f823702017-09-13 07:18:08 -070089.. _calling_python_methods:
90
91Calling Python methods
92========================
93
94To call an object's method, one can again use ``.attr`` to obtain access to the
95Python 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
103In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
Henry Schreinerd8c7ee02020-07-20 13:35:21 -0400104the 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``
jbarlow839f823702017-09-13 07:18:08 -0700106object 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
117Keyword arguments
118=================
119
Dean Moldovan67b52d82016-10-16 19:12:43 +0200120Keyword 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
129In C++, the same call can be made using:
130
131.. code-block:: cpp
132
myd73499b815ad2017-01-13 18:15:52 +0800133 using namespace pybind11::literals; // to bring in the `_a` literal
Dean Moldovan67b52d82016-10-16 19:12:43 +0200134 f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
135
jbarlow839f823702017-09-13 07:18:08 -0700136Unpacking arguments
137===================
138
Dean Moldovan67b52d82016-10-16 19:12:43 +0200139Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
140other 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
157Generalized 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 Moldovan83e328f2017-06-09 00:44:49 +0200167 The file :file:`tests/test_pytypes.cpp` contains a complete
Dean Moldovan67b52d82016-10-16 19:12:43 +0200168 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/
jbarlow83b8863692020-08-22 15:11:09 -0700173
174Handling exceptions
175===================
176
177Python exceptions from wrapper classes will be thrown as a ``py::error_already_set``.
178See :ref:`Handling exceptions from Python in C++
179<handling_python_exceptions_cpp>` for more information on handling exceptions
180raised when calling C++ wrapper classes.