1Python 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
36.. _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
58.. _calling_python_functions:
59
60Calling Python functions
61========================
62
63It is also possible to call Python classes, functions and methods 
64via ``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
78One can convert the result obtained from Python to a pure C++ version 
79if a ``py::class_`` or type conversion is defined.
80
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
87.. _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
102the 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`` 
104object 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
118Keyword 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
131    using namespace pybind11::literals; // to bring in the `_a` literal
132    f(1234, "say"_a="hello", "to"_a=some_instance); // keyword call in C++
133
134Unpacking arguments
135===================
136
137Unpacking 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
165    The file :file:`tests/test_pytypes.cpp` contains a complete
166    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/
171