blob: 19a226a8765f266e53d617bcb2d8e991864bffc4 [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001Python types
2############
3
4Available wrappers
5==================
6
7All major Python types are available as thin C++ wrapper classes. These
8can also be used as function parameters -- see :ref:`python_objects_as_args`.
9
10Available types include :class:`handle`, :class:`object`, :class:`bool_`,
11:class:`int_`, :class:`float_`, :class:`str`, :class:`bytes`, :class:`tuple`,
12:class:`list`, :class:`dict`, :class:`slice`, :class:`none`, :class:`capsule`,
13:class:`iterable`, :class:`iterator`, :class:`function`, :class:`buffer`,
14:class:`array`, and :class:`array_t`.
15
16Casting back and forth
17======================
18
19In this kind of mixed code, it is often necessary to convert arbitrary C++
20types to Python, which can be done using :func:`py::cast`:
21
22.. code-block:: cpp
23
24 MyClass *cls = ..;
25 py::object obj = py::cast(cls);
26
27The reverse direction uses the following syntax:
28
29.. code-block:: cpp
30
31 py::object obj = ...;
32 MyClass *cls = obj.cast<MyClass *>();
33
34When conversion fails, both directions throw the exception :class:`cast_error`.
35
jbarlow839f823702017-09-13 07:18:08 -070036.. _python_libs:
37
38Accessing Python libraries from C++
39===================================
40
41It is also possible to import objects defined in the Python standard
42library or available in the current Python environment (``sys.path``) and work
43with these in C++.
44
45This example obtains a reference to the Python ``Decimal`` class.
46
47.. code-block:: cpp
48
49 // Equivalent to "from decimal import Decimal"
50 py::object Decimal = py::module::import("decimal").attr("Decimal");
51
52.. code-block:: cpp
53
54 // Try to import scipy
55 py::object scipy = py::module::import("scipy");
56 return scipy.attr("__version__");
57
Dean Moldovan57a9bbc2017-01-31 16:54:08 +010058.. _calling_python_functions:
59
Dean Moldovan67b52d82016-10-16 19:12:43 +020060Calling Python functions
61========================
62
Henry Schreinerd8c7ee02020-07-20 13:35:21 -040063It is also possible to call Python classes, functions and methods
jbarlow839f823702017-09-13 07:18:08 -070064via ``operator()``.
65
66.. code-block:: cpp
67
68 // Construct a Python object of class Decimal
69 py::object pi = Decimal("3.14159");
70
71.. code-block:: cpp
72
73 // Use Python to make our directories
74 py::object os = py::module::import("os");
75 py::object makedirs = os.attr("makedirs");
76 makedirs("/tmp/path/to/somewhere");
77
Henry Schreinerd8c7ee02020-07-20 13:35:21 -040078One can convert the result obtained from Python to a pure C++ version
jbarlow839f823702017-09-13 07:18:08 -070079if a ``py::class_`` or type conversion is defined.
Dean Moldovan67b52d82016-10-16 19:12:43 +020080
81.. code-block:: cpp
82
83 py::function f = <...>;
84 py::object result_py = f(1234, "hello", some_instance);
85 MyClass &result = result_py.cast<MyClass>();
86
jbarlow839f823702017-09-13 07:18:08 -070087.. _calling_python_methods:
88
89Calling Python methods
90========================
91
92To call an object's method, one can again use ``.attr`` to obtain access to the
93Python method.
94
95.. code-block:: cpp
96
97 // Calculate e^π in decimal
98 py::object exp_pi = pi.attr("exp")();
99 py::print(py::str(exp_pi));
100
101In the example above ``pi.attr("exp")`` is a *bound method*: it will always call
Henry Schreinerd8c7ee02020-07-20 13:35:21 -0400102the method for that same instance of the class. Alternately one can create an
103*unbound method* via the Python class (instead of instance) and pass the ``self``
jbarlow839f823702017-09-13 07:18:08 -0700104object explicitly, followed by other arguments.
105
106.. code-block:: cpp
107
108 py::object decimal_exp = Decimal.attr("exp");
109
110 // Compute the e^n for n=0..4
111 for (int n = 0; n < 5; n++) {
112 py::print(decimal_exp(Decimal(n));
113 }
114
115Keyword arguments
116=================
117
Dean Moldovan67b52d82016-10-16 19:12:43 +0200118Keyword arguments are also supported. In Python, there is the usual call syntax:
119
120.. code-block:: python
121
122 def f(number, say, to):
123 ... # function code
124
125 f(1234, say="hello", to=some_instance) # keyword call in Python
126
127In C++, the same call can be made using:
128
129.. code-block:: cpp
130
myd73499b815ad2017-01-13 18:15:52 +0800131 using namespace pybind11::literals; // to bring in the `_a` literal
Dean Moldovan67b52d82016-10-16 19:12:43 +0200132 f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
133
jbarlow839f823702017-09-13 07:18:08 -0700134Unpacking arguments
135===================
136
Dean Moldovan67b52d82016-10-16 19:12:43 +0200137Unpacking of ``*args`` and ``**kwargs`` is also possible and can be mixed with
138other arguments:
139
140.. code-block:: cpp
141
142 // * unpacking
143 py::tuple args = py::make_tuple(1234, "hello", some_instance);
144 f(*args);
145
146 // ** unpacking
147 py::dict kwargs = py::dict("number"_a=1234, "say"_a="hello", "to"_a=some_instance);
148 f(**kwargs);
149
150 // mixed keywords, * and ** unpacking
151 py::tuple args = py::make_tuple(1234);
152 py::dict kwargs = py::dict("to"_a=some_instance);
153 f(*args, "say"_a="hello", **kwargs);
154
155Generalized unpacking according to PEP448_ is also supported:
156
157.. code-block:: cpp
158
159 py::dict kwargs1 = py::dict("number"_a=1234);
160 py::dict kwargs2 = py::dict("to"_a=some_instance);
161 f(**kwargs1, "say"_a="hello", **kwargs2);
162
163.. seealso::
164
Dean Moldovan83e328f2017-06-09 00:44:49 +0200165 The file :file:`tests/test_pytypes.cpp` contains a complete
Dean Moldovan67b52d82016-10-16 19:12:43 +0200166 example that demonstrates passing native Python types in more detail. The
167 file :file:`tests/test_callbacks.cpp` presents a few examples of calling
168 Python functions from C++, including keywords arguments and unpacking.
169
170.. _PEP448: https://www.python.org/dev/peps/pep-0448/