blob: 2d709d7cd059fe6096ac77edc2b64d0ae0e35c65 [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>
Dean Moldovan7918bcc2017-08-08 16:02:31 +020063 static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) {
Jason Rhinelanderebd6ad52017-08-07 15:48:49 -040064 return boost::apply_visitor(args...);
Dean Moldovan4ffa76e2017-04-21 23:54:41 +020065 }
66 };
67 }} // namespace pybind11::detail
68
69The ``visit_helper`` specialization is not required if your ``name::variant`` provides
70a ``name::visit()`` function. For any other function name, the specialization must be
71included to tell pybind11 how to visit the variant.
72
Dean Moldovan7918bcc2017-08-08 16:02:31 +020073.. note::
74
75 pybind11 only supports the modern implementation of ``boost::variant``
76 which makes use of variadic templates. This requires Boost 1.56 or newer.
77 Additionally, on Windows, MSVC 2017 is required because ``boost::variant``
78 falls back to the old non-variadic implementation on MSVC 2015.
79
Dean Moldovan67b52d82016-10-16 19:12:43 +020080.. _opaque:
81
82Making opaque types
83===================
84
85pybind11 heavily relies on a template matching mechanism to convert parameters
86and return values that are constructed from STL data types such as vectors,
87linked lists, hash tables, etc. This even works in a recursive manner, for
88instance to deal with lists of hash maps of pairs of elementary and custom
89types, etc.
90
91However, a fundamental limitation of this approach is that internal conversions
92between Python and C++ types involve a copy operation that prevents
93pass-by-reference semantics. What does this mean?
94
95Suppose we bind the following function
96
97.. code-block:: cpp
98
99 void append_1(std::vector<int> &v) {
100 v.push_back(1);
101 }
102
103and call it from Python, the following happens:
104
105.. code-block:: pycon
106
107 >>> v = [5, 6]
108 >>> append_1(v)
109 >>> print(v)
110 [5, 6]
111
112As you can see, when passing STL data structures by reference, modifications
113are not propagated back the Python side. A similar situation arises when
114exposing STL data structures using the ``def_readwrite`` or ``def_readonly``
115functions:
116
117.. code-block:: cpp
118
119 /* ... definition ... */
120
121 class MyClass {
122 std::vector<int> contents;
123 };
124
125 /* ... binding code ... */
126
127 py::class_<MyClass>(m, "MyClass")
myd73499b815ad2017-01-13 18:15:52 +0800128 .def(py::init<>())
Dean Moldovan67b52d82016-10-16 19:12:43 +0200129 .def_readwrite("contents", &MyClass::contents);
130
131In this case, properties can be read and written in their entirety. However, an
132``append`` operation involving such a list type has no effect:
133
134.. code-block:: pycon
135
136 >>> m = MyClass()
137 >>> m.contents = [5, 6]
138 >>> print(m.contents)
139 [5, 6]
140 >>> m.contents.append(7)
141 >>> print(m.contents)
142 [5, 6]
143
144Finally, the involved copy operations can be costly when dealing with very
145large lists. To deal with all of the above situations, pybind11 provides a
146macro named ``PYBIND11_MAKE_OPAQUE(T)`` that disables the template-based
147conversion machinery of types, thus rendering them *opaque*. The contents of
148opaque objects are never inspected or extracted, hence they *can* be passed by
149reference. For instance, to turn ``std::vector<int>`` into an opaque type, add
150the declaration
151
152.. code-block:: cpp
153
154 PYBIND11_MAKE_OPAQUE(std::vector<int>);
155
156before any binding code (e.g. invocations to ``class_::def()``, etc.). This
157macro must be specified at the top level (and outside of any namespaces), since
158it instantiates a partial template overload. If your binding code consists of
Jason Rhinelander7437c692017-07-28 22:03:44 -0400159multiple compilation units, it must be present in every file (typically via a
160common header) preceding any usage of ``std::vector<int>``. Opaque types must
161also have a corresponding ``class_`` declaration to associate them with a name
162in Python, and to define a set of available operations, e.g.:
Dean Moldovan67b52d82016-10-16 19:12:43 +0200163
164.. code-block:: cpp
165
166 py::class_<std::vector<int>>(m, "IntVector")
167 .def(py::init<>())
168 .def("clear", &std::vector<int>::clear)
169 .def("pop_back", &std::vector<int>::pop_back)
170 .def("__len__", [](const std::vector<int> &v) { return v.size(); })
171 .def("__iter__", [](std::vector<int> &v) {
172 return py::make_iterator(v.begin(), v.end());
173 }, py::keep_alive<0, 1>()) /* Keep vector alive while iterator is used */
174 // ....
175
Jason Rhinelander7437c692017-07-28 22:03:44 -0400176Please take a look at the :ref:`macro_notes` before using the
177``PYBIND11_MAKE_OPAQUE`` macro.
178
179.. seealso::
180
181 The file :file:`tests/test_opaque_types.cpp` contains a complete
182 example that demonstrates how to create and expose opaque types using
183 pybind11 in more detail.
184
185.. _stl_bind:
186
187Binding STL containers
188======================
189
Dean Moldovan67b52d82016-10-16 19:12:43 +0200190The ability to expose STL containers as native Python objects is a fairly
191common request, hence pybind11 also provides an optional header file named
192:file:`pybind11/stl_bind.h` that does exactly this. The mapped containers try
193to match the behavior of their native Python counterparts as much as possible.
194
195The following example showcases usage of :file:`pybind11/stl_bind.h`:
196
197.. code-block:: cpp
198
199 // Don't forget this
200 #include <pybind11/stl_bind.h>
201
202 PYBIND11_MAKE_OPAQUE(std::vector<int>);
203 PYBIND11_MAKE_OPAQUE(std::map<std::string, double>);
204
205 // ...
206
207 // later in binding code:
208 py::bind_vector<std::vector<int>>(m, "VectorInt");
209 py::bind_map<std::map<std::string, double>>(m, "MapStringDouble");
210
Jason Rhinelander7437c692017-07-28 22:03:44 -0400211When binding STL containers pybind11 considers the types of the container's
212elements to decide whether the container should be confined to the local module
213(via the :ref:`module_local` feature). If the container element types are
214anything other than already-bound custom types bound without
215``py::module_local()`` the container binding will have ``py::module_local()``
216applied. This includes converting types such as numeric types, strings, Eigen
217types; and types that have not yet been bound at the time of the stl container
218binding. This module-local binding is designed to avoid potential conflicts
219between module bindings (for example, from two separate modules each attempting
220to bind ``std::vector<int>`` as a python type).
221
222It is possible to override this behavior to force a definition to be either
223module-local or global. To do so, you can pass the attributes
224``py::module_local()`` (to make the binding module-local) or
225``py::module_local(false)`` (to make the binding global) into the
226``py::bind_vector`` or ``py::bind_map`` arguments:
227
228.. code-block:: cpp
229
230 py::bind_vector<std::vector<int>>(m, "VectorInt", py::module_local(false));
231
232Note, however, that such a global binding would make it impossible to load this
233module at the same time as any other pybind module that also attempts to bind
234the same container type (``std::vector<int>`` in the above example).
235
236See :ref:`module_local` for more details on module-local bindings.
Dean Moldovan67b52d82016-10-16 19:12:43 +0200237
238.. seealso::
239
Dean Moldovan67b52d82016-10-16 19:12:43 +0200240 The file :file:`tests/test_stl_binders.cpp` shows how to use the
241 convenience STL container wrappers.