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) {
102  m.def("obj_class_name", [](py::handle obj) { return py::detail::obj_class_name(obj.ptr()); });
103 
105 
106  // test_bool
107  m.def("get_bool", [] { return py::bool_(false); });
108  // test_int
109  m.def("get_int", [] { return py::int_(0); });
110  // test_iterator
111  m.def("get_iterator", [] { return py::iterator(); });
112  // test_iterable
113  m.def("get_iterable", [] { return py::iterable(); });
114  m.def("get_frozenset_from_iterable",
115  [](const py::iterable &iter) { return py::frozenset(iter); });
116  m.def("get_list_from_iterable", [](const py::iterable &iter) { return py::list(iter); });
117  m.def("get_set_from_iterable", [](const py::iterable &iter) { return py::set(iter); });
118  m.def("get_tuple_from_iterable", [](const py::iterable &iter) { return py::tuple(iter); });
119  // test_float
120  m.def("get_float", [] { return py::float_(0.0f); });
121  // test_list
122  m.def("list_no_args", []() { return py::list{}; });
123  m.def("list_ssize_t", []() { return py::list{(py::ssize_t) 0}; });
124  m.def("list_size_t", []() { return py::list{(py::size_t) 0}; });
125  m.def("list_insert_ssize_t", [](py::list *l) { return l->insert((py::ssize_t) 1, 83); });
126  m.def("list_insert_size_t", [](py::list *l) { return l->insert((py::size_t) 3, 57); });
127  m.def("get_list", []() {
128  py::list list;
129  list.append("value");
130  py::print("Entry at position 0:", list[0]);
131  list[0] = py::str("overwritten");
132  list.insert(0, "inserted-0");
133  list.insert(2, "inserted-2");
134  return list;
135  });
136  m.def("print_list", [](const py::list &list) {
137  int index = 0;
138  for (auto item : list) {
139  py::print("list item {}: {}"_s.format(index++, item));
140  }
141  });
142  // test_none
143  m.def("get_none", [] { return py::none(); });
144  m.def("print_none", [](const py::none &none) { py::print("none: {}"_s.format(none)); });
145 
146  // test_set, test_frozenset
147  m.def("get_set", []() {
148  py::set set;
149  set.add(py::str("key1"));
150  set.add("key2");
151  set.add(std::string("key3"));
152  return set;
153  });
154  m.def("get_frozenset", []() {
155  py::set set;
156  set.add(py::str("key1"));
157  set.add("key2");
158  set.add(std::string("key3"));
159  return py::frozenset(set);
160  });
161  m.def("print_anyset", [](const py::anyset &set) {
162  for (auto item : set) {
163  py::print("key:", item);
164  }
165  });
166  m.def("anyset_size", [](const py::anyset &set) { return set.size(); });
167  m.def("anyset_empty", [](const py::anyset &set) { return set.empty(); });
168  m.def("anyset_contains",
169  [](const py::anyset &set, const py::object &key) { return set.contains(key); });
170  m.def("anyset_contains",
171  [](const py::anyset &set, const char *key) { return set.contains(key); });
172  m.def("set_add", [](py::set &set, const py::object &key) { set.add(key); });
173  m.def("set_clear", [](py::set &set) { set.clear(); });
174 
175  // test_dict
176  m.def("get_dict", []() { return py::dict("key"_a = "value"); });
177  m.def("print_dict", [](const py::dict &dict) {
178  for (auto item : dict) {
179  py::print("key: {}, value={}"_s.format(item.first, item.second));
180  }
181  });
182  m.def("dict_keyword_constructor", []() {
183  auto d1 = py::dict("x"_a = 1, "y"_a = 2);
184  auto d2 = py::dict("z"_a = 3, **d1);
185  return d2;
186  });
187  m.def("dict_contains",
188  [](const py::dict &dict, const py::object &val) { return dict.contains(val); });
189  m.def("dict_contains",
190  [](const py::dict &dict, const char *val) { return dict.contains(val); });
191 
192  // test_tuple
193  m.def("tuple_no_args", []() { return py::tuple{}; });
194  m.def("tuple_ssize_t", []() { return py::tuple{(py::ssize_t) 0}; });
195  m.def("tuple_size_t", []() { return py::tuple{(py::size_t) 0}; });
196  m.def("get_tuple", []() { return py::make_tuple(42, py::none(), "spam"); });
197 
198  // test_simple_namespace
199  m.def("get_simple_namespace", []() {
200  auto ns = py::module_::import("types").attr("SimpleNamespace")(
201  "attr"_a = 42, "x"_a = "foo", "wrong"_a = 1);
202  py::delattr(ns, "wrong");
203  py::setattr(ns, "right", py::int_(2));
204  return ns;
205  });
206 
207  // test_str
208  m.def("str_from_char_ssize_t", []() { return py::str{"red", (py::ssize_t) 3}; });
209  m.def("str_from_char_size_t", []() { return py::str{"blue", (py::size_t) 4}; });
210  m.def("str_from_string", []() { return py::str(std::string("baz")); });
211  m.def("str_from_std_string_input", [](const std::string &stri) { return py::str(stri); });
212  m.def("str_from_cstr_input", [](const char *c_str) { return py::str(c_str); });
213  m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
214  m.def("str_from_bytes_input",
215  [](const py::bytes &encoded_str) { return py::str(encoded_str); });
216 
217  m.def("str_from_object", [](const py::object &obj) { return py::str(obj); });
218  m.def("repr_from_object", [](const py::object &obj) { return py::repr(obj); });
219  m.def("str_from_handle", [](py::handle h) { return py::str(h); });
220  m.def("str_from_string_from_str",
221  [](const py::str &obj) { return py::str(static_cast<std::string>(obj)); });
222 
223  m.def("str_format", []() {
224  auto s1 = "{} + {} = {}"_s.format(1, 2, 3);
225  auto s2 = "{a} + {b} = {c}"_s.format("a"_a = 1, "b"_a = 2, "c"_a = 3);
226  return py::make_tuple(s1, s2);
227  });
228 
229  // test_bytes
230  m.def("bytes_from_char_ssize_t", []() { return py::bytes{"green", (py::ssize_t) 5}; });
231  m.def("bytes_from_char_size_t", []() { return py::bytes{"purple", (py::size_t) 6}; });
232  m.def("bytes_from_string", []() { return py::bytes(std::string("foo")); });
233  m.def("bytes_from_str", []() { return py::bytes(py::str("bar", 3)); });
234 
235  // test bytearray
236  m.def("bytearray_from_char_ssize_t", []() { return py::bytearray{"$%", (py::ssize_t) 2}; });
237  m.def("bytearray_from_char_size_t", []() { return py::bytearray{"@$!", (py::size_t) 3}; });
238  m.def("bytearray_from_string", []() { return py::bytearray(std::string("foo")); });
239  m.def("bytearray_size", []() { return py::bytearray("foo").size(); });
240 
241  // test_capsule
242  m.def("return_capsule_with_destructor", []() {
243  py::print("creating capsule");
244  return py::capsule([]() { py::print("destructing capsule"); });
245  });
246 
247  m.def("return_renamed_capsule_with_destructor", []() {
248  py::print("creating capsule");
249  auto cap = py::capsule([]() { py::print("destructing capsule"); });
250  static const char *capsule_name = "test_name1";
251  py::print("renaming capsule");
252  cap.set_name(capsule_name);
253  return cap;
254  });
255 
256  m.def("return_capsule_with_destructor_2", []() {
257  py::print("creating capsule");
258  return py::capsule((void *) 1234, [](void *ptr) {
259  py::print("destructing capsule: {}"_s.format((size_t) ptr));
260  });
261  });
262 
263  m.def("return_capsule_with_destructor_3", []() {
264  py::print("creating capsule");
265  auto cap = py::capsule((void *) 1233, "oname", [](void *ptr) {
266  py::print("destructing capsule: {}"_s.format((size_t) ptr));
267  });
268  py::print("original name: {}"_s.format(cap.name()));
269  return cap;
270  });
271 
272  m.def("return_renamed_capsule_with_destructor_2", []() {
273  py::print("creating capsule");
274  auto cap = py::capsule((void *) 1234, [](void *ptr) {
275  py::print("destructing capsule: {}"_s.format((size_t) ptr));
276  });
277  static const char *capsule_name = "test_name2";
278  py::print("renaming capsule");
279  cap.set_name(capsule_name);
280  return cap;
281  });
282 
283  m.def("return_capsule_with_name_and_destructor", []() {
284  auto capsule = py::capsule((void *) 12345, "pointer type description", [](PyObject *ptr) {
285  if (ptr) {
286  const auto *name = PyCapsule_GetName(ptr);
287  py::print("destructing capsule ({}, '{}')"_s.format(
288  (size_t) PyCapsule_GetPointer(ptr, name), name));
289  }
290  });
291 
292  capsule.set_pointer((void *) 1234);
293 
294  // Using get_pointer<T>()
295  void *contents1 = static_cast<void *>(capsule);
296  void *contents2 = capsule.get_pointer();
297  void *contents3 = capsule.get_pointer<void>();
298 
299  auto result1 = reinterpret_cast<size_t>(contents1);
300  auto result2 = reinterpret_cast<size_t>(contents2);
301  auto result3 = reinterpret_cast<size_t>(contents3);
302 
303  py::print(
304  "created capsule ({}, '{}')"_s.format(result1 & result2 & result3, capsule.name()));
305  return capsule;
306  });
307 
308  m.def("return_capsule_with_explicit_nullptr_dtor", []() {
309  py::print("creating capsule with explicit nullptr dtor");
310  return py::capsule(reinterpret_cast<void *>(1234),
311  static_cast<void (*)(void *)>(nullptr)); // PR #4221
312  });
313 
314  // test_accessors
315  m.def("accessor_api", [](const py::object &o) {
316  auto d = py::dict();
317 
318  d["basic_attr"] = o.attr("basic_attr");
319 
320  auto l = py::list();
321  for (auto item : o.attr("begin_end")) {
322  l.append(item);
323  }
324  d["begin_end"] = l;
325 
326  d["operator[object]"] = o.attr("d")["operator[object]"_s];
327  d["operator[char *]"] = o.attr("d")["operator[char *]"];
328 
329  d["attr(object)"] = o.attr("sub").attr("attr_obj");
330  d["attr(char *)"] = o.attr("sub").attr("attr_char");
331  try {
332  o.attr("sub").attr("missing").ptr();
333  } catch (const py::error_already_set &) {
334  d["missing_attr_ptr"] = "raised"_s;
335  }
336  try {
337  o.attr("missing").attr("doesn't matter");
338  } catch (const py::error_already_set &) {
339  d["missing_attr_chain"] = "raised"_s;
340  }
341 
342  d["is_none"] = o.attr("basic_attr").is_none();
343 
344  d["operator()"] = o.attr("func")(1);
345  d["operator*"] = o.attr("func")(*o.attr("begin_end"));
346 
347  // Test implicit conversion
348  py::list implicit_list = o.attr("begin_end");
349  d["implicit_list"] = implicit_list;
350  py::dict implicit_dict = o.attr("__dict__");
351  d["implicit_dict"] = implicit_dict;
352 
353  return d;
354  });
355 
356  m.def("tuple_accessor", [](const py::tuple &existing_t) {
357  try {
358  existing_t[0] = 1;
359  } catch (const py::error_already_set &) {
360  // --> Python system error
361  // Only new tuples (refcount == 1) are mutable
362  auto new_t = py::tuple(3);
363  for (size_t i = 0; i < new_t.size(); ++i) {
364  new_t[i] = i;
365  }
366  return new_t;
367  }
368  return py::tuple();
369  });
370 
371  m.def("accessor_assignment", []() {
372  auto l = py::list(1);
373  l[0] = 0;
374 
375  auto d = py::dict();
376  d["get"] = l[0];
377  auto var = l[0];
378  d["deferred_get"] = var;
379  l[0] = 1;
380  d["set"] = l[0];
381  var = 99; // this assignment should not overwrite l[0]
382  d["deferred_set"] = l[0];
383  d["var"] = var;
384 
385  return d;
386  });
387 
388  m.def("accessor_moves", []() { // See PR #3970
389  py::list return_list;
390 #ifdef PYBIND11_HANDLE_REF_DEBUG
391  py::int_ py_int_0(0);
392  py::int_ py_int_42(42);
393  py::str py_str_count("count");
394 
395  auto tup = py::make_tuple(0);
396 
397  py::sequence seq(tup);
398 
399  py::list lst;
400  lst.append(0);
401 
402 # define PYBIND11_LOCAL_DEF(...) \
403  { \
404  std::size_t inc_refs = py::handle::inc_ref_counter(); \
405  __VA_ARGS__; \
406  inc_refs = py::handle::inc_ref_counter() - inc_refs; \
407  return_list.append(inc_refs); \
408  }
409 
410  PYBIND11_LOCAL_DEF(tup[py_int_0]) // l-value (to have a control)
411  PYBIND11_LOCAL_DEF(tup[py::int_(0)]) // r-value
412 
413  PYBIND11_LOCAL_DEF(tup.attr(py_str_count)) // l-value
414  PYBIND11_LOCAL_DEF(tup.attr(py::str("count"))) // r-value
415 
416  PYBIND11_LOCAL_DEF(seq[py_int_0]) // l-value
417  PYBIND11_LOCAL_DEF(seq[py::int_(0)]) // r-value
418 
419  PYBIND11_LOCAL_DEF(seq.attr(py_str_count)) // l-value
420  PYBIND11_LOCAL_DEF(seq.attr(py::str("count"))) // r-value
421 
422  PYBIND11_LOCAL_DEF(lst[py_int_0]) // l-value
423  PYBIND11_LOCAL_DEF(lst[py::int_(0)]) // r-value
424 
425  PYBIND11_LOCAL_DEF(lst.attr(py_str_count)) // l-value
426  PYBIND11_LOCAL_DEF(lst.attr(py::str("count"))) // r-value
427 
428  auto lst_acc = lst[py::int_(0)];
429  lst_acc = py::int_(42); // Detaches lst_acc from lst.
430  PYBIND11_LOCAL_DEF(lst_acc = py_int_42) // l-value
431  PYBIND11_LOCAL_DEF(lst_acc = py::int_(42)) // r-value
432 # undef PYBIND11_LOCAL_DEF
433 #endif
434  return return_list;
435  });
436 
437  // test_constructors
438  m.def("default_constructors", []() {
439  return py::dict("bytes"_a = py::bytes(),
440  "bytearray"_a = py::bytearray(),
441  "str"_a = py::str(),
442  "bool"_a = py::bool_(),
443  "int"_a = py::int_(),
444  "float"_a = py::float_(),
445  "tuple"_a = py::tuple(),
446  "list"_a = py::list(),
447  "dict"_a = py::dict(),
448  "set"_a = py::set());
449  });
450 
451  m.def("converting_constructors", [](const py::dict &d) {
452  return py::dict("bytes"_a = py::bytes(d["bytes"]),
453  "bytearray"_a = py::bytearray(d["bytearray"]),
454  "str"_a = py::str(d["str"]),
455  "bool"_a = py::bool_(d["bool"]),
456  "int"_a = py::int_(d["int"]),
457  "float"_a = py::float_(d["float"]),
458  "tuple"_a = py::tuple(d["tuple"]),
459  "list"_a = py::list(d["list"]),
460  "dict"_a = py::dict(d["dict"]),
461  "set"_a = py::set(d["set"]),
462  "frozenset"_a = py::frozenset(d["frozenset"]),
463  "memoryview"_a = py::memoryview(d["memoryview"]));
464  });
465 
466  m.def("cast_functions", [](const py::dict &d) {
467  // When converting between Python types, obj.cast<T>() should be the same as T(obj)
468  return py::dict("bytes"_a = d["bytes"].cast<py::bytes>(),
469  "bytearray"_a = d["bytearray"].cast<py::bytearray>(),
470  "str"_a = d["str"].cast<py::str>(),
471  "bool"_a = d["bool"].cast<py::bool_>(),
472  "int"_a = d["int"].cast<py::int_>(),
473  "float"_a = d["float"].cast<py::float_>(),
474  "tuple"_a = d["tuple"].cast<py::tuple>(),
475  "list"_a = d["list"].cast<py::list>(),
476  "dict"_a = d["dict"].cast<py::dict>(),
477  "set"_a = d["set"].cast<py::set>(),
478  "frozenset"_a = d["frozenset"].cast<py::frozenset>(),
479  "memoryview"_a = d["memoryview"].cast<py::memoryview>());
480  });
481 
482  m.def("convert_to_pybind11_str", [](const py::object &o) { return py::str(o); });
483 
484  m.def("nonconverting_constructor",
485  [](const std::string &type, py::object value, bool move) -> py::object {
486  if (type == "bytes") {
487  return move ? py::bytes(std::move(value)) : py::bytes(value);
488  }
489  if (type == "none") {
490  return move ? py::none(std::move(value)) : py::none(value);
491  }
492  if (type == "ellipsis") {
493  return move ? py::ellipsis(std::move(value)) : py::ellipsis(value);
494  }
495  if (type == "type") {
496  return move ? py::type(std::move(value)) : py::type(value);
497  }
498  throw std::runtime_error("Invalid type");
499  });
500 
501  m.def("get_implicit_casting", []() {
502  py::dict d;
503  d["char*_i1"] = "abc";
504  const char *c2 = "abc";
505  d["char*_i2"] = c2;
506  d["char*_e"] = py::cast(c2);
507  d["char*_p"] = py::str(c2);
508 
509  d["int_i1"] = 42;
510  int i = 42;
511  d["int_i2"] = i;
512  i++;
513  d["int_e"] = py::cast(i);
514  i++;
515  d["int_p"] = py::int_(i);
516 
517  d["str_i1"] = std::string("str");
518  std::string s2("str1");
519  d["str_i2"] = s2;
520  s2[3] = '2';
521  d["str_e"] = py::cast(s2);
522  s2[3] = '3';
523  d["str_p"] = py::str(s2);
524 
525  py::list l(2);
526  l[0] = 3;
527  l[1] = py::cast(6);
528  l.append(9);
529  l.append(py::cast(12));
530  l.append(py::int_(15));
531 
532  return py::dict("d"_a = d, "l"_a = l);
533  });
534 
535  // test_print
536  m.def("print_function", []() {
537  py::print("Hello, World!");
538  py::print(1, 2.0, "three", true, std::string("-- multiple args"));
539  auto args = py::make_tuple("and", "a", "custom", "separator");
540  py::print("*args", *args, "sep"_a = "-");
541  py::print("no new line here", "end"_a = " -- ");
542  py::print("next print");
543 
544  auto py_stderr = py::module_::import("sys").attr("stderr");
545  py::print("this goes to stderr", "file"_a = py_stderr);
546 
547  py::print("flush", "flush"_a = true);
548 
549  py::print(
550  "{a} + {b} = {c}"_s.format("a"_a = "py::print", "b"_a = "str.format", "c"_a = "this"));
551  });
552 
553  m.def("print_failure", []() { py::print(42, UnregisteredType()); });
554 
555  m.def("hash_function", [](py::object obj) { return py::hash(std::move(obj)); });
556 
557  m.def("obj_contains",
558  [](py::object &obj, const py::object &key) { return obj.contains(key); });
559 
560  m.def("test_number_protocol", [](const py::object &a, const py::object &b) {
561  py::list l;
562  l.append(a.equal(b));
563  l.append(a.not_equal(b));
564  l.append(a < b);
565  l.append(a <= b);
566  l.append(a > b);
567  l.append(a >= b);
568  l.append(a + b);
569  l.append(a - b);
570  l.append(a * b);
571  l.append(a / b);
572  l.append(a | b);
573  l.append(a & b);
574  l.append(a ^ b);
575  l.append(a >> b);
576  l.append(a << b);
577  return l;
578  });
579 
580  m.def("test_list_slicing", [](const py::list &a) { return a[py::slice(0, -1, 2)]; });
581 
582  // See #2361
583  m.def("issue2361_str_implicit_copy_none", []() {
584  py::str is_this_none = py::none();
585  return is_this_none;
586  });
587  m.def("issue2361_dict_implicit_copy_none", []() {
588  py::dict is_this_none = py::none();
589  return is_this_none;
590  });
591 
592  m.def("test_memoryview_object", [](const py::buffer &b) { return py::memoryview(b); });
593 
594  m.def("test_memoryview_buffer_info",
595  [](const py::buffer &b) { return py::memoryview(b.request()); });
596 
597  m.def("test_memoryview_from_buffer", [](bool is_unsigned) {
598  static const int16_t si16[] = {3, 1, 4, 1, 5};
599  static const uint16_t ui16[] = {2, 7, 1, 8};
600  if (is_unsigned) {
601  return py::memoryview::from_buffer(ui16, {4}, {sizeof(uint16_t)});
602  }
603  return py::memoryview::from_buffer(si16, {5}, {sizeof(int16_t)});
604  });
605 
606  m.def("test_memoryview_from_buffer_nativeformat", []() {
607  static const char *format = "@i";
608  static const int32_t arr[] = {4, 7, 5};
609  return py::memoryview::from_buffer(arr, sizeof(int32_t), format, {3}, {sizeof(int32_t)});
610  });
611 
612  m.def("test_memoryview_from_buffer_empty_shape", []() {
613  static const char *buf = "";
614  return py::memoryview::from_buffer(buf, 1, "B", {}, {});
615  });
616 
617  m.def("test_memoryview_from_buffer_invalid_strides", []() {
618  static const char *buf = "\x02\x03\x04";
619  return py::memoryview::from_buffer(buf, 1, "B", {3}, {});
620  });
621 
622  m.def("test_memoryview_from_buffer_nullptr", []() {
623  return py::memoryview::from_buffer(static_cast<void *>(nullptr), 1, "B", {}, {});
624  });
625 
626  m.def("test_memoryview_from_memory", []() {
627  const char *buf = "\xff\xe1\xab\x37";
628  return py::memoryview::from_memory(buf, static_cast<py::ssize_t>(strlen(buf)));
629  });
630 
631  // test_builtin_functions
632  m.def("get_len", [](py::handle h) { return py::len(h); });
633 
634 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
635  m.attr("PYBIND11_STR_LEGACY_PERMISSIVE") = true;
636 #endif
637 
638  m.def("isinstance_pybind11_bytes",
639  [](py::object o) { return py::isinstance<py::bytes>(std::move(o)); });
640  m.def("isinstance_pybind11_str",
641  [](py::object o) { return py::isinstance<py::str>(std::move(o)); });
642 
643  m.def("pass_to_pybind11_bytes", [](py::bytes b) { return py::len(std::move(b)); });
644  m.def("pass_to_pybind11_str", [](py::str s) { return py::len(std::move(s)); });
645  m.def("pass_to_std_string", [](const std::string &s) { return s.size(); });
646 
647  // test_weakref
648  m.def("weakref_from_handle", [](py::handle h) { return py::weakref(h); });
649  m.def("weakref_from_handle_and_function",
650  [](py::handle h, py::function f) { return py::weakref(h, std::move(f)); });
651  m.def("weakref_from_object", [](const py::object &o) { return py::weakref(o); });
652  m.def("weakref_from_object_and_function",
653  [](py::object o, py::function f) { return py::weakref(std::move(o), std::move(f)); });
654 
655 // See PR #3263 for background (https://github.com/pybind/pybind11/pull/3263):
656 // pytypes.h could be changed to enforce the "most correct" user code below, by removing
657 // `const` from iterator `reference` using type aliases, but that will break existing
658 // user code.
659 #if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION)
660 // This is "most correct" and enforced on these platforms.
661 # define PYBIND11_AUTO_IT auto it
662 #else
663 // This works on many platforms and is (unfortunately) reflective of existing user code.
664 // NOLINTNEXTLINE(bugprone-macro-parentheses)
665 # define PYBIND11_AUTO_IT auto &it
666 #endif
667 
668  m.def("tuple_iterator", []() {
669  auto tup = py::make_tuple(5, 7);
670  int tup_sum = 0;
671  for (PYBIND11_AUTO_IT : tup) {
672  tup_sum += it.cast<int>();
673  }
674  return tup_sum;
675  });
676 
677  m.def("dict_iterator", []() {
678  py::dict dct;
679  dct[py::int_(3)] = 5;
680  dct[py::int_(7)] = 11;
681  int kv_sum = 0;
682  for (PYBIND11_AUTO_IT : dct) {
683  kv_sum += it.first.cast<int>() * 100 + it.second.cast<int>();
684  }
685  return kv_sum;
686  });
687 
688  m.def("passed_iterator", [](const py::iterator &py_it) {
689  int elem_sum = 0;
690  for (PYBIND11_AUTO_IT : py_it) {
691  elem_sum += it.cast<int>();
692  }
693  return elem_sum;
694  });
695 
696 #undef PYBIND11_AUTO_IT
697 
698  // Tests below this line are for pybind11 IMPLEMENTATION DETAILS:
699 
700  m.def("sequence_item_get_ssize_t", [](const py::object &o) {
702  });
703  m.def("sequence_item_set_ssize_t", [](const py::object &o) {
704  auto s = py::str{"peppa", 5};
706  });
707  m.def("sequence_item_get_size_t", [](const py::object &o) {
709  });
710  m.def("sequence_item_set_size_t", [](const py::object &o) {
711  auto s = py::str{"george", 6};
713  });
714  m.def("list_item_get_ssize_t", [](const py::object &o) {
716  });
717  m.def("list_item_set_ssize_t", [](const py::object &o) {
718  auto s = py::str{"rebecca", 7};
720  });
721  m.def("list_item_get_size_t", [](const py::object &o) {
723  });
724  m.def("list_item_set_size_t", [](const py::object &o) {
725  auto s = py::str{"richard", 7};
727  });
728  m.def("tuple_item_get_ssize_t", [](const py::object &o) {
730  });
731  m.def("tuple_item_set_ssize_t", []() {
732  auto s0 = py::str{"emely", 5};
733  auto s1 = py::str{"edmond", 6};
734  auto o = py::tuple{2};
737  return o;
738  });
739  m.def("tuple_item_get_size_t", [](const py::object &o) {
741  });
742  m.def("tuple_item_set_size_t", []() {
743  auto s0 = py::str{"candy", 5};
744  auto s1 = py::str{"cat", 3};
745  auto o = py::tuple{2};
748  return o;
749  });
750 
751  m.def("square_float_", [](const external::float_ &x) -> double {
752  double v = x.get_value();
753  return v * v;
754  });
755 
756  m.def("tuple_rvalue_getter", [](const py::tuple &tup) {
757  // tests accessing tuple object with rvalue int
758  for (size_t i = 0; i < tup.size(); i++) {
759  auto o = py::handle(tup[py::int_(i)]);
760  if (!o) {
761  throw py::value_error("tuple is malformed");
762  }
763  }
764  return tup;
765  });
766  m.def("list_rvalue_getter", [](const py::list &l) {
767  // tests accessing list with rvalue int
768  for (size_t i = 0; i < l.size(); i++) {
769  auto o = py::handle(l[py::int_(i)]);
770  if (!o) {
771  throw py::value_error("list is malformed");
772  }
773  }
774  return l;
775  });
776  m.def("populate_dict_rvalue", [](int population) {
777  auto d = py::dict();
778  for (int i = 0; i < population; i++) {
779  d[py::int_(i)] = py::int_(i);
780  }
781  return d;
782  });
783  m.def("populate_obj_str_attrs", [](py::object &o, int population) {
784  for (int i = 0; i < population; i++) {
785  o.attr(py::str(py::int_(i))) = py::str(py::int_(i));
786  }
787  return o;
788  });
789 
790  // testing immutable object augmented assignment: #issue 3812
791  m.def("inplace_append", [](py::object &a, const py::object &b) {
792  a += b;
793  return a;
794  });
795  m.def("inplace_subtract", [](py::object &a, const py::object &b) {
796  a -= b;
797  return a;
798  });
799  m.def("inplace_multiply", [](py::object &a, const py::object &b) {
800  a *= b;
801  return a;
802  });
803  m.def("inplace_divide", [](py::object &a, const py::object &b) {
804  a /= b;
805  return a;
806  });
807  m.def("inplace_or", [](py::object &a, const py::object &b) {
808  a |= b;
809  return a;
810  });
811  m.def("inplace_and", [](py::object &a, const py::object &b) {
812  a &= b;
813  return a;
814  });
815  m.def("inplace_lshift", [](py::object &a, const py::object &b) {
816  a <<= b;
817  return a;
818  });
819  m.def("inplace_rshift", [](py::object &a, const py::object &b) {
820  a >>= b;
821  return a;
822  });
823 }
Eigen::internal::print
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
Definition: NEON/PacketMath.h:3115
external::detail::conv
PyObject * conv(PyObject *o)
Definition: test_pytypes.cpp:18
name
Annotation for function names.
Definition: attr.h:51
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:905
int16_t
signed short int16_t
Definition: ms_stdint.h:81
format
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: openglsupport.cpp:226
gtsam.examples.DogLegOptimizerExample.type
type
Definition: DogLegOptimizerExample.py:111
ssize_t
Py_ssize_t ssize_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:475
s
RealScalar s
Definition: level1_cplx_impl.h:126
d
static const double d[K][N]
Definition: igam.h:11
b
Scalar * b
Definition: benchVecAdd.cpp:17
PYBIND11_OBJECT_CVT
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1373
x
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
Definition: gnuplot_common_settings.hh:12
ret
DenseIndex ret
Definition: level1_cplx_impl.h:44
capsule
Definition: pytypes.h:1909
UnregisteredType
Dummy type which is not exported anywhere – something to trigger a conversion error.
Definition: pybind11_tests.h:23
detail
Definition: testSerializationNonlinear.cpp:70
h
const double h
Definition: testSimpleHelicopter.cpp:19
external::detail::default_constructed
PyObject * default_constructed()
Definition: test_pytypes.cpp:31
hash
ssize_t hash(handle obj)
Definition: pytypes.h:917
external
Definition: test_pytypes.cpp:14
handle_from_move_only_type_with_operator_PyObject::from_const
bool from_const()
Definition: test_pytypes.cpp:88
dict
Definition: pytypes.h:2065
make_tuple
tuple make_tuple()
Definition: cast.h:1248
delattr
void delattr(handle obj, handle name)
Definition: pytypes.h:861
l
static const Line3 l(Rot3(), 1, 1)
external::detail::check
bool check(PyObject *o)
Definition: test_pytypes.cpp:16
handle_from_move_only_type_with_operator_PyObject
Definition: test_pytypes.cpp:66
m
Matrix3f m
Definition: AngleAxis_mimic_euler.cpp:1
handle_from_move_only_type_with_operator_PyObject::from_ncnst
bool from_ncnst()
Definition: test_pytypes.cpp:82
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:476
external::float_
Definition: test_pytypes.cpp:33
handle_from_move_only_type_with_operator_PyObject::operator_const::operator_const
operator_const()=default
key
const gtsam::Symbol key('X', 0)
set
void set(Container &c, Position position, const Value &value)
Definition: stdlist_overload.cpp:37
tree::f
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Definition: testExpression.cpp:218
test_docs.d2
d2
Definition: test_docs.py:29
a
ArrayXXi a
Definition: Array_initializer_list_23_cxx11.cpp:1
move
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
Definition: cast.h:1119
arr
py::array arr
Definition: test_numpy_array.cpp:77
dict::contains
bool contains(T &&key) const
Definition: pytypes.h:2086
pure_compile_tests_for_handle_from_PyObject_pointers
void pure_compile_tests_for_handle_from_PyObject_pointers()
Definition: test_pytypes.cpp:48
pybind11_tests.h
iter
iterator iter(handle obj)
Definition: pytypes.h:2428
args
Definition: pytypes.h:2163
c_str
const char * c_str(Args &&...args)
Definition: internals.h:599
uint16_t
unsigned short uint16_t
Definition: ms_stdint.h:84
c2
static double c2
Definition: airy.c:55
v
Array< int, Dynamic, 1 > v
Definition: Array_initializer_list_vector_cxx11.cpp:1
handle_from_move_only_type_with_operator_PyObject::operator_ncnst::operator_ncnst
operator_ncnst()=default
pybind11
Definition: wrap/pybind11/pybind11/__init__.py:1
handle_from_move_only_type_with_operator_PyObject::m_defs
void m_defs(py::module_ &m)
Definition: test_pytypes.cpp:94
int32_t
signed int int32_t
Definition: ms_stdint.h:82
TEST_SUBMODULE
TEST_SUBMODULE(pytypes, m)
Definition: test_pytypes.cpp:101
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2399
PYBIND11_AUTO_IT
#define PYBIND11_AUTO_IT
none
Definition: pytypes.h:1744
implicit_conversion_from_0_to_handle
Definition: test_pytypes.cpp:42
gtsam.examples.ShonanAveragingCLI.str
str
Definition: ShonanAveragingCLI.py:115
Eigen::seq
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)
Definition: ArithmeticSequence.h:234
get
Container::iterator get(Container &c, Position position)
Definition: stdlist_overload.cpp:29
handle_from_move_only_type_with_operator_PyObject::operator_const
Definition: test_pytypes.cpp:76
handle_from_move_only_type_with_operator_PyObject::operator_ncnst
Definition: test_pytypes.cpp:70
external::float_::get_value
double get_value() const
Definition: test_pytypes.cpp:38
test_callbacks.value
value
Definition: test_callbacks.py:158
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
obj_class_name
const char * obj_class_name(PyObject *obj)
Definition: pytypes.h:470
Eigen::internal::cast
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Definition: Eigen/src/Core/MathFunctions.h:460
repr
str repr(handle h)
Definition: pytypes.h:2420


gtsam
Author(s):
autogenerated on Tue Jun 25 2024 03:05:29