stl_bind.h 28 KB

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