blob: ac6318f0e4b73f8c5ba36a5b872a4467a2c4e40a [file] [log] [blame]
Dean Moldovan67b52d82016-10-16 19:12:43 +02001STL containers
2##############
3
4Automatic conversion
5====================
6
7When including the additional header file :file:`pybind11/stl.h`, conversions
Wenzel Jakobbaec23c2017-02-17 12:59:32 +01008between ``std::vector<>``/``std::list<>``/``std::array<>``,
9``std::set<>``/``std::unordered_set<>``, and
10``std::map<>``/``std::unordered_map<>`` and the Python ``list``, ``set`` and
11``dict`` data structures are automatically enabled. The types ``std::pair<>``
12and ``std::tuple<>`` are already supported out of the box with just the core
13:file:`pybind11/pybind11.h` header.
Dean Moldovan67b52d82016-10-16 19:12:43 +020014
15The major downside of these implicit conversions is that containers must be
16converted (i.e. copied) on every Python->C++ and C++->Python transition, which
17can have implications on the program semantics and performance. Please read the
18next sections for more details and alternative approaches that avoid this.
19
20.. note::
21
22 Arbitrary nesting of any of these types is possible.
23
24.. seealso::
25
Dean Moldovan83e328f2017-06-09 00:44:49 +020026 The file :file:`tests/test_stl.cpp` contains a complete
Dean Moldovan67b52d82016-10-16 19:12:43 +020027 example that demonstrates how to pass STL data types in more detail.
28
Dean Moldovan4ffa76e2017-04-21 23:54:41 +020029C++17 library containers
30========================
31
32The :file:`pybind11/stl.h` header also includes support for ``std::optional<>``
33and ``std::variant<>``. These require a C++17 compiler and standard library.
34In C++14 mode, ``std::experimental::optional<>`` is supported if available.
35
36Various versions of these containers also exist for C++11 (e.g. in Boost).
37pybind11 provides an easy way to specialize the ``type_caster`` for such
38types:
39
40.. code-block:: cpp
41
42 // `boost::optional` as an example -- can be any `std::optional`-like container
43 namespace pybind11 { namespace detail {
44 template <typename T>
45 struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {};
46 }}
47
48The above should be placed in a header file and included in all translation units
49where automatic conversion is needed. Similarly, a specialization can be provided
50for custom variant types:
51
52.. code-block:: cpp
53
54 // `boost::variant` as an example -- can be any `std::variant`-like container
55 namespace pybind11 { namespace detail {
56 template <typename... Ts>
57 struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {};
58
59 // Specifies the function used to visit the variant -- `apply_visitor` instead of `visit`
60 template <>
61 struct visit_helper<boost::variant> {
62 template <typename... Args>
63 static auto call(Args &&...args)
Jason Rhinelanderebd6ad52017-08-07 15:48:49 -040064 -> decltype(boost::apply_visitor(args...)) {
65 return boost::apply_visitor(args...);
Dean Moldovan4ffa76e2017-04-21 23:54:41 +020066 }
67 };
68 }} // namespace pybind11::detail
69
70The ``visit_helper`` specialization is not required if your ``name::variant`` provides
71a ``name::visit()`` function. For any other function name, the specialization must be
72included to tell pybind11 how to visit the variant.
73
Dean Moldovan67b52d82016-10-16 19:12:43 +020074.. _opaque:
75
76Making opaque types
77===================
78
79pybind11 heavily relies on a template matching mechanism to convert parameters
80and return values that are constructed from STL data types such as vectors,
81linked lists, hash tables, etc. This even works in a recursive manner, for
82instance to deal with lists of hash maps of pairs of elementary and custom
83types, etc.
84
85However, a fundamental limitation of this approach is that internal conversions
86between Python and C++ types involve a copy operation that prevents
87pass-by-reference semantics. What does this mean?
88
89Suppose we bind the following function
90
91.. code-block:: cpp
92
93 void append_1(std::vector<int> &v) {
94 v.push_back(1);
95 }
96
97and call it from Python, the following happens:
98
99.. code-block:: pycon
100
101 >>> v = [5, 6]
102 >>> append_1(v)
103 >>> print(v)
104 [5, 6]
105
106As you can see, when passing STL data structures by reference, modifications
107are not propagated back the Python side. A similar situation arises when
108exposing STL data structures using the ``def_readwrite`` or ``def_readonly``
109functions:
110
111.. code-block:: cpp
112
113 /* ... definition ... */
114
115 class MyClass {
116 std::vector<int> contents;
117 };
118
119 /* ... binding code ... */
120
121 py::class_<MyClass>(m, "MyClass")
myd73499b815ad2017-01-13 18:15:52 +0800122 .def(py::init<>())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200123 .def_readwrite("contents", &MyClass::contents);
124
125In this case, properties can be read and written in their entirety. However, an
126``append`` operation involving such a list type has no effect:
127
128.. code-block:: pycon
129
130 >>> m = MyClass()
131 >>> m.contents = [5, 6]
132 >>> print(m.contents)
133 [5, 6]
134 >>> m.contents.append(7)
135 >>> print(m.contents)
136 [5, 6]
137
138Finally, the involved copy operations can be costly when dealing with very
139large lists. To deal with all of the above situations, pybind11 provides a
140macro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based
141conversion machinery of types, thus rendering them *opaque*. The contents of
142opaque objects are never inspected or extracted, hence they *can* be passed by
143reference. For instance, to turn ``std::vector<int>`` into an opaque type, add
144the declaration
145
146.. code-block:: cpp
147
148 PYBIND11_MAKE_OPAQUE(std::vector<int>);
149
150before any binding code (e.g. invocations to ``class_::def()``, etc.). This
151macro must be specified at the top level (and outside of any namespaces), since
152it instantiates a partial template overload. If your binding code consists of
Jason Rhinelander7437c692017-07-28 22:03:44 -0400153multiple compilation units, it must be present in every file (typically via a
154common header) preceding any usage of ``std::vector<int>``. Opaque types must
155also have a corresponding ``class_`` declaration to associate them with a name
156in Python, and to define a set of available operations, e.g.:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200157
158.. code-block:: cpp
159
160 py::class_<std::vector<int>>(m, "IntVector")
161 .def(py::init<>())
162 .def("clear", &std::vector<int>::clear)
163 .def("pop_back", &std::vector<int>::pop_back)
164 .def("__len__", [](const std::vector<int> &v) { return v.size(); })
165 .def("__iter__", [](std::vector<int> &v) {
166 return py::make_iterator(v.begin(), v.end());
167 }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
168 // ....
169
Jason Rhinelander7437c692017-07-28 22:03:44 -0400170Please take a look at the :ref:`macro_notes` before using the
171``PYBIND11_MAKE_OPAQUE`` macro.
172
173.. seealso::
174
175 The file :file:`tests/test_opaque_types.cpp` contains a complete
176 example that demonstrates how to create and expose opaque types using
177 pybind11 in more detail.
178
179.. _stl_bind:
180
181Binding STL containers
182======================
183
Dean Moldovan67b52d82016-10-16 19:12:43 +0200184The ability to expose STL containers as native Python objects is a fairly
185common request, hence pybind11 also provides an optional header file named
186:file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try
187to match the behavior of their native Python counterparts as much as possible.
188
189The following example showcases usage of :file:`pybind11/stl_bind.h`:
190
191.. code-block:: cpp
192
193 // Don't forget this
194 #include <pybind11/stl_bind.h>
195
196 PYBIND11_MAKE_OPAQUE(std::vector<int>);
197 PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
198
199 // ...
200
201 // later in binding code:
202 py::bind_vector<std::vector<int>>(m, "VectorInt");
203 py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
204
Jason Rhinelander7437c692017-07-28 22:03:44 -0400205When binding STL containers pybind11 considers the types of the container's
206elements to decide whether the container should be confined to the local module
207(via the :ref:`module_local` feature). If the container element types are
208anything other than already-bound custom types bound without
209``py::module_local()`` the container binding will have ``py::module_local()``
210applied. This includes converting types such as numeric types, strings, Eigen
211types; and types that have not yet been bound at the time of the stl container
212binding. This module-local binding is designed to avoid potential conflicts
213between module bindings (for example, from two separate modules each attempting
214to bind ``std::vector<int>`` as a python type).
215
216It is possible to override this behavior to force a definition to be either
217module-local or global. To do so, you can pass the attributes
218``py::module_local()`` (to make the binding module-local) or
219``py::module_local(false)`` (to make the binding global) into the
220``py::bind_vector`` or ``py::bind_map`` arguments:
221
222.. code-block:: cpp
223
224 py::bind_vector<std::vector<int>>(m, "VectorInt", py::module_local(false));
225
226Note, however, that such a global binding would make it impossible to load this
227module at the same time as any other pybind module that also attempts to bind
228the same container type (``std::vector<int>`` in the above example).
229
230See :ref:`module_local` for more details on module-local bindings.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200231
232.. seealso::
233
Dean Moldovan67b52d82016-10-16 19:12:43 +0200234 The file :file:`tests/test_stl_binders.cpp` shows how to use the
235 convenience STL container wrappers.