test_pytypes.cpp
Go to the documentation of this file.
1 /*
2  tests/test_pytypes.cpp -- Python type casters
3 
4  Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
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 #include "pybind11_tests.h"
11 
12 #include <utility>
13 
14 namespace external {
15 namespace detail {
16 bool check(PyObject *o) { return PyFloat_Check(o) != 0; }
17 
18 PyObject *conv(PyObject *o) {
19  PyObject *ret = nullptr;
20  if (PyLong_Check(o)) {
21  double v = PyLong_AsDouble(o);
22  if (!(v == -1.0 && PyErr_Occurred())) {
23  ret = PyFloat_FromDouble(v);
24  }
25  } else {
26  PyErr_SetString(PyExc_TypeError, "Unexpected type");
27  }
28  return ret;
29 }
30 
31 PyObject *default_constructed() { return PyFloat_FromDouble(0.0); }
32 } // namespace detail
33 class float_ : public py::object {
35 
36  float_() : py::object(external::detail::default_constructed(), stolen_t{}) {}
37 
38  double get_value() const { return PyFloat_AsDouble(this->ptr()); }
39 };
40 } // namespace external
41 
43 // Uncomment to trigger compiler error. Note: Before PR #4008 this used to compile successfully.
44 // void expected_to_trigger_compiler_error() { py::handle(0); }
45 } // namespace implicit_conversion_from_0_to_handle
46 
47 // Used to validate systematically that PR #4008 does/did NOT change the behavior.
49  {
50  PyObject *ptr = Py_None;
51  py::handle{ptr};
52  }
53  {
54  PyObject *const ptr = Py_None;
55  py::handle{ptr};
56  }
57  // Uncomment to trigger compiler errors.
58  // PyObject const * ptr = Py_None; py::handle{ptr};
59  // PyObject const *const ptr = Py_None; py::handle{ptr};
60  // PyObject volatile * ptr = Py_None; py::handle{ptr};
61  // PyObject volatile *const ptr = Py_None; py::handle{ptr};
62  // PyObject const volatile * ptr = Py_None; py::handle{ptr};
63  // PyObject const volatile *const ptr = Py_None; py::handle{ptr};
64 }
65 
67 
68 // Reduced from
69 // https://github.com/pytorch/pytorch/blob/279634f384662b7c3a9f8bf7ccc3a6afd2f05657/torch/csrc/utils/object_ptr.h
71  operator_ncnst() = default;
72  operator_ncnst(operator_ncnst &&) = default;
73  operator PyObject *() /* */ { return Py_None; } // NOLINT(google-explicit-constructor)
74 };
75 
77  operator_const() = default;
78  operator_const(operator_const &&) = default;
79  operator PyObject *() const { return Py_None; } // NOLINT(google-explicit-constructor)
80 };
81 
82 bool from_ncnst() {
83  operator_ncnst obj;
84  auto h = py::handle(obj); // Critical part of test: does this compile?
85  return h.ptr() == Py_None; // Just something.
86 }
87 
88 bool from_const() {
89  operator_const obj;
90  auto h = py::handle(obj); // Critical part of test: does this compile?
91  return h.ptr() == Py_None; // Just something.
92 }
93 
94 void m_defs(py::module_ &m) {
95  m.def("handle_from_move_only_type_with_operator_PyObject_ncnst", from_ncnst);
96  m.def("handle_from_move_only_type_with_operator_PyObject_const", from_const);
97 }
98 
99 } // namespace handle_from_move_only_type_with_operator_PyObject
100 
101 TEST_SUBMODULE(pytypes, m) {
103 
104  // test_bool
105  m.def("get_bool", [] { return py::bool_(false); });
106  // test_int
107  m.def("get_int", [] { return py::int_(0); });
108  // test_iterator
109  m.def("get_iterator", [] { return py::iterator(); });
110  // test_iterable
111  m.def("get_iterable", [] { return py::iterable(); });
112  // test_float
113  m.def("get_float", [] { return py::float_(0.0f); });
114  // test_list
115  m.def("list_no_args", []() { return py::list{}; });
116  m.def("list_ssize_t", []() { return py::list{(py::ssize_t) 0}; });
117  m.def("list_size_t", []() { return py::list{(py::size_t) 0}; });
118  m.def("list_insert_ssize_t", [](py::list *l) { return l->insert((py::ssize_t) 1, 83); });
119  m.def("list_insert_size_t", [](py::list *l) { return l->insert((py::size_t) 3, 57); });
120  m.def("get_list", []() {
121  py::list list;
122  list.append("value");
123  py::print("Entry at position 0:", list[0]);
124  list[0] = py::str("overwritten");
125  list.insert(0, "inserted-0");
126  list.insert(2, "inserted-2");
127  return list;
128  });
129  m.def("print_list", [](const py::list &list) {
130  int index = 0;
131  for (auto item : list) {
132  py::print("list item {}: {}"_s.format(index++, item));
133  }
134  });
135  // test_none
136  m.def("get_none", [] { return py::none(); });
137  m.def("print_none", [](const py::none &none) { py::print("none: {}"_s.format(none)); });
138 
139  // test_set, test_frozenset
140  m.def("get_set", []() {
141  py::set set;
142  set.add(py::str("key1"));
143  set.add("key2");
144  set.add(std::string("key3"));
145  return set;
146  });
147  m.def("get_frozenset", []() {
148  py::set set;
149  set.add(py::str("key1"));
150  set.add("key2");
151  set.add(std::string("key3"));
152  return py::frozenset(set);
153  });
154  m.def("print_anyset", [](const py::anyset &set) {
155  for (auto item : set) {
156  py::print("key:", item);
157  }
158  });
159  m.def("anyset_size", [](const py::anyset &set) { return set.size(); });
160  m.def("anyset_empty", [](const py::anyset &set) { return set.empty(); });
161  m.def("anyset_contains",
162  [](const py::anyset &set, const py::object &key) { return set.contains(key); });
163  m.def("anyset_contains",
164  [](const py::anyset &set, const char *key) { return set.contains(key); });
165  m.def("set_add", [](py::set &set, const py::object &key) { set.add(key); });
166  m.def("set_clear", [](py::set &set) { set.clear(); });
167 
168  // test_dict
169  m.def("get_dict", []() { return py::dict("key"_a = "value"); });
170  m.def("print_dict", [](const py::dict &dict) {
171  for (auto item : dict) {
172  py::print("key: {}, value={}"_s.format(item.first, item.second));
173  }
174  });
175  m.def("dict_keyword_constructor", []() {
176  auto d1 = py::dict("x"_a = 1, "y"_a = 2);
177  auto d2 = py::dict("z"_a = 3, **d1);
178  return d2;
179  });
180  m.def("dict_contains",
181  [](const py::dict &dict, py::object val) { return dict.contains(val); });
182  m.def("dict_contains",
183  [](const py::dict &dict, const char *val) { return dict.contains(val); });
184 
185  // test_tuple
186  m.def("tuple_no_args", []() { return py::tuple{}; });
187  m.def("tuple_ssize_t", []() { return py::tuple{(py::ssize_t) 0}; });
188  m.def("tuple_size_t", []() { return py::tuple{(py::size_t) 0}; });
189  m.def("get_tuple", []() { return py::make_tuple(42, py::none(), "spam"); });
190 
191  // test_simple_namespace
192  m.def("get_simple_namespace", []() {
193  auto ns = py::module_::import("types").attr("SimpleNamespace")(
194  "attr"_a = 42, "x"_a = "foo", "wrong"_a = 1);
195  py::delattr(ns, "wrong");
196  py::setattr(ns, "right", py::int_(2));
197  return ns;
198  });
199 
200  // test_str
201  m.def("str_from_char_ssize_t", []() { return py::str{"red", (py::ssize_t) 3}; });
202  m.def("str_from_char_size_t", []() { return py::str{"blue", (py::size_t) 4}; });
203  m.def("str_from_string", []() { return py::str(std::string("baz")); });
204  m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
205  m.def("str_from_object", [](const py::object &obj) { return py::str(obj); });
206  m.def("repr_from_object", [](const py::object &obj) { return py::repr(obj); });
207  m.def("str_from_handle", [](py::handle h) { return py::str(h); });
208  m.def("str_from_string_from_str",
209  [](const py::str &obj) { return py::str(static_cast<std::string>(obj)); });
210 
211  m.def("str_format", []() {
212  auto s1 = "{} + {} = {}"_s.format(1, 2, 3);
213  auto s2 = "{a} + {b} = {c}"_s.format("a"_a = 1, "b"_a = 2, "c"_a = 3);
214  return py::make_tuple(s1, s2);
215  });
216 
217  // test_bytes
218  m.def("bytes_from_char_ssize_t", []() { return py::bytes{"green", (py::ssize_t) 5}; });
219  m.def("bytes_from_char_size_t", []() { return py::bytes{"purple", (py::size_t) 6}; });
220  m.def("bytes_from_string", []() { return py::bytes(std::string("foo")); });
221  m.def("bytes_from_str", []() { return py::bytes(py::str("bar", 3)); });
222 
223  // test bytearray
224  m.def("bytearray_from_char_ssize_t", []() { return py::bytearray{"$%", (py::ssize_t) 2}; });
225  m.def("bytearray_from_char_size_t", []() { return py::bytearray{"@$!", (py::size_t) 3}; });
226  m.def("bytearray_from_string", []() { return py::bytearray(std::string("foo")); });
227  m.def("bytearray_size", []() { return py::bytearray("foo").size(); });
228 
229  // test_capsule
230  m.def("return_capsule_with_destructor", []() {
231  py::print("creating capsule");
232  return py::capsule([]() { py::print("destructing capsule"); });
233  });
234 
235  m.def("return_renamed_capsule_with_destructor", []() {
236  py::print("creating capsule");
237  auto cap = py::capsule([]() { py::print("destructing capsule"); });
238  static const char *capsule_name = "test_name1";
239  py::print("renaming capsule");
240  cap.set_name(capsule_name);
241  return cap;
242  });
243 
244  m.def("return_capsule_with_destructor_2", []() {
245  py::print("creating capsule");
246  return py::capsule((void *) 1234, [](void *ptr) {
247  py::print("destructing capsule: {}"_s.format((size_t) ptr));
248  });
249  });
250 
251  m.def("return_renamed_capsule_with_destructor_2", []() {
252  py::print("creating capsule");
253  auto cap = py::capsule((void *) 1234, [](void *ptr) {
254  py::print("destructing capsule: {}"_s.format((size_t) ptr));
255  });
256  static const char *capsule_name = "test_name2";
257  py::print("renaming capsule");
258  cap.set_name(capsule_name);
259  return cap;
260  });
261 
262  m.def("return_capsule_with_name_and_destructor", []() {
263  auto capsule = py::capsule((void *) 12345, "pointer type description", [](PyObject *ptr) {
264  if (ptr) {
265  const auto *name = PyCapsule_GetName(ptr);
266  py::print("destructing capsule ({}, '{}')"_s.format(
267  (size_t) PyCapsule_GetPointer(ptr, name), name));
268  }
269  });
270 
271  capsule.set_pointer((void *) 1234);
272 
273  // Using get_pointer<T>()
274  void *contents1 = static_cast<void *>(capsule);
275  void *contents2 = capsule.get_pointer();
276  void *contents3 = capsule.get_pointer<void>();
277 
278  auto result1 = reinterpret_cast<size_t>(contents1);
279  auto result2 = reinterpret_cast<size_t>(contents2);
280  auto result3 = reinterpret_cast<size_t>(contents3);
281 
282  py::print(
283  "created capsule ({}, '{}')"_s.format(result1 & result2 & result3, capsule.name()));
284  return capsule;
285  });
286 
287  // test_accessors
288  m.def("accessor_api", [](const py::object &o) {
289  auto d = py::dict();
290 
291  d["basic_attr"] = o.attr("basic_attr");
292 
293  auto l = py::list();
294  for (auto item : o.attr("begin_end")) {
295  l.append(item);
296  }
297  d["begin_end"] = l;
298 
299  d["operator[object]"] = o.attr("d")["operator[object]"_s];
300  d["operator[char *]"] = o.attr("d")["operator[char *]"];
301 
302  d["attr(object)"] = o.attr("sub").attr("attr_obj");
303  d["attr(char *)"] = o.attr("sub").attr("attr_char");
304  try {
305  o.attr("sub").attr("missing").ptr();
306  } catch (const py::error_already_set &) {
307  d["missing_attr_ptr"] = "raised"_s;
308  }
309  try {
310  o.attr("missing").attr("doesn't matter");
311  } catch (const py::error_already_set &) {
312  d["missing_attr_chain"] = "raised"_s;
313  }
314 
315  d["is_none"] = o.attr("basic_attr").is_none();
316 
317  d["operator()"] = o.attr("func")(1);
318  d["operator*"] = o.attr("func")(*o.attr("begin_end"));
319 
320  // Test implicit conversion
321  py::list implicit_list = o.attr("begin_end");
322  d["implicit_list"] = implicit_list;
323  py::dict implicit_dict = o.attr("__dict__");
324  d["implicit_dict"] = implicit_dict;
325 
326  return d;
327  });
328 
329  m.def("tuple_accessor", [](const py::tuple &existing_t) {
330  try {
331  existing_t[0] = 1;
332  } catch (const py::error_already_set &) {
333  // --> Python system error
334  // Only new tuples (refcount == 1) are mutable
335  auto new_t = py::tuple(3);
336  for (size_t i = 0; i < new_t.size(); ++i) {
337  new_t[i] = i;
338  }
339  return new_t;
340  }
341  return py::tuple();
342  });
343 
344  m.def("accessor_assignment", []() {
345  auto l = py::list(1);
346  l[0] = 0;
347 
348  auto d = py::dict();
349  d["get"] = l[0];
350  auto var = l[0];
351  d["deferred_get"] = var;
352  l[0] = 1;
353  d["set"] = l[0];
354  var = 99; // this assignment should not overwrite l[0]
355  d["deferred_set"] = l[0];
356  d["var"] = var;
357 
358  return d;
359  });
360 
361  m.def("accessor_moves", []() { // See PR #3970
362  py::list return_list;
363 #ifdef PYBIND11_HANDLE_REF_DEBUG
364  py::int_ py_int_0(0);
365  py::int_ py_int_42(42);
366  py::str py_str_count("count");
367 
368  auto tup = py::make_tuple(0);
369 
370  py::sequence seq(tup);
371 
372  py::list lst;
373  lst.append(0);
374 
375 # define PYBIND11_LOCAL_DEF(...) \
376  { \
377  std::size_t inc_refs = py::handle::inc_ref_counter(); \
378  __VA_ARGS__; \
379  inc_refs = py::handle::inc_ref_counter() - inc_refs; \
380  return_list.append(inc_refs); \
381  }
382 
383  PYBIND11_LOCAL_DEF(tup[py_int_0]) // l-value (to have a control)
384  PYBIND11_LOCAL_DEF(tup[py::int_(0)]) // r-value
385 
386  PYBIND11_LOCAL_DEF(tup.attr(py_str_count)) // l-value
387  PYBIND11_LOCAL_DEF(tup.attr(py::str("count"))) // r-value
388 
389  PYBIND11_LOCAL_DEF(seq[py_int_0]) // l-value
390  PYBIND11_LOCAL_DEF(seq[py::int_(0)]) // r-value
391 
392  PYBIND11_LOCAL_DEF(seq.attr(py_str_count)) // l-value
393  PYBIND11_LOCAL_DEF(seq.attr(py::str("count"))) // r-value
394 
395  PYBIND11_LOCAL_DEF(lst[py_int_0]) // l-value
396  PYBIND11_LOCAL_DEF(lst[py::int_(0)]) // r-value
397 
398  PYBIND11_LOCAL_DEF(lst.attr(py_str_count)) // l-value
399  PYBIND11_LOCAL_DEF(lst.attr(py::str("count"))) // r-value
400 
401  auto lst_acc = lst[py::int_(0)];
402  lst_acc = py::int_(42); // Detaches lst_acc from lst.
403  PYBIND11_LOCAL_DEF(lst_acc = py_int_42) // l-value
404  PYBIND11_LOCAL_DEF(lst_acc = py::int_(42)) // r-value
405 # undef PYBIND11_LOCAL_DEF
406 #endif
407  return return_list;
408  });
409 
410  // test_constructors
411  m.def("default_constructors", []() {
412  return py::dict("bytes"_a = py::bytes(),
413  "bytearray"_a = py::bytearray(),
414  "str"_a = py::str(),
415  "bool"_a = py::bool_(),
416  "int"_a = py::int_(),
417  "float"_a = py::float_(),
418  "tuple"_a = py::tuple(),
419  "list"_a = py::list(),
420  "dict"_a = py::dict(),
421  "set"_a = py::set());
422  });
423 
424  m.def("converting_constructors", [](const py::dict &d) {
425  return py::dict("bytes"_a = py::bytes(d["bytes"]),
426  "bytearray"_a = py::bytearray(d["bytearray"]),
427  "str"_a = py::str(d["str"]),
428  "bool"_a = py::bool_(d["bool"]),
429  "int"_a = py::int_(d["int"]),
430  "float"_a = py::float_(d["float"]),
431  "tuple"_a = py::tuple(d["tuple"]),
432  "list"_a = py::list(d["list"]),
433  "dict"_a = py::dict(d["dict"]),
434  "set"_a = py::set(d["set"]),
435  "frozenset"_a = py::frozenset(d["frozenset"]),
436  "memoryview"_a = py::memoryview(d["memoryview"]));
437  });
438 
439  m.def("cast_functions", [](const py::dict &d) {
440  // When converting between Python types, obj.cast<T>() should be the same as T(obj)
441  return py::dict("bytes"_a = d["bytes"].cast<py::bytes>(),
442  "bytearray"_a = d["bytearray"].cast<py::bytearray>(),
443  "str"_a = d["str"].cast<py::str>(),
444  "bool"_a = d["bool"].cast<py::bool_>(),
445  "int"_a = d["int"].cast<py::int_>(),
446  "float"_a = d["float"].cast<py::float_>(),
447  "tuple"_a = d["tuple"].cast<py::tuple>(),
448  "list"_a = d["list"].cast<py::list>(),
449  "dict"_a = d["dict"].cast<py::dict>(),
450  "set"_a = d["set"].cast<py::set>(),
451  "frozenset"_a = d["frozenset"].cast<py::frozenset>(),
452  "memoryview"_a = d["memoryview"].cast<py::memoryview>());
453  });
454 
455  m.def("convert_to_pybind11_str", [](const py::object &o) { return py::str(o); });
456 
457  m.def("nonconverting_constructor",
458  [](const std::string &type, py::object value, bool move) -> py::object {
459  if (type == "bytes") {
460  return move ? py::bytes(std::move(value)) : py::bytes(value);
461  }
462  if (type == "none") {
463  return move ? py::none(std::move(value)) : py::none(value);
464  }
465  if (type == "ellipsis") {
466  return move ? py::ellipsis(std::move(value)) : py::ellipsis(value);
467  }
468  if (type == "type") {
469  return move ? py::type(std::move(value)) : py::type(value);
470  }
471  throw std::runtime_error("Invalid type");
472  });
473 
474  m.def("get_implicit_casting", []() {
475  py::dict d;
476  d["char*_i1"] = "abc";
477  const char *c2 = "abc";
478  d["char*_i2"] = c2;
479  d["char*_e"] = py::cast(c2);
480  d["char*_p"] = py::str(c2);
481 
482  d["int_i1"] = 42;
483  int i = 42;
484  d["int_i2"] = i;
485  i++;
486  d["int_e"] = py::cast(i);
487  i++;
488  d["int_p"] = py::int_(i);
489 
490  d["str_i1"] = std::string("str");
491  std::string s2("str1");
492  d["str_i2"] = s2;
493  s2[3] = '2';
494  d["str_e"] = py::cast(s2);
495  s2[3] = '3';
496  d["str_p"] = py::str(s2);
497 
498  py::list l(2);
499  l[0] = 3;
500  l[1] = py::cast(6);
501  l.append(9);
502  l.append(py::cast(12));
503  l.append(py::int_(15));
504 
505  return py::dict("d"_a = d, "l"_a = l);
506  });
507 
508  // test_print
509  m.def("print_function", []() {
510  py::print("Hello, World!");
511  py::print(1, 2.0, "three", true, std::string("-- multiple args"));
512  auto args = py::make_tuple("and", "a", "custom", "separator");
513  py::print("*args", *args, "sep"_a = "-");
514  py::print("no new line here", "end"_a = " -- ");
515  py::print("next print");
516 
517  auto py_stderr = py::module_::import("sys").attr("stderr");
518  py::print("this goes to stderr", "file"_a = py_stderr);
519 
520  py::print("flush", "flush"_a = true);
521 
522  py::print(
523  "{a} + {b} = {c}"_s.format("a"_a = "py::print", "b"_a = "str.format", "c"_a = "this"));
524  });
525 
526  m.def("print_failure", []() { py::print(42, UnregisteredType()); });
527 
528  m.def("hash_function", [](py::object obj) { return py::hash(std::move(obj)); });
529 
530  m.def("test_number_protocol", [](const py::object &a, const py::object &b) {
531  py::list l;
532  l.append(a.equal(b));
533  l.append(a.not_equal(b));
534  l.append(a < b);
535  l.append(a <= b);
536  l.append(a > b);
537  l.append(a >= b);
538  l.append(a + b);
539  l.append(a - b);
540  l.append(a * b);
541  l.append(a / b);
542  l.append(a | b);
543  l.append(a & b);
544  l.append(a ^ b);
545  l.append(a >> b);
546  l.append(a << b);
547  return l;
548  });
549 
550  m.def("test_list_slicing", [](const py::list &a) { return a[py::slice(0, -1, 2)]; });
551 
552  // See #2361
553  m.def("issue2361_str_implicit_copy_none", []() {
554  py::str is_this_none = py::none();
555  return is_this_none;
556  });
557  m.def("issue2361_dict_implicit_copy_none", []() {
558  py::dict is_this_none = py::none();
559  return is_this_none;
560  });
561 
562  m.def("test_memoryview_object", [](const py::buffer &b) { return py::memoryview(b); });
563 
564  m.def("test_memoryview_buffer_info",
565  [](const py::buffer &b) { return py::memoryview(b.request()); });
566 
567  m.def("test_memoryview_from_buffer", [](bool is_unsigned) {
568  static const int16_t si16[] = {3, 1, 4, 1, 5};
569  static const uint16_t ui16[] = {2, 7, 1, 8};
570  if (is_unsigned) {
571  return py::memoryview::from_buffer(ui16, {4}, {sizeof(uint16_t)});
572  }
573  return py::memoryview::from_buffer(si16, {5}, {sizeof(int16_t)});
574  });
575 
576  m.def("test_memoryview_from_buffer_nativeformat", []() {
577  static const char *format = "@i";
578  static const int32_t arr[] = {4, 7, 5};
579  return py::memoryview::from_buffer(arr, sizeof(int32_t), format, {3}, {sizeof(int32_t)});
580  });
581 
582  m.def("test_memoryview_from_buffer_empty_shape", []() {
583  static const char *buf = "";
584  return py::memoryview::from_buffer(buf, 1, "B", {}, {});
585  });
586 
587  m.def("test_memoryview_from_buffer_invalid_strides", []() {
588  static const char *buf = "\x02\x03\x04";
589  return py::memoryview::from_buffer(buf, 1, "B", {3}, {});
590  });
591 
592  m.def("test_memoryview_from_buffer_nullptr", []() {
593  return py::memoryview::from_buffer(static_cast<void *>(nullptr), 1, "B", {}, {});
594  });
595 
596  m.def("test_memoryview_from_memory", []() {
597  const char *buf = "\xff\xe1\xab\x37";
598  return py::memoryview::from_memory(buf, static_cast<py::ssize_t>(strlen(buf)));
599  });
600 
601  // test_builtin_functions
602  m.def("get_len", [](py::handle h) { return py::len(h); });
603 
604 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
605  m.attr("PYBIND11_STR_LEGACY_PERMISSIVE") = true;
606 #endif
607 
608  m.def("isinstance_pybind11_bytes",
609  [](py::object o) { return py::isinstance<py::bytes>(std::move(o)); });
610  m.def("isinstance_pybind11_str",
611  [](py::object o) { return py::isinstance<py::str>(std::move(o)); });
612 
613  m.def("pass_to_pybind11_bytes", [](py::bytes b) { return py::len(std::move(b)); });
614  m.def("pass_to_pybind11_str", [](py::str s) { return py::len(std::move(s)); });
615  m.def("pass_to_std_string", [](const std::string &s) { return s.size(); });
616 
617  // test_weakref
618  m.def("weakref_from_handle", [](py::handle h) { return py::weakref(h); });
619  m.def("weakref_from_handle_and_function",
620  [](py::handle h, py::function f) { return py::weakref(h, std::move(f)); });
621  m.def("weakref_from_object", [](const py::object &o) { return py::weakref(o); });
622  m.def("weakref_from_object_and_function",
623  [](py::object o, py::function f) { return py::weakref(std::move(o), std::move(f)); });
624 
625 // See PR #3263 for background (https://github.com/pybind/pybind11/pull/3263):
626 // pytypes.h could be changed to enforce the "most correct" user code below, by removing
627 // `const` from iterator `reference` using type aliases, but that will break existing
628 // user code.
629 #if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION)
630 // This is "most correct" and enforced on these platforms.
631 # define PYBIND11_AUTO_IT auto it
632 #else
633 // This works on many platforms and is (unfortunately) reflective of existing user code.
634 // NOLINTNEXTLINE(bugprone-macro-parentheses)
635 # define PYBIND11_AUTO_IT auto &it
636 #endif
637 
638  m.def("tuple_iterator", []() {
639  auto tup = py::make_tuple(5, 7);
640  int tup_sum = 0;
641  for (PYBIND11_AUTO_IT : tup) {
642  tup_sum += it.cast<int>();
643  }
644  return tup_sum;
645  });
646 
647  m.def("dict_iterator", []() {
648  py::dict dct;
649  dct[py::int_(3)] = 5;
650  dct[py::int_(7)] = 11;
651  int kv_sum = 0;
652  for (PYBIND11_AUTO_IT : dct) {
653  kv_sum += it.first.cast<int>() * 100 + it.second.cast<int>();
654  }
655  return kv_sum;
656  });
657 
658  m.def("passed_iterator", [](const py::iterator &py_it) {
659  int elem_sum = 0;
660  for (PYBIND11_AUTO_IT : py_it) {
661  elem_sum += it.cast<int>();
662  }
663  return elem_sum;
664  });
665 
666 #undef PYBIND11_AUTO_IT
667 
668  // Tests below this line are for pybind11 IMPLEMENTATION DETAILS:
669 
670  m.def("sequence_item_get_ssize_t", [](const py::object &o) {
672  });
673  m.def("sequence_item_set_ssize_t", [](const py::object &o) {
674  auto s = py::str{"peppa", 5};
676  });
677  m.def("sequence_item_get_size_t", [](const py::object &o) {
679  });
680  m.def("sequence_item_set_size_t", [](const py::object &o) {
681  auto s = py::str{"george", 6};
683  });
684  m.def("list_item_get_ssize_t", [](const py::object &o) {
686  });
687  m.def("list_item_set_ssize_t", [](const py::object &o) {
688  auto s = py::str{"rebecca", 7};
690  });
691  m.def("list_item_get_size_t", [](const py::object &o) {
693  });
694  m.def("list_item_set_size_t", [](const py::object &o) {
695  auto s = py::str{"richard", 7};
697  });
698  m.def("tuple_item_get_ssize_t", [](const py::object &o) {
700  });
701  m.def("tuple_item_set_ssize_t", []() {
702  auto s0 = py::str{"emely", 5};
703  auto s1 = py::str{"edmond", 6};
704  auto o = py::tuple{2};
707  return o;
708  });
709  m.def("tuple_item_get_size_t", [](const py::object &o) {
711  });
712  m.def("tuple_item_set_size_t", []() {
713  auto s0 = py::str{"candy", 5};
714  auto s1 = py::str{"cat", 3};
715  auto o = py::tuple{2};
718  return o;
719  });
720 
721  m.def("square_float_", [](const external::float_ &x) -> double {
722  double v = x.get_value();
723  return v * v;
724  });
725 
726  m.def("tuple_rvalue_getter", [](const py::tuple &tup) {
727  // tests accessing tuple object with rvalue int
728  for (size_t i = 0; i < tup.size(); i++) {
729  auto o = py::handle(tup[py::int_(i)]);
730  if (!o) {
731  throw py::value_error("tuple is malformed");
732  }
733  }
734  return tup;
735  });
736  m.def("list_rvalue_getter", [](const py::list &l) {
737  // tests accessing list with rvalue int
738  for (size_t i = 0; i < l.size(); i++) {
739  auto o = py::handle(l[py::int_(i)]);
740  if (!o) {
741  throw py::value_error("list is malformed");
742  }
743  }
744  return l;
745  });
746  m.def("populate_dict_rvalue", [](int population) {
747  auto d = py::dict();
748  for (int i = 0; i < population; i++) {
749  d[py::int_(i)] = py::int_(i);
750  }
751  return d;
752  });
753  m.def("populate_obj_str_attrs", [](py::object &o, int population) {
754  for (int i = 0; i < population; i++) {
755  o.attr(py::str(py::int_(i))) = py::str(py::int_(i));
756  }
757  return o;
758  });
759 }
const gtsam::Symbol key('X', 0)
Matrix3f m
ssize_t hash(handle obj)
Definition: pytypes.h:792
Scalar * b
Definition: benchVecAdd.cpp:17
tuple make_tuple()
Definition: cast.h:1209
PyObject * conv(PyObject *o)
Definition: pytypes.h:2012
void pure_compile_tests_for_handle_from_PyObject_pointers()
unsigned short uint16_t
Definition: ms_stdint.h:84
py::array arr
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
PyObject * default_constructed()
bool check(PyObject *o)
signed short int16_t
Definition: ms_stdint.h:81
void delattr(handle obj, handle name)
Definition: pytypes.h:736
Definition: pytypes.h:1614
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1252
TEST_SUBMODULE(pytypes, m)
Dummy type which is not exported anywhere – something to trigger a conversion error.
#define PYBIND11_AUTO_IT
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1080
static const Line3 l(Rot3(), 1, 1)
double get_value() const
Array< int, Dynamic, 1 > v
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
signed int int32_t
Definition: ms_stdint.h:82
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
RealScalar s
void set(Container &c, Position position, const Value &value)
DenseIndex ret
internal::enable_if<!(symbolic::is_symbolic< FirstType >::value||symbolic::is_symbolic< LastType >::value), ArithmeticSequence< typename internal::cleanup_index_type< FirstType >::type, Index > >::type seq(FirstType f, LastType l)
const double h
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: pytypes.h:1924
Annotation for function names.
Definition: attr.h:48
str repr(handle h)
Definition: pytypes.h:2265
Container::iterator get(Container &c, Position position)
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2244
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:780


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:46