μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
stl_bind.h
Go to the documentation of this file.
1/*
2 pybind11/std_bind.h: Binding generators for STL data types
3
4 Copyright (c) 2016 Sergey Lyskov and Wenzel Jakob
5
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8*/
9
10#pragma once
11
12#include "detail/common.h"
13#include "detail/type_caster_base.h"
14#include "cast.h"
15#include "operators.h"
16
17#include <algorithm>
18#include <sstream>
19#include <type_traits>
20
23
24/* SFINAE helper class used by 'is_comparable */
25template <typename T>
26struct container_traits {
27 template <typename T2>
28 static std::true_type
29 test_comparable(decltype(std::declval<const T2 &>() == std::declval<const T2 &>()) *);
30 template <typename T2>
31 static std::false_type test_comparable(...);
32 template <typename T2>
33 static std::true_type test_value(typename T2::value_type *);
34 template <typename T2>
35 static std::false_type test_value(...);
36 template <typename T2>
37 static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *);
38 template <typename T2>
39 static std::false_type test_pair(...);
40
41 static constexpr const bool is_comparable
42 = std::is_same<std::true_type, decltype(test_comparable<T>(nullptr))>::value;
43 static constexpr const bool is_pair
44 = std::is_same<std::true_type, decltype(test_pair<T>(nullptr, nullptr))>::value;
45 static constexpr const bool is_vector
46 = std::is_same<std::true_type, decltype(test_value<T>(nullptr))>::value;
47 static constexpr const bool is_element = !is_pair && !is_vector;
48};
49
50/* Default: is_comparable -> std::false_type */
51template <typename T, typename SFINAE = void>
52struct is_comparable : std::false_type {};
53
54/* For non-map data structures, check whether operator== can be instantiated */
55template <typename T>
56struct is_comparable<
57 T,
59 : std::true_type {};
60
61/* For a vector/map data structure, recursively check the value type
62 (which is std::pair for maps) */
63template <typename T>
64struct is_comparable<T, enable_if_t<container_traits<T>::is_vector>> {
65 static constexpr const bool value = is_comparable<typename T::value_type>::value;
66};
67
68/* For pairs, recursively check the two data types */
69template <typename T>
70struct is_comparable<T, enable_if_t<container_traits<T>::is_pair>> {
71 static constexpr const bool value = is_comparable<typename T::first_type>::value
73};
74
75/* Fallback functions */
76template <typename, typename, typename... Args>
77void vector_if_copy_constructible(const Args &...) {}
78template <typename, typename, typename... Args>
79void vector_if_equal_operator(const Args &...) {}
80template <typename, typename, typename... Args>
81void vector_if_insertion_operator(const Args &...) {}
82template <typename, typename, typename... Args>
83void vector_modifiers(const Args &...) {}
84
85template <typename Vector, typename Class_>
87 cl.def(init<const Vector &>(), "Copy constructor");
88}
89
90template <typename Vector, typename Class_>
92 using T = typename Vector::value_type;
93
94 cl.def(self == self);
95 cl.def(self != self);
96
97 cl.def(
98 "count",
99 [](const Vector &v, const T &x) { return std::count(v.begin(), v.end(), x); },
100 arg("x"),
101 "Return the number of times ``x`` appears in the list");
102
103 cl.def(
104 "remove",
105 [](Vector &v, const T &x) {
106 auto p = std::find(v.begin(), v.end(), x);
107 if (p != v.end()) {
108 v.erase(p);
109 } else {
110 throw value_error();
111 }
112 },
113 arg("x"),
114 "Remove the first item from the list whose value is x. "
115 "It is an error if there is no such item.");
116
117 cl.def(
118 "__contains__",
119 [](const Vector &v, const T &x) { return std::find(v.begin(), v.end(), x) != v.end(); },
120 arg("x"),
121 "Return true the container contains ``x``");
122}
123
124// Vector modifiers -- requires a copyable vector_type:
125// (Technically, some of these (pop and __delitem__) don't actually require copyability, but it
126// seems silly to allow deletion but not insertion, so include them here too.)
127template <typename Vector, typename Class_>
130 using T = typename Vector::value_type;
131 using SizeType = typename Vector::size_type;
132 using DiffType = typename Vector::difference_type;
133
134 auto wrap_i = [](DiffType i, SizeType n) {
135 if (i < 0) {
136 i += n;
137 }
138 if (i < 0 || (SizeType) i >= n) {
139 throw index_error();
140 }
141 return i;
142 };
143
144 cl.def(
145 "append",
146 [](Vector &v, const T &value) { v.push_back(value); },
147 arg("x"),
148 "Add an item to the end of the list");
149
150 cl.def(init([](const iterable &it) {
151 auto v = std::unique_ptr<Vector>(new Vector());
152 v->reserve(len_hint(it));
153 for (handle h : it) {
154 v->push_back(h.cast<T>());
155 }
156 return v.release();
157 }));
158
159 cl.def(
160 "clear", [](Vector &v) { v.clear(); }, "Clear the contents");
161
162 cl.def(
163 "extend",
164 [](Vector &v, const Vector &src) { v.insert(v.end(), src.begin(), src.end()); },
165 arg("L"),
166 "Extend the list by appending all the items in the given list");
167
168 cl.def(
169 "extend",
170 [](Vector &v, const iterable &it) {
171 const size_t old_size = v.size();
172 v.reserve(old_size + len_hint(it));
173 try {
174 for (handle h : it) {
175 v.push_back(h.cast<T>());
176 }
177 } catch (const cast_error &) {
178 v.erase(v.begin() + static_cast<typename Vector::difference_type>(old_size),
179 v.end());
180 try {
181 v.shrink_to_fit();
182 } catch (const std::exception &) {
183 // Do nothing
184 }
185 throw;
186 }
187 },
188 arg("L"),
189 "Extend the list by appending all the items in the given list");
190
191 cl.def(
192 "insert",
193 [](Vector &v, DiffType i, const T &x) {
194 // Can't use wrap_i; i == v.size() is OK
195 if (i < 0) {
196 i += v.size();
197 }
198 if (i < 0 || (SizeType) i > v.size()) {
199 throw index_error();
200 }
201 v.insert(v.begin() + i, x);
202 },
203 arg("i"),
204 arg("x"),
205 "Insert an item at a given position.");
206
207 cl.def(
208 "pop",
209 [](Vector &v) {
210 if (v.empty()) {
211 throw index_error();
212 }
213 T t = std::move(v.back());
214 v.pop_back();
215 return t;
216 },
217 "Remove and return the last item");
218
219 cl.def(
220 "pop",
221 [wrap_i](Vector &v, DiffType i) {
222 i = wrap_i(i, v.size());
223 T t = std::move(v[(SizeType) i]);
224 v.erase(std::next(v.begin(), i));
225 return t;
226 },
227 arg("i"),
228 "Remove and return the item at index ``i``");
229
230 cl.def("__setitem__", [wrap_i](Vector &v, DiffType i, const T &t) {
231 i = wrap_i(i, v.size());
232 v[(SizeType) i] = t;
233 });
234
236 cl.def(
237 "__getitem__",
238 [](const Vector &v, const slice &slice) -> Vector * {
239 size_t start = 0, stop = 0, step = 0, slicelength = 0;
240
241 if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
242 throw error_already_set();
243 }
244
245 auto *seq = new Vector();
246 seq->reserve((size_t) slicelength);
247
248 for (size_t i = 0; i < slicelength; ++i) {
249 seq->push_back(v[start]);
250 start += step;
251 }
252 return seq;
253 },
254 arg("s"),
255 "Retrieve list elements using a slice object");
256
257 cl.def(
258 "__setitem__",
259 [](Vector &v, const slice &slice, const Vector &value) {
260 size_t start = 0, stop = 0, step = 0, slicelength = 0;
261 if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
262 throw error_already_set();
263 }
264
265 if (slicelength != value.size()) {
266 throw std::runtime_error(
267 "Left and right hand size of slice assignment have different sizes!");
268 }
269
270 for (size_t i = 0; i < slicelength; ++i) {
271 v[start] = value[i];
272 start += step;
273 }
274 },
275 "Assign list elements using a slice object");
276
277 cl.def(
278 "__delitem__",
279 [wrap_i](Vector &v, DiffType i) {
280 i = wrap_i(i, v.size());
281 v.erase(v.begin() + i);
282 },
283 "Delete the list elements at index ``i``");
284
285 cl.def(
286 "__delitem__",
287 [](Vector &v, const slice &slice) {
288 size_t start = 0, stop = 0, step = 0, slicelength = 0;
289
290 if (!slice.compute(v.size(), &start, &stop, &step, &slicelength)) {
291 throw error_already_set();
292 }
293
294 if (step == 1 && false) {
295 v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
296 } else {
297 for (size_t i = 0; i < slicelength; ++i) {
298 v.erase(v.begin() + DiffType(start));
299 start += step - 1;
300 }
301 }
302 },
303 "Delete list elements using a slice object");
304}
305
306// If the type has an operator[] that doesn't return a reference (most notably std::vector<bool>),
307// we have to access by copying; otherwise we return by reference.
308template <typename Vector>
310 = negation<std::is_same<decltype(std::declval<Vector>()[typename Vector::size_type()]),
311 typename Vector::value_type &>>;
312
313// The usual case: access and iterate by reference
314template <typename Vector, typename Class_>
316 using T = typename Vector::value_type;
317 using SizeType = typename Vector::size_type;
318 using DiffType = typename Vector::difference_type;
319 using ItType = typename Vector::iterator;
320
321 auto wrap_i = [](DiffType i, SizeType n) {
322 if (i < 0) {
323 i += n;
324 }
325 if (i < 0 || (SizeType) i >= n) {
326 throw index_error();
327 }
328 return i;
329 };
330
331 cl.def(
332 "__getitem__",
333 [wrap_i](Vector &v, DiffType i) -> T & {
334 i = wrap_i(i, v.size());
335 return v[(SizeType) i];
336 },
338 );
339
340 cl.def(
341 "__iter__",
342 [](Vector &v) {
343 return make_iterator<return_value_policy::reference_internal, ItType, ItType, T &>(
344 v.begin(), v.end());
345 },
346 keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
347 );
348}
349
350// The case for special objects, like std::vector<bool>, that have to be returned-by-copy:
351template <typename Vector, typename Class_>
353 using T = typename Vector::value_type;
354 using SizeType = typename Vector::size_type;
355 using DiffType = typename Vector::difference_type;
356 using ItType = typename Vector::iterator;
357 cl.def("__getitem__", [](const Vector &v, DiffType i) -> T {
358 if (i < 0 && (i += v.size()) < 0) {
359 throw index_error();
360 }
361 if ((SizeType) i >= v.size()) {
362 throw index_error();
363 }
364 return v[(SizeType) i];
365 });
366
367 cl.def(
368 "__iter__",
369 [](Vector &v) {
370 return make_iterator<return_value_policy::copy, ItType, ItType, T>(v.begin(), v.end());
371 },
372 keep_alive<0, 1>() /* Essential: keep list alive while iterator exists */
373 );
374}
375
376template <typename Vector, typename Class_>
377auto vector_if_insertion_operator(Class_ &cl, std::string const &name)
378 -> decltype(std::declval<std::ostream &>() << std::declval<typename Vector::value_type>(),
379 void()) {
380 using size_type = typename Vector::size_type;
381
382 cl.def(
383 "__repr__",
384 [name](Vector &v) {
385 std::ostringstream s;
386 s << name << '[';
387 for (size_type i = 0; i < v.size(); ++i) {
388 s << v[i];
389 if (i != v.size() - 1) {
390 s << ", ";
391 }
392 }
393 s << ']';
394 return s.str();
395 },
396 "Return the canonical string representation of this list.");
397}
398
399// Provide the buffer interface for vectors if we have data() and we have a format for it
400// GCC seems to have "void std::vector<bool>::data()" - doing SFINAE on the existence of data()
401// is insufficient, we need to check it returns an appropriate pointer
402template <typename Vector, typename = void>
403struct vector_has_data_and_format : std::false_type {};
404template <typename Vector>
406 Vector,
407 enable_if_t<std::is_same<decltype(format_descriptor<typename Vector::value_type>::format(),
408 std::declval<Vector>().data()),
409 typename Vector::value_type *>::value>> : std::true_type {};
410
411// [workaround(intel)] Separate function required here
412// Workaround as the Intel compiler does not compile the enable_if_t part below
413// (tested with icc (ICC) 2021.1 Beta 20200827)
414template <typename... Args>
415constexpr bool args_any_are_buffer() {
416 return detail::any_of<std::is_same<Args, buffer_protocol>...>::value;
417}
418
419// [workaround(intel)] Separate function required here
420// [workaround(msvc)] Can't use constexpr bool in return type
421
422// Add the buffer interface to a vector
423template <typename Vector, typename Class_, typename... Args>
424void vector_buffer_impl(Class_ &cl, std::true_type) {
425 using T = typename Vector::value_type;
426
428 "There is not an appropriate format descriptor for this vector");
429
430 // numpy.h declares this for arbitrary types, but it may raise an exception and crash hard
431 // at runtime if PYBIND11_NUMPY_DTYPE hasn't been called, so check here
433
434 cl.def_buffer([](Vector &v) -> buffer_info {
435 return buffer_info(v.data(),
436 static_cast<ssize_t>(sizeof(T)),
438 1,
439 {v.size()},
440 {sizeof(T)});
441 });
442
443 cl.def(init([](const buffer &buf) {
444 auto info = buf.request();
445 if (info.ndim != 1 || info.strides[0] % static_cast<ssize_t>(sizeof(T))) {
446 throw type_error("Only valid 1D buffers can be copied to a vector");
447 }
448 if (!detail::compare_buffer_info<T>::compare(info)
449 || (ssize_t) sizeof(T) != info.itemsize) {
450 throw type_error("Format mismatch (Python: " + info.format
451 + " C++: " + format_descriptor<T>::format() + ")");
452 }
453
454 T *p = static_cast<T *>(info.ptr);
455 ssize_t step = info.strides[0] / static_cast<ssize_t>(sizeof(T));
456 T *end = p + info.shape[0] * step;
457 if (step == 1) {
458 return Vector(p, end);
459 }
460 Vector vec;
461 vec.reserve((size_t) info.shape[0]);
462 for (; p != end; p += step) {
463 vec.push_back(*p);
464 }
465 return vec;
466 }));
467
468 return;
469}
470
471template <typename Vector, typename Class_, typename... Args>
472void vector_buffer_impl(Class_ &, std::false_type) {}
473
474template <typename Vector, typename Class_, typename... Args>
475void vector_buffer(Class_ &cl) {
476 vector_buffer_impl<Vector, Class_, Args...>(
477 cl, detail::any_of<std::is_same<Args, buffer_protocol>...>{});
478}
479
481
482//
483// std::vector
484//
485template <typename Vector, typename holder_type = std::unique_ptr<Vector>, typename... Args>
487 using Class_ = class_<Vector, holder_type>;
488
489 // If the value_type is unregistered (e.g. a converting type) or is itself registered
490 // module-local then make the vector binding module-local as well:
491 using vtype = typename Vector::value_type;
492 auto *vtype_info = detail::get_type_info(typeid(vtype));
493 bool local = !vtype_info || vtype_info->module_local;
494
495 Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
496
497 // Declare the buffer interface if a buffer_protocol() is passed in
498 detail::vector_buffer<Vector, Class_, Args...>(cl);
499
500 cl.def(init<>());
501
502 // Register copy constructor (if possible)
503 detail::vector_if_copy_constructible<Vector, Class_>(cl);
504
505 // Register comparison-related operators and functions (if possible)
506 detail::vector_if_equal_operator<Vector, Class_>(cl);
507
508 // Register stream insertion operator (if possible)
509 detail::vector_if_insertion_operator<Vector, Class_>(cl, name);
510
511 // Modifiers require copyable vector value type
512 detail::vector_modifiers<Vector, Class_>(cl);
513
514 // Accessor and iterator; return by value if copyable, otherwise we return by ref + keep-alive
515 detail::vector_accessor<Vector, Class_>(cl);
516
517 cl.def(
518 "__bool__",
519 [](const Vector &v) -> bool { return !v.empty(); },
520 "Check whether the list is nonempty");
521
522 cl.def("__len__", &Vector::size);
523
524#if 0
525 // C++ style functions deprecated, leaving it here as an example
526 cl.def(init<size_type>());
527
528 cl.def("resize",
529 (void (Vector::*) (size_type count)) & Vector::resize,
530 "changes the number of elements stored");
531
532 cl.def("erase",
533 [](Vector &v, SizeType i) {
534 if (i >= v.size())
535 throw index_error();
536 v.erase(v.begin() + i);
537 }, "erases element at index ``i``");
538
539 cl.def("empty", &Vector::empty, "checks whether the container is empty");
540 cl.def("size", &Vector::size, "returns the number of elements");
541 cl.def("push_back", (void (Vector::*)(const T&)) &Vector::push_back, "adds an element to the end");
542 cl.def("pop_back", &Vector::pop_back, "removes the last element");
543
544 cl.def("max_size", &Vector::max_size, "returns the maximum possible number of elements");
545 cl.def("reserve", &Vector::reserve, "reserves storage");
546 cl.def("capacity", &Vector::capacity, "returns the number of elements that can be held in currently allocated storage");
547 cl.def("shrink_to_fit", &Vector::shrink_to_fit, "reduces memory usage by freeing unused memory");
548
549 cl.def("clear", &Vector::clear, "clears the contents");
550 cl.def("swap", &Vector::swap, "swaps the contents");
551
552 cl.def("front", [](Vector &v) {
553 if (v.size()) return v.front();
554 else throw index_error();
555 }, "access the first element");
556
557 cl.def("back", [](Vector &v) {
558 if (v.size()) return v.back();
559 else throw index_error();
560 }, "access the last element ");
561
562#endif
563
564 return cl;
565}
566
567//
568// std::map, std::unordered_map
569//
570
572
573/* Fallback functions */
574template <typename, typename, typename... Args>
575void map_if_insertion_operator(const Args &...) {}
576template <typename, typename, typename... Args>
577void map_assignment(const Args &...) {}
578
579// Map assignment when copy-assignable: just copy the value
580template <typename Map, typename Class_>
583 using KeyType = typename Map::key_type;
584 using MappedType = typename Map::mapped_type;
585
586 cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) {
587 auto it = m.find(k);
588 if (it != m.end()) {
589 it->second = v;
590 } else {
591 m.emplace(k, v);
592 }
593 });
594}
595
596// Not copy-assignable, but still copy-constructible: we can update the value by erasing and
597// reinserting
598template <typename Map, typename Class_>
601 Class_> &cl) {
602 using KeyType = typename Map::key_type;
603 using MappedType = typename Map::mapped_type;
604
605 cl.def("__setitem__", [](Map &m, const KeyType &k, const MappedType &v) {
606 // We can't use m[k] = v; because value type might not be default constructable
607 auto r = m.emplace(k, v);
608 if (!r.second) {
609 // value type is not copy assignable so the only way to insert it is to erase it
610 // first...
611 m.erase(r.first);
612 m.emplace(k, v);
613 }
614 });
615}
616
617template <typename Map, typename Class_>
618auto map_if_insertion_operator(Class_ &cl, std::string const &name)
619 -> decltype(std::declval<std::ostream &>() << std::declval<typename Map::key_type>()
620 << std::declval<typename Map::mapped_type>(),
621 void()) {
622
623 cl.def(
624 "__repr__",
625 [name](Map &m) {
626 std::ostringstream s;
627 s << name << '{';
628 bool f = false;
629 for (auto const &kv : m) {
630 if (f) {
631 s << ", ";
632 }
633 s << kv.first << ": " << kv.second;
634 f = true;
635 }
636 s << '}';
637 return s.str();
638 },
639 "Return the canonical string representation of this map.");
640}
641
642template <typename KeyType>
643struct keys_view {
644 virtual size_t len() = 0;
645 virtual iterator iter() = 0;
646 virtual bool contains(const KeyType &k) = 0;
647 virtual bool contains(const object &k) = 0;
648 virtual ~keys_view() = default;
649};
650
651template <typename MappedType>
652struct values_view {
653 virtual size_t len() = 0;
654 virtual iterator iter() = 0;
655 virtual ~values_view() = default;
656};
657
658template <typename KeyType, typename MappedType>
659struct items_view {
660 virtual size_t len() = 0;
661 virtual iterator iter() = 0;
662 virtual ~items_view() = default;
663};
664
665template <typename Map, typename KeysView>
666struct KeysViewImpl : public KeysView {
667 explicit KeysViewImpl(Map &map) : map(map) {}
668 size_t len() override { return map.size(); }
669 iterator iter() override { return make_key_iterator(map.begin(), map.end()); }
670 bool contains(const typename Map::key_type &k) override { return map.find(k) != map.end(); }
671 bool contains(const object &) override { return false; }
672 Map &map;
673};
674
675template <typename Map, typename ValuesView>
676struct ValuesViewImpl : public ValuesView {
677 explicit ValuesViewImpl(Map &map) : map(map) {}
678 size_t len() override { return map.size(); }
679 iterator iter() override { return make_value_iterator(map.begin(), map.end()); }
680 Map &map;
681};
682
683template <typename Map, typename ItemsView>
684struct ItemsViewImpl : public ItemsView {
685 explicit ItemsViewImpl(Map &map) : map(map) {}
686 size_t len() override { return map.size(); }
687 iterator iter() override { return make_iterator(map.begin(), map.end()); }
688 Map &map;
689};
690
692
693template <typename Map, typename holder_type = std::unique_ptr<Map>, typename... Args>
694class_<Map, holder_type> bind_map(handle scope, const std::string &name, Args &&...args) {
695 using KeyType = typename Map::key_type;
696 using MappedType = typename Map::mapped_type;
697 using StrippedKeyType = detail::remove_cvref_t<KeyType>;
698 using StrippedMappedType = detail::remove_cvref_t<MappedType>;
699 using KeysView = detail::keys_view<StrippedKeyType>;
700 using ValuesView = detail::values_view<StrippedMappedType>;
701 using ItemsView = detail::items_view<StrippedKeyType, StrippedMappedType>;
702 using Class_ = class_<Map, holder_type>;
703
704 // If either type is a non-module-local bound type then make the map binding non-local as well;
705 // otherwise (e.g. both types are either module-local or converting) the map will be
706 // module-local.
707 auto *tinfo = detail::get_type_info(typeid(MappedType));
708 bool local = !tinfo || tinfo->module_local;
709 if (local) {
710 tinfo = detail::get_type_info(typeid(KeyType));
711 local = !tinfo || tinfo->module_local;
712 }
713
714 Class_ cl(scope, name.c_str(), pybind11::module_local(local), std::forward<Args>(args)...);
715 static constexpr auto key_type_descr = detail::make_caster<KeyType>::name;
716 static constexpr auto mapped_type_descr = detail::make_caster<MappedType>::name;
717 std::string key_type_name(key_type_descr.text), mapped_type_name(mapped_type_descr.text);
718
719 // If key type isn't properly wrapped, fall back to C++ names
720 if (key_type_name == "%") {
721 key_type_name = detail::type_info_description(typeid(KeyType));
722 }
723 // Similarly for value type:
724 if (mapped_type_name == "%") {
725 mapped_type_name = detail::type_info_description(typeid(MappedType));
726 }
727
728 // Wrap KeysView[KeyType] if it wasn't already wrapped
729 if (!detail::get_type_info(typeid(KeysView))) {
731 scope, ("KeysView[" + key_type_name + "]").c_str(), pybind11::module_local(local));
732 keys_view.def("__len__", &KeysView::len);
733 keys_view.def("__iter__",
734 &KeysView::iter,
735 keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
736 );
737 keys_view.def("__contains__",
738 static_cast<bool (KeysView::*)(const KeyType &)>(&KeysView::contains));
739 // Fallback for when the object is not of the key type
740 keys_view.def("__contains__",
741 static_cast<bool (KeysView::*)(const object &)>(&KeysView::contains));
742 }
743 // Similarly for ValuesView:
744 if (!detail::get_type_info(typeid(ValuesView))) {
746 ("ValuesView[" + mapped_type_name + "]").c_str(),
747 pybind11::module_local(local));
748 values_view.def("__len__", &ValuesView::len);
749 values_view.def("__iter__",
750 &ValuesView::iter,
751 keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
752 );
753 }
754 // Similarly for ItemsView:
755 if (!detail::get_type_info(typeid(ItemsView))) {
757 scope,
758 ("ItemsView[" + key_type_name + ", ").append(mapped_type_name + "]").c_str(),
759 pybind11::module_local(local));
760 items_view.def("__len__", &ItemsView::len);
761 items_view.def("__iter__",
762 &ItemsView::iter,
763 keep_alive<0, 1>() /* Essential: keep view alive while iterator exists */
764 );
765 }
766
767 cl.def(init<>());
768
769 // Register stream insertion operator (if possible)
770 detail::map_if_insertion_operator<Map, Class_>(cl, name);
771
772 cl.def(
773 "__bool__",
774 [](const Map &m) -> bool { return !m.empty(); },
775 "Check whether the map is nonempty");
776
777 cl.def(
778 "__iter__",
779 [](Map &m) { return make_key_iterator(m.begin(), m.end()); },
780 keep_alive<0, 1>() /* Essential: keep map alive while iterator exists */
781 );
782
783 cl.def(
784 "keys",
785 [](Map &m) {
786 return std::unique_ptr<KeysView>(new detail::KeysViewImpl<Map, KeysView>(m));
787 },
788 keep_alive<0, 1>() /* Essential: keep map alive while view exists */
789 );
790
791 cl.def(
792 "values",
793 [](Map &m) {
794 return std::unique_ptr<ValuesView>(new detail::ValuesViewImpl<Map, ValuesView>(m));
795 },
796 keep_alive<0, 1>() /* Essential: keep map alive while view exists */
797 );
798
799 cl.def(
800 "items",
801 [](Map &m) {
802 return std::unique_ptr<ItemsView>(new detail::ItemsViewImpl<Map, ItemsView>(m));
803 },
804 keep_alive<0, 1>() /* Essential: keep map alive while view exists */
805 );
806
807 cl.def(
808 "__getitem__",
809 [](Map &m, const KeyType &k) -> MappedType & {
810 auto it = m.find(k);
811 if (it == m.end()) {
812 throw key_error();
813 }
814 return it->second;
815 },
817 );
818
819 cl.def("__contains__", [](Map &m, const KeyType &k) -> bool {
820 auto it = m.find(k);
821 if (it == m.end()) {
822 return false;
823 }
824 return true;
825 });
826 // Fallback for when the object is not of the key type
827 cl.def("__contains__", [](Map &, const object &) -> bool { return false; });
828
829 // Assignment provided only if the type is copyable
830 detail::map_assignment<Map, Class_>(cl);
831
832 cl.def("__delitem__", [](Map &m, const KeyType &k) {
833 auto it = m.find(k);
834 if (it == m.end()) {
835 throw key_error();
836 }
837 m.erase(it);
838 });
839
840 cl.def("__len__", &Map::size);
841
842 return cl;
843}
844
Definition: pytypes.h:1776
buffer_info request(bool writable=false) const
Definition: pytypes.h:1826
Fetch and hold an error which was already set in Python.
Definition: pytypes.h:379
\rst Holds a reference to a Python object (no reference counting)
Definition: pytypes.h:194
\rst Wraps a Python iterator so that it can also be used as a C++ input iterator
Definition: pytypes.h:1102
bool compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const
Definition: pytypes.h:1565
static constexpr auto name
size_t len_hint(handle h)
Get the length hint of a Python object.
Definition: pytypes.h:2012
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
Definition: common.h:625
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
Py_ssize_t ssize_t
Definition: common.h:460
@ reference_internal
This policy only applies to methods and properties.
const char * c_str(Args &&...args)
Constructs a std::string with the given arguments, stores it in internals, and returns its c_str().
Definition: internals.h:534
static const self_t self
Definition: operators.h:72
iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the values (.second) of a iterator over pairs from a first and past-the-...
Definition: pybind11.h:2425
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1900
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the keys (.first) of a iterator over pairs from a first and past-the-end...
Definition: pybind11.h:2409
iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
Definition: pybind11.h:2393
class_< Vector, holder_type > bind_vector(handle scope, std::string const &name, Args &&...args)
Definition: stl_bind.h:486
void vector_buffer_impl(Class_ &cl, std::true_type)
Definition: stl_bind.h:424
void vector_if_equal_operator(const Args &...)
Definition: stl_bind.h:79
void vector_accessor(enable_if_t<!vector_needs_copy< Vector >::value, Class_ > &cl)
Definition: stl_bind.h:315
constexpr bool args_any_are_buffer()
Definition: stl_bind.h:415
void vector_if_copy_constructible(const Args &...)
Definition: stl_bind.h:77
void vector_buffer(Class_ &cl)
Definition: stl_bind.h:475
void map_assignment(const Args &...)
Definition: stl_bind.h:577
class_< Map, holder_type > bind_map(handle scope, const std::string &name, Args &&...args)
Definition: stl_bind.h:694
void vector_modifiers(const Args &...)
Definition: stl_bind.h:83
void vector_if_insertion_operator(const Args &...)
Definition: stl_bind.h:81
void map_if_insertion_operator(const Args &...)
Definition: stl_bind.h:575
iterator iter() override
Definition: stl_bind.h:687
size_t len() override
Definition: stl_bind.h:686
ItemsViewImpl(Map &map)
Definition: stl_bind.h:685
Map & map
Definition: stl_bind.h:672
bool contains(const typename Map::key_type &k) override
Definition: stl_bind.h:670
KeysViewImpl(Map &map)
Definition: stl_bind.h:667
size_t len() override
Definition: stl_bind.h:668
iterator iter() override
Definition: stl_bind.h:669
bool contains(const object &) override
Definition: stl_bind.h:671
size_t len() override
Definition: stl_bind.h:678
ValuesViewImpl(Map &map)
Definition: stl_bind.h:677
iterator iter() override
Definition: stl_bind.h:679
Annotation for arguments.
Definition: cast.h:1238
Information record describing a Python buffer object.
Definition: buffer_info.h:43
static std::true_type test_value(typename T2::value_type *)
static constexpr const bool is_pair
Definition: stl_bind.h:41
static std::true_type test_comparable(decltype(std::declval< const T2 & >()==std::declval< const T2 & >()) *)
static constexpr const bool is_element
Definition: stl_bind.h:44
static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *)
static constexpr const bool is_vector
Definition: stl_bind.h:43
static std::false_type test_value(...)
static std::false_type test_comparable(...)
static std::false_type test_pair(...)
virtual iterator iter()=0
virtual ~items_view()=default
virtual size_t len()=0
Keep patient alive while nurse lives.
Definition: attr.h:69
virtual bool contains(const object &k)=0
virtual ~keys_view()=default
virtual bool contains(const KeyType &k)=0
virtual iterator iter()=0
virtual size_t len()=0
Annotation for function names.
Definition: attr.h:47
Annotation for parent scope.
Definition: attr.h:35
virtual ~values_view()=default
virtual size_t len()=0
virtual iterator iter()=0