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/typing.h>
11 
12 #include "pybind11_tests.h"
13 
14 #include <utility>
15 
16 namespace external {
17 namespace detail {
18 bool check(PyObject *o) { return PyFloat_Check(o) != 0; }
19 
20 PyObject *conv(PyObject *o) {
21  PyObject *ret = nullptr;
22  if (PyLong_Check(o)) {
23  double v = PyLong_AsDouble(o);
24  if (!(v == -1.0 && PyErr_Occurred())) {
25  ret = PyFloat_FromDouble(v);
26  }
27  } else {
28  py::set_error(PyExc_TypeError, "Unexpected type");
29  }
30  return ret;
31 }
32 
33 PyObject *default_constructed() { return PyFloat_FromDouble(0.0); }
34 } // namespace detail
35 class float_ : public py::object {
37 
38  float_() : py::object(external::detail::default_constructed(), stolen_t{}) {}
39 
40  double get_value() const { return PyFloat_AsDouble(this->ptr()); }
41 };
42 } // namespace external
43 
44 namespace pybind11 {
45 namespace detail {
46 template <>
48  static constexpr auto name = const_name("float");
49 };
50 } // namespace detail
51 } // namespace pybind11
52 
54 // Uncomment to trigger compiler error. Note: Before PR #4008 this used to compile successfully.
55 // void expected_to_trigger_compiler_error() { py::handle(0); }
56 } // namespace implicit_conversion_from_0_to_handle
57 
58 // Used to validate systematically that PR #4008 does/did NOT change the behavior.
60  {
61  PyObject *ptr = Py_None;
62  py::handle{ptr};
63  }
64  {
65  PyObject *const ptr = Py_None;
66  py::handle{ptr};
67  }
68  // Uncomment to trigger compiler errors.
69  // PyObject const * ptr = Py_None; py::handle{ptr};
70  // PyObject const *const ptr = Py_None; py::handle{ptr};
71  // PyObject volatile * ptr = Py_None; py::handle{ptr};
72  // PyObject volatile *const ptr = Py_None; py::handle{ptr};
73  // PyObject const volatile * ptr = Py_None; py::handle{ptr};
74  // PyObject const volatile *const ptr = Py_None; py::handle{ptr};
75 }
76 
78 
79 // Reduced from
80 // https://github.com/pytorch/pytorch/blob/279634f384662b7c3a9f8bf7ccc3a6afd2f05657/torch/csrc/utils/object_ptr.h
82  operator_ncnst() = default;
83  operator_ncnst(operator_ncnst &&) = default;
84  operator PyObject *() /* */ { return Py_None; } // NOLINT(google-explicit-constructor)
85 };
86 
88  operator_const() = default;
89  operator_const(operator_const &&) = default;
90  operator PyObject *() const { return Py_None; } // NOLINT(google-explicit-constructor)
91 };
92 
93 bool from_ncnst() {
94  operator_ncnst obj;
95  auto h = py::handle(obj); // Critical part of test: does this compile?
96  return h.ptr() == Py_None; // Just something.
97 }
98 
99 bool from_const() {
100  operator_const obj;
101  auto h = py::handle(obj); // Critical part of test: does this compile?
102  return h.ptr() == Py_None; // Just something.
103 }
104 
105 void m_defs(py::module_ &m) {
106  m.def("handle_from_move_only_type_with_operator_PyObject_ncnst", from_ncnst);
107  m.def("handle_from_move_only_type_with_operator_PyObject_const", from_const);
108 }
109 
110 } // namespace handle_from_move_only_type_with_operator_PyObject
111 
112 #if defined(__cpp_nontype_template_parameter_class)
113 namespace literals {
114 enum Color { RED = 0, BLUE = 1 };
115 
116 typedef py::typing::Literal<"26",
117  "0x1A",
118  "\"hello world\"",
119  "b\"hello world\"",
120  "u\"hello world\"",
121  "True",
122  "Color.RED",
123  "None">
124  LiteralFoo;
125 } // namespace literals
126 namespace typevar {
127 typedef py::typing::TypeVar<"T"> TypeVarT;
128 typedef py::typing::TypeVar<"V"> TypeVarV;
129 } // namespace typevar
130 #endif
131 
132 TEST_SUBMODULE(pytypes, m) {
133  m.def("obj_class_name", [](py::handle obj) { return py::detail::obj_class_name(obj.ptr()); });
134 
136 
137  // test_bool
138  m.def("get_bool", [] { return py::bool_(false); });
139  // test_int
140  m.def("get_int", [] { return py::int_(0); });
141  // test_iterator
142  m.def("get_iterator", [] { return py::iterator(); });
143  // test_iterable
144  m.def("get_iterable", [] { return py::iterable(); });
145  m.def("get_frozenset_from_iterable",
146  [](const py::iterable &iter) { return py::frozenset(iter); });
147  m.def("get_list_from_iterable", [](const py::iterable &iter) { return py::list(iter); });
148  m.def("get_set_from_iterable", [](const py::iterable &iter) { return py::set(iter); });
149  m.def("get_tuple_from_iterable", [](const py::iterable &iter) { return py::tuple(iter); });
150  // test_float
151  m.def("get_float", [] { return py::float_(0.0f); });
152  // test_list
153  m.def("list_no_args", []() { return py::list{}; });
154  m.def("list_ssize_t", []() { return py::list{(py::ssize_t) 0}; });
155  m.def("list_size_t", []() { return py::list{(py::size_t) 0}; });
156  m.def("list_insert_ssize_t", [](py::list *l) { return l->insert((py::ssize_t) 1, 83); });
157  m.def("list_insert_size_t", [](py::list *l) { return l->insert((py::size_t) 3, 57); });
158  m.def("list_clear", [](py::list *l) { l->clear(); });
159  m.def("get_list", []() {
160  py::list list;
161  list.append("value");
162  py::print("Entry at position 0:", list[0]);
163  list[0] = py::str("overwritten");
164  list.insert(0, "inserted-0");
165  list.insert(2, "inserted-2");
166  return list;
167  });
168  m.def("print_list", [](const py::list &list) {
169  int index = 0;
170  for (auto item : list) {
171  py::print("list item {}: {}"_s.format(index++, item));
172  }
173  });
174  // test_none
175  m.def("get_none", [] { return py::none(); });
176  m.def("print_none", [](const py::none &none) { py::print("none: {}"_s.format(none)); });
177 
178  // test_set, test_frozenset
179  m.def("get_set", []() {
180  py::set set;
181  set.add(py::str("key1"));
182  set.add("key2");
183  set.add(std::string("key3"));
184  return set;
185  });
186  m.def("get_frozenset", []() {
187  py::set set;
188  set.add(py::str("key1"));
189  set.add("key2");
190  set.add(std::string("key3"));
191  return py::frozenset(set);
192  });
193  m.def("print_anyset", [](const py::anyset &set) {
194  for (auto item : set) {
195  py::print("key:", item);
196  }
197  });
198  m.def("anyset_size", [](const py::anyset &set) { return set.size(); });
199  m.def("anyset_empty", [](const py::anyset &set) { return set.empty(); });
200  m.def("anyset_contains",
201  [](const py::anyset &set, const py::object &key) { return set.contains(key); });
202  m.def("anyset_contains",
203  [](const py::anyset &set, const char *key) { return set.contains(key); });
204  m.def("set_add", [](py::set &set, const py::object &key) { set.add(key); });
205  m.def("set_clear", [](py::set &set) { set.clear(); });
206 
207  // test_dict
208  m.def("get_dict", []() { return py::dict("key"_a = "value"); });
209  m.def("print_dict", [](const py::dict &dict) {
210  for (auto item : dict) {
211  py::print("key: {}, value={}"_s.format(item.first, item.second));
212  }
213  });
214  m.def("dict_keyword_constructor", []() {
215  auto d1 = py::dict("x"_a = 1, "y"_a = 2);
216  auto d2 = py::dict("z"_a = 3, **d1);
217  return d2;
218  });
219  m.def("dict_contains",
220  [](const py::dict &dict, const py::object &val) { return dict.contains(val); });
221  m.def("dict_contains",
222  [](const py::dict &dict, const char *val) { return dict.contains(val); });
223 
224  // test_tuple
225  m.def("tuple_no_args", []() { return py::tuple{}; });
226  m.def("tuple_ssize_t", []() { return py::tuple{(py::ssize_t) 0}; });
227  m.def("tuple_size_t", []() { return py::tuple{(py::size_t) 0}; });
228  m.def("get_tuple", []() { return py::make_tuple(42, py::none(), "spam"); });
229 
230  // test_simple_namespace
231  m.def("get_simple_namespace", []() {
232  auto ns = py::module_::import("types").attr("SimpleNamespace")(
233  "attr"_a = 42, "x"_a = "foo", "wrong"_a = 1);
234  py::delattr(ns, "wrong");
235  py::setattr(ns, "right", py::int_(2));
236  return ns;
237  });
238 
239  // test_str
240  m.def("str_from_char_ssize_t", []() { return py::str{"red", (py::ssize_t) 3}; });
241  m.def("str_from_char_size_t", []() { return py::str{"blue", (py::size_t) 4}; });
242  m.def("str_from_string", []() { return py::str(std::string("baz")); });
243  m.def("str_from_std_string_input", [](const std::string &stri) { return py::str(stri); });
244  m.def("str_from_cstr_input", [](const char *c_str) { return py::str(c_str); });
245  m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
246  m.def("str_from_bytes_input",
247  [](const py::bytes &encoded_str) { return py::str(encoded_str); });
248 
249  m.def("str_from_object", [](const py::object &obj) { return py::str(obj); });
250  m.def("repr_from_object", [](const py::object &obj) { return py::repr(obj); });
251  m.def("str_from_handle", [](py::handle h) { return py::str(h); });
252  m.def("str_from_string_from_str",
253  [](const py::str &obj) { return py::str(static_cast<std::string>(obj)); });
254 
255  m.def("str_format", []() {
256  auto s1 = "{} + {} = {}"_s.format(1, 2, 3);
257  auto s2 = "{a} + {b} = {c}"_s.format("a"_a = 1, "b"_a = 2, "c"_a = 3);
258  return py::make_tuple(s1, s2);
259  });
260 
261  // test_bytes
262  m.def("bytes_from_char_ssize_t", []() { return py::bytes{"green", (py::ssize_t) 5}; });
263  m.def("bytes_from_char_size_t", []() { return py::bytes{"purple", (py::size_t) 6}; });
264  m.def("bytes_from_string", []() { return py::bytes(std::string("foo")); });
265  m.def("bytes_from_str", []() { return py::bytes(py::str("bar", 3)); });
266 
267  // test bytearray
268  m.def("bytearray_from_char_ssize_t", []() { return py::bytearray{"$%", (py::ssize_t) 2}; });
269  m.def("bytearray_from_char_size_t", []() { return py::bytearray{"@$!", (py::size_t) 3}; });
270  m.def("bytearray_from_string", []() { return py::bytearray(std::string("foo")); });
271  m.def("bytearray_size", []() { return py::bytearray("foo").size(); });
272 
273  // test_capsule
274  m.def("return_capsule_with_destructor", []() {
275  py::print("creating capsule");
276  return py::capsule([]() { py::print("destructing capsule"); });
277  });
278 
279  m.def("return_renamed_capsule_with_destructor", []() {
280  py::print("creating capsule");
281  auto cap = py::capsule([]() { py::print("destructing capsule"); });
282  static const char *capsule_name = "test_name1";
283  py::print("renaming capsule");
284  cap.set_name(capsule_name);
285  return cap;
286  });
287 
288  m.def("return_capsule_with_destructor_2", []() {
289  py::print("creating capsule");
290  return py::capsule((void *) 1234, [](void *ptr) {
291  py::print("destructing capsule: {}"_s.format((size_t) ptr));
292  });
293  });
294 
295  m.def("return_capsule_with_destructor_3", []() {
296  py::print("creating capsule");
297  auto cap = py::capsule((void *) 1233, "oname", [](void *ptr) {
298  py::print("destructing capsule: {}"_s.format((size_t) ptr));
299  });
300  py::print("original name: {}"_s.format(cap.name()));
301  return cap;
302  });
303 
304  m.def("return_renamed_capsule_with_destructor_2", []() {
305  py::print("creating capsule");
306  auto cap = py::capsule((void *) 1234, [](void *ptr) {
307  py::print("destructing capsule: {}"_s.format((size_t) ptr));
308  });
309  static const char *capsule_name = "test_name2";
310  py::print("renaming capsule");
311  cap.set_name(capsule_name);
312  return cap;
313  });
314 
315  m.def("return_capsule_with_name_and_destructor", []() {
316  auto capsule = py::capsule((void *) 12345, "pointer type description", [](PyObject *ptr) {
317  if (ptr) {
318  const auto *name = PyCapsule_GetName(ptr);
319  py::print("destructing capsule ({}, '{}')"_s.format(
320  (size_t) PyCapsule_GetPointer(ptr, name), name));
321  }
322  });
323 
324  capsule.set_pointer((void *) 1234);
325 
326  // Using get_pointer<T>()
327  void *contents1 = static_cast<void *>(capsule);
328  void *contents2 = capsule.get_pointer();
329  void *contents3 = capsule.get_pointer<void>();
330 
331  auto result1 = reinterpret_cast<size_t>(contents1);
332  auto result2 = reinterpret_cast<size_t>(contents2);
333  auto result3 = reinterpret_cast<size_t>(contents3);
334 
335  py::print(
336  "created capsule ({}, '{}')"_s.format(result1 & result2 & result3, capsule.name()));
337  return capsule;
338  });
339 
340  m.def("return_capsule_with_explicit_nullptr_dtor", []() {
341  py::print("creating capsule with explicit nullptr dtor");
342  return py::capsule(reinterpret_cast<void *>(1234),
343  static_cast<void (*)(void *)>(nullptr)); // PR #4221
344  });
345 
346  // test_accessors
347  m.def("accessor_api", [](const py::object &o) {
348  auto d = py::dict();
349 
350  d["basic_attr"] = o.attr("basic_attr");
351 
352  auto l = py::list();
353  for (auto item : o.attr("begin_end")) {
354  l.append(item);
355  }
356  d["begin_end"] = l;
357 
358  d["operator[object]"] = o.attr("d")["operator[object]"_s];
359  d["operator[char *]"] = o.attr("d")["operator[char *]"];
360 
361  d["attr(object)"] = o.attr("sub").attr("attr_obj");
362  d["attr(char *)"] = o.attr("sub").attr("attr_char");
363  try {
364  o.attr("sub").attr("missing").ptr();
365  } catch (const py::error_already_set &) {
366  d["missing_attr_ptr"] = "raised"_s;
367  }
368  try {
369  o.attr("missing").attr("doesn't matter");
370  } catch (const py::error_already_set &) {
371  d["missing_attr_chain"] = "raised"_s;
372  }
373 
374  d["is_none"] = o.attr("basic_attr").is_none();
375 
376  d["operator()"] = o.attr("func")(1);
377  d["operator*"] = o.attr("func")(*o.attr("begin_end"));
378 
379  // Test implicit conversion
380  py::list implicit_list = o.attr("begin_end");
381  d["implicit_list"] = implicit_list;
382  py::dict implicit_dict = o.attr("__dict__");
383  d["implicit_dict"] = implicit_dict;
384 
385  return d;
386  });
387 
388  m.def("tuple_accessor", [](const py::tuple &existing_t) {
389  try {
390  existing_t[0] = 1;
391  } catch (const py::error_already_set &) {
392  // --> Python system error
393  // Only new tuples (refcount == 1) are mutable
394  auto new_t = py::tuple(3);
395  for (size_t i = 0; i < new_t.size(); ++i) {
396  new_t[i] = i;
397  }
398  return new_t;
399  }
400  return py::tuple();
401  });
402 
403  m.def("accessor_assignment", []() {
404  auto l = py::list(1);
405  l[0] = 0;
406 
407  auto d = py::dict();
408  d["get"] = l[0];
409  auto var = l[0];
410  d["deferred_get"] = var;
411  l[0] = 1;
412  d["set"] = l[0];
413  var = 99; // this assignment should not overwrite l[0]
414  d["deferred_set"] = l[0];
415  d["var"] = var;
416 
417  return d;
418  });
419 
420  m.def("accessor_moves", []() { // See PR #3970
421  py::list return_list;
422 #ifdef PYBIND11_HANDLE_REF_DEBUG
423  py::int_ py_int_0(0);
424  py::int_ py_int_42(42);
425  py::str py_str_count("count");
426 
427  auto tup = py::make_tuple(0);
428 
429  py::sequence seq(tup);
430 
431  py::list lst;
432  lst.append(0);
433 
434 # define PYBIND11_LOCAL_DEF(...) \
435  { \
436  std::size_t inc_refs = py::handle::inc_ref_counter(); \
437  __VA_ARGS__; \
438  inc_refs = py::handle::inc_ref_counter() - inc_refs; \
439  return_list.append(inc_refs); \
440  }
441 
442  PYBIND11_LOCAL_DEF(tup[py_int_0]) // l-value (to have a control)
443  PYBIND11_LOCAL_DEF(tup[py::int_(0)]) // r-value
444 
445  PYBIND11_LOCAL_DEF(tup.attr(py_str_count)) // l-value
446  PYBIND11_LOCAL_DEF(tup.attr(py::str("count"))) // r-value
447 
448  PYBIND11_LOCAL_DEF(seq[py_int_0]) // l-value
449  PYBIND11_LOCAL_DEF(seq[py::int_(0)]) // r-value
450 
451  PYBIND11_LOCAL_DEF(seq.attr(py_str_count)) // l-value
452  PYBIND11_LOCAL_DEF(seq.attr(py::str("count"))) // r-value
453 
454  PYBIND11_LOCAL_DEF(lst[py_int_0]) // l-value
455  PYBIND11_LOCAL_DEF(lst[py::int_(0)]) // r-value
456 
457  PYBIND11_LOCAL_DEF(lst.attr(py_str_count)) // l-value
458  PYBIND11_LOCAL_DEF(lst.attr(py::str("count"))) // r-value
459 
460  auto lst_acc = lst[py::int_(0)];
461  lst_acc = py::int_(42); // Detaches lst_acc from lst.
462  PYBIND11_LOCAL_DEF(lst_acc = py_int_42) // l-value
463  PYBIND11_LOCAL_DEF(lst_acc = py::int_(42)) // r-value
464 # undef PYBIND11_LOCAL_DEF
465 #endif
466  return return_list;
467  });
468 
469  // test_constructors
470  m.def("default_constructors", []() {
471  return py::dict("bytes"_a = py::bytes(),
472  "bytearray"_a = py::bytearray(),
473  "str"_a = py::str(),
474  "bool"_a = py::bool_(),
475  "int"_a = py::int_(),
476  "float"_a = py::float_(),
477  "tuple"_a = py::tuple(),
478  "list"_a = py::list(),
479  "dict"_a = py::dict(),
480  "set"_a = py::set());
481  });
482 
483  m.def("converting_constructors", [](const py::dict &d) {
484  return py::dict("bytes"_a = py::bytes(d["bytes"]),
485  "bytearray"_a = py::bytearray(d["bytearray"]),
486  "str"_a = py::str(d["str"]),
487  "bool"_a = py::bool_(d["bool"]),
488  "int"_a = py::int_(d["int"]),
489  "float"_a = py::float_(d["float"]),
490  "tuple"_a = py::tuple(d["tuple"]),
491  "list"_a = py::list(d["list"]),
492  "dict"_a = py::dict(d["dict"]),
493  "set"_a = py::set(d["set"]),
494  "frozenset"_a = py::frozenset(d["frozenset"]),
495  "memoryview"_a = py::memoryview(d["memoryview"]));
496  });
497 
498  m.def("cast_functions", [](const py::dict &d) {
499  // When converting between Python types, obj.cast<T>() should be the same as T(obj)
500  return py::dict("bytes"_a = d["bytes"].cast<py::bytes>(),
501  "bytearray"_a = d["bytearray"].cast<py::bytearray>(),
502  "str"_a = d["str"].cast<py::str>(),
503  "bool"_a = d["bool"].cast<py::bool_>(),
504  "int"_a = d["int"].cast<py::int_>(),
505  "float"_a = d["float"].cast<py::float_>(),
506  "tuple"_a = d["tuple"].cast<py::tuple>(),
507  "list"_a = d["list"].cast<py::list>(),
508  "dict"_a = d["dict"].cast<py::dict>(),
509  "set"_a = d["set"].cast<py::set>(),
510  "frozenset"_a = d["frozenset"].cast<py::frozenset>(),
511  "memoryview"_a = d["memoryview"].cast<py::memoryview>());
512  });
513 
514  m.def("convert_to_pybind11_str", [](const py::object &o) { return py::str(o); });
515 
516  m.def("nonconverting_constructor",
517  [](const std::string &type, py::object value, bool move) -> py::object {
518  if (type == "bytes") {
519  return move ? py::bytes(std::move(value)) : py::bytes(value);
520  }
521  if (type == "none") {
522  return move ? py::none(std::move(value)) : py::none(value);
523  }
524  if (type == "ellipsis") {
525  return move ? py::ellipsis(std::move(value)) : py::ellipsis(value);
526  }
527  if (type == "type") {
528  return move ? py::type(std::move(value)) : py::type(value);
529  }
530  throw std::runtime_error("Invalid type");
531  });
532 
533  m.def("get_implicit_casting", []() {
534  py::dict d;
535  d["char*_i1"] = "abc";
536  const char *c2 = "abc";
537  d["char*_i2"] = c2;
538  d["char*_e"] = py::cast(c2);
539  d["char*_p"] = py::str(c2);
540 
541  d["int_i1"] = 42;
542  int i = 42;
543  d["int_i2"] = i;
544  i++;
545  d["int_e"] = py::cast(i);
546  i++;
547  d["int_p"] = py::int_(i);
548 
549  d["str_i1"] = std::string("str");
550  std::string s2("str1");
551  d["str_i2"] = s2;
552  s2[3] = '2';
553  d["str_e"] = py::cast(s2);
554  s2[3] = '3';
555  d["str_p"] = py::str(s2);
556 
557  py::list l(2);
558  l[0] = 3;
559  l[1] = py::cast(6);
560  l.append(9);
561  l.append(py::cast(12));
562  l.append(py::int_(15));
563 
564  return py::dict("d"_a = d, "l"_a = l);
565  });
566 
567  // test_print
568  m.def("print_function", []() {
569  py::print("Hello, World!");
570  py::print(1, 2.0, "three", true, std::string("-- multiple args"));
571  auto args = py::make_tuple("and", "a", "custom", "separator");
572  py::print("*args", *args, "sep"_a = "-");
573  py::print("no new line here", "end"_a = " -- ");
574  py::print("next print");
575 
576  auto py_stderr = py::module_::import("sys").attr("stderr");
577  py::print("this goes to stderr", "file"_a = py_stderr);
578 
579  py::print("flush", "flush"_a = true);
580 
581  py::print(
582  "{a} + {b} = {c}"_s.format("a"_a = "py::print", "b"_a = "str.format", "c"_a = "this"));
583  });
584 
585  m.def("print_failure", []() { py::print(42, UnregisteredType()); });
586 
587  m.def("hash_function", [](py::object obj) { return py::hash(std::move(obj)); });
588 
589  m.def("obj_contains",
590  [](py::object &obj, const py::object &key) { return obj.contains(key); });
591 
592  m.def("test_number_protocol", [](const py::object &a, const py::object &b) {
593  py::list l;
594  l.append(a.equal(b));
595  l.append(a.not_equal(b));
596  l.append(a < b);
597  l.append(a <= b);
598  l.append(a > b);
599  l.append(a >= b);
600  l.append(a + b);
601  l.append(a - b);
602  l.append(a * b);
603  l.append(a / b);
604  l.append(a | b);
605  l.append(a & b);
606  l.append(a ^ b);
607  l.append(a >> b);
608  l.append(a << b);
609  return l;
610  });
611 
612  m.def("test_list_slicing", [](const py::list &a) { return a[py::slice(0, -1, 2)]; });
613 
614  // See #2361
615  m.def("issue2361_str_implicit_copy_none", []() {
616  py::str is_this_none = py::none();
617  return is_this_none;
618  });
619  m.def("issue2361_dict_implicit_copy_none", []() {
620  py::dict is_this_none = py::none();
621  return is_this_none;
622  });
623 
624  m.def("test_memoryview_object", [](const py::buffer &b) { return py::memoryview(b); });
625 
626  m.def("test_memoryview_buffer_info",
627  [](const py::buffer &b) { return py::memoryview(b.request()); });
628 
629  m.def("test_memoryview_from_buffer", [](bool is_unsigned) {
630  static const int16_t si16[] = {3, 1, 4, 1, 5};
631  static const uint16_t ui16[] = {2, 7, 1, 8};
632  if (is_unsigned) {
633  return py::memoryview::from_buffer(ui16, {4}, {sizeof(uint16_t)});
634  }
635  return py::memoryview::from_buffer(si16, {5}, {sizeof(int16_t)});
636  });
637 
638  m.def("test_memoryview_from_buffer_nativeformat", []() {
639  static const char *format = "@i";
640  static const int32_t arr[] = {4, 7, 5};
641  return py::memoryview::from_buffer(arr, sizeof(int32_t), format, {3}, {sizeof(int32_t)});
642  });
643 
644  m.def("test_memoryview_from_buffer_empty_shape", []() {
645  static const char *buf = "";
646  return py::memoryview::from_buffer(buf, 1, "B", {}, {});
647  });
648 
649  m.def("test_memoryview_from_buffer_invalid_strides", []() {
650  static const char *buf = "\x02\x03\x04";
651  return py::memoryview::from_buffer(buf, 1, "B", {3}, {});
652  });
653 
654  m.def("test_memoryview_from_buffer_nullptr", []() {
655  return py::memoryview::from_buffer(static_cast<void *>(nullptr), 1, "B", {}, {});
656  });
657 
658  m.def("test_memoryview_from_memory", []() {
659  const char *buf = "\xff\xe1\xab\x37";
660  return py::memoryview::from_memory(buf, static_cast<py::ssize_t>(strlen(buf)));
661  });
662 
663  // test_builtin_functions
664  m.def("get_len", [](py::handle h) { return py::len(h); });
665 
666 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
667  m.attr("PYBIND11_STR_LEGACY_PERMISSIVE") = true;
668 #endif
669 
670  m.def("isinstance_pybind11_bytes",
671  [](py::object o) { return py::isinstance<py::bytes>(std::move(o)); });
672  m.def("isinstance_pybind11_str",
673  [](py::object o) { return py::isinstance<py::str>(std::move(o)); });
674 
675  m.def("pass_to_pybind11_bytes", [](py::bytes b) { return py::len(std::move(b)); });
676  m.def("pass_to_pybind11_str", [](py::str s) { return py::len(std::move(s)); });
677  m.def("pass_to_std_string", [](const std::string &s) { return s.size(); });
678 
679  // test_weakref
680  m.def("weakref_from_handle", [](py::handle h) { return py::weakref(h); });
681  m.def("weakref_from_handle_and_function",
682  [](py::handle h, py::function f) { return py::weakref(h, std::move(f)); });
683  m.def("weakref_from_object", [](const py::object &o) { return py::weakref(o); });
684  m.def("weakref_from_object_and_function",
685  [](py::object o, py::function f) { return py::weakref(std::move(o), std::move(f)); });
686 
687 // See PR #3263 for background (https://github.com/pybind/pybind11/pull/3263):
688 // pytypes.h could be changed to enforce the "most correct" user code below, by removing
689 // `const` from iterator `reference` using type aliases, but that will break existing
690 // user code.
691 #if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION)
692 // This is "most correct" and enforced on these platforms.
693 # define PYBIND11_AUTO_IT auto it
694 #else
695  // This works on many platforms and is (unfortunately) reflective of existing user code.
696  // NOLINTNEXTLINE(bugprone-macro-parentheses)
697 # define PYBIND11_AUTO_IT auto &it
698 #endif
699 
700  m.def("tuple_iterator", []() {
701  auto tup = py::make_tuple(5, 7);
702  int tup_sum = 0;
703  for (PYBIND11_AUTO_IT : tup) {
704  tup_sum += it.cast<int>();
705  }
706  return tup_sum;
707  });
708 
709  m.def("dict_iterator", []() {
710  py::dict dct;
711  dct[py::int_(3)] = 5;
712  dct[py::int_(7)] = 11;
713  int kv_sum = 0;
714  for (PYBIND11_AUTO_IT : dct) {
715  kv_sum += it.first.cast<int>() * 100 + it.second.cast<int>();
716  }
717  return kv_sum;
718  });
719 
720  m.def("passed_iterator", [](const py::iterator &py_it) {
721  int elem_sum = 0;
722  for (PYBIND11_AUTO_IT : py_it) {
723  elem_sum += it.cast<int>();
724  }
725  return elem_sum;
726  });
727 
728 #undef PYBIND11_AUTO_IT
729 
730  // Tests below this line are for pybind11 IMPLEMENTATION DETAILS:
731 
732  m.def("sequence_item_get_ssize_t", [](const py::object &o) {
734  });
735  m.def("sequence_item_set_ssize_t", [](const py::object &o) {
736  auto s = py::str{"peppa", 5};
738  });
739  m.def("sequence_item_get_size_t", [](const py::object &o) {
741  });
742  m.def("sequence_item_set_size_t", [](const py::object &o) {
743  auto s = py::str{"george", 6};
745  });
746  m.def("list_item_get_ssize_t", [](const py::object &o) {
748  });
749  m.def("list_item_set_ssize_t", [](const py::object &o) {
750  auto s = py::str{"rebecca", 7};
752  });
753  m.def("list_item_get_size_t", [](const py::object &o) {
755  });
756  m.def("list_item_set_size_t", [](const py::object &o) {
757  auto s = py::str{"richard", 7};
759  });
760  m.def("tuple_item_get_ssize_t", [](const py::object &o) {
762  });
763  m.def("tuple_item_set_ssize_t", []() {
764  auto s0 = py::str{"emely", 5};
765  auto s1 = py::str{"edmond", 6};
766  auto o = py::tuple{2};
769  return o;
770  });
771  m.def("tuple_item_get_size_t", [](const py::object &o) {
773  });
774  m.def("tuple_item_set_size_t", []() {
775  auto s0 = py::str{"candy", 5};
776  auto s1 = py::str{"cat", 3};
777  auto o = py::tuple{2};
780  return o;
781  });
782 
783  m.def("square_float_", [](const external::float_ &x) -> double {
784  double v = x.get_value();
785  return v * v;
786  });
787 
788  m.def("tuple_rvalue_getter", [](const py::tuple &tup) {
789  // tests accessing tuple object with rvalue int
790  for (size_t i = 0; i < tup.size(); i++) {
791  auto o = py::handle(tup[py::int_(i)]);
792  if (!o) {
793  throw py::value_error("tuple is malformed");
794  }
795  }
796  return tup;
797  });
798  m.def("list_rvalue_getter", [](const py::list &l) {
799  // tests accessing list with rvalue int
800  for (size_t i = 0; i < l.size(); i++) {
801  auto o = py::handle(l[py::int_(i)]);
802  if (!o) {
803  throw py::value_error("list is malformed");
804  }
805  }
806  return l;
807  });
808  m.def("populate_dict_rvalue", [](int population) {
809  auto d = py::dict();
810  for (int i = 0; i < population; i++) {
811  d[py::int_(i)] = py::int_(i);
812  }
813  return d;
814  });
815  m.def("populate_obj_str_attrs", [](py::object &o, int population) {
816  for (int i = 0; i < population; i++) {
817  o.attr(py::str(py::int_(i))) = py::str(py::int_(i));
818  }
819  return o;
820  });
821 
822  // testing immutable object augmented assignment: #issue 3812
823  m.def("inplace_append", [](py::object &a, const py::object &b) {
824  a += b;
825  return a;
826  });
827  m.def("inplace_subtract", [](py::object &a, const py::object &b) {
828  a -= b;
829  return a;
830  });
831  m.def("inplace_multiply", [](py::object &a, const py::object &b) {
832  a *= b;
833  return a;
834  });
835  m.def("inplace_divide", [](py::object &a, const py::object &b) {
836  a /= b;
837  return a;
838  });
839  m.def("inplace_or", [](py::object &a, const py::object &b) {
840  a |= b;
841  return a;
842  });
843  m.def("inplace_and", [](py::object &a, const py::object &b) {
844  a &= b;
845  return a;
846  });
847  m.def("inplace_lshift", [](py::object &a, const py::object &b) {
848  a <<= b;
849  return a;
850  });
851  m.def("inplace_rshift", [](py::object &a, const py::object &b) {
852  a >>= b;
853  return a;
854  });
855 
856  m.def("annotate_tuple_float_str", [](const py::typing::Tuple<py::float_, py::str> &) {});
857  m.def("annotate_tuple_empty", [](const py::typing::Tuple<> &) {});
858  m.def("annotate_tuple_variable_length",
859  [](const py::typing::Tuple<py::float_, py::ellipsis> &) {});
860  m.def("annotate_dict_str_int", [](const py::typing::Dict<py::str, int> &) {});
861  m.def("annotate_list_int", [](const py::typing::List<int> &) {});
862  m.def("annotate_set_str", [](const py::typing::Set<std::string> &) {});
863  m.def("annotate_iterable_str", [](const py::typing::Iterable<std::string> &) {});
864  m.def("annotate_iterator_int", [](const py::typing::Iterator<int> &) {});
865  m.def("annotate_fn",
866  [](const py::typing::Callable<int(py::typing::List<py::str>, py::str)> &) {});
867 
868  m.def("annotate_fn_only_return", [](const py::typing::Callable<int(py::ellipsis)> &) {});
869  m.def("annotate_type", [](const py::typing::Type<int> &t) -> py::type { return t; });
870 
871  m.def("annotate_union",
872  [](py::typing::List<py::typing::Union<py::str, py::int_, py::object>> l,
873  py::str a,
874  py::int_ b,
875  py::object c) -> py::typing::List<py::typing::Union<py::str, py::int_, py::object>> {
876  l.append(a);
877  l.append(b);
878  l.append(c);
879  return l;
880  });
881 
882  m.def("union_typing_only",
883  [](py::typing::List<py::typing::Union<py::str>> &l)
884  -> py::typing::List<py::typing::Union<py::int_>> { return l; });
885 
886  m.def("annotate_union_to_object",
887  [](py::typing::Union<int, py::str> &o) -> py::object { return o; });
888 
889  m.def("annotate_optional",
890  [](py::list &list) -> py::typing::List<py::typing::Optional<py::str>> {
891  list.append(py::str("hi"));
892  list.append(py::none());
893  return list;
894  });
895 
896  m.def("annotate_type_guard", [](py::object &o) -> py::typing::TypeGuard<py::str> {
897  return py::isinstance<py::str>(o);
898  });
899  m.def("annotate_type_is",
900  [](py::object &o) -> py::typing::TypeIs<py::str> { return py::isinstance<py::str>(o); });
901 
902  m.def("annotate_no_return", []() -> py::typing::NoReturn { throw 0; });
903  m.def("annotate_never", []() -> py::typing::Never { throw 0; });
904 
905  m.def("annotate_optional_to_object",
906  [](py::typing::Optional<int> &o) -> py::object { return o; });
907 
908 #if defined(__cpp_nontype_template_parameter_class)
909  py::enum_<literals::Color>(m, "Color")
910  .value("RED", literals::Color::RED)
911  .value("BLUE", literals::Color::BLUE);
912 
913  m.def("annotate_literal", [](literals::LiteralFoo &o) -> py::object { return o; });
914  m.def("annotate_generic_containers",
915  [](const py::typing::List<typevar::TypeVarT> &l) -> py::typing::List<typevar::TypeVarV> {
916  return l;
917  });
918 
919  m.def("annotate_listT_to_T",
920  [](const py::typing::List<typevar::TypeVarT> &l) -> typevar::TypeVarT { return l[0]; });
921  m.def("annotate_object_to_T", [](const py::object &o) -> typevar::TypeVarT { return o; });
922  m.attr("if_defined__cpp_nontype_template_parameter_class") = true;
923 #else
924  m.attr("if_defined__cpp_nontype_template_parameter_class") = false;
925 #endif
926 }
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:20
name
Annotation for function names.
Definition: attr.h:51
setattr
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:922
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:489
s
RealScalar s
Definition: level1_cplx_impl.h:126
const_name
constexpr descr< N - 1 > const_name(char const (&text)[N])
Definition: descr.h:60
d
static const double d[K][N]
Definition: igam.h:11
c
Scalar Scalar * c
Definition: benchVecAdd.cpp:17
b
Scalar * b
Definition: benchVecAdd.cpp:17
PYBIND11_OBJECT_CVT
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
Definition: pytypes.h:1407
literals
Definition: cast.h:1511
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:1951
UnregisteredType
Dummy type which is not exported anywhere – something to trigger a conversion error.
Definition: pybind11_tests.h:25
detail
Definition: testSerializationNonlinear.cpp:70
h
const double h
Definition: testSimpleHelicopter.cpp:19
external::detail::default_constructed
PyObject * default_constructed()
Definition: test_pytypes.cpp:33
hash
ssize_t hash(handle obj)
Definition: pytypes.h:934
external
Definition: test_pytypes.cpp:16
handle_from_move_only_type_with_operator_PyObject::from_const
bool from_const()
Definition: test_pytypes.cpp:99
dict
Definition: pytypes.h:2107
make_tuple
tuple make_tuple()
Definition: cast.h:1383
delattr
void delattr(handle obj, handle name)
Definition: pytypes.h:878
l
static const Line3 l(Rot3(), 1, 1)
external::detail::check
bool check(PyObject *o)
Definition: test_pytypes.cpp:18
handle_from_move_only_type_with_operator_PyObject
Definition: test_pytypes.cpp:77
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:93
size_t
std::size_t size_t
Definition: wrap/pybind11/include/pybind11/detail/common.h:490
set_error
void set_error(const handle &type, const char *message)
Definition: pytypes.h:346
external::float_
Definition: test_pytypes.cpp:35
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:1243
arr
py::array arr
Definition: test_numpy_array.cpp:77
dict::contains
bool contains(T &&key) const
Definition: pytypes.h:2128
handle_type_name
Definition: cast.h:894
pure_compile_tests_for_handle_from_PyObject_pointers
void pure_compile_tests_for_handle_from_PyObject_pointers()
Definition: test_pytypes.cpp:59
Color
Vector4f Color
Definition: gpuhelper.h:19
pybind11_tests.h
iter
iterator iter(handle obj)
Definition: pytypes.h:2475
args
Definition: pytypes.h:2210
c_str
const char * c_str(Args &&...args)
Definition: internals.h:684
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
float_
Definition: pytypes.h:1870
typing.h
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:105
int32_t
signed int int32_t
Definition: ms_stdint.h:82
TEST_SUBMODULE
TEST_SUBMODULE(pytypes, m)
Definition: test_pytypes.cpp:132
len
size_t len(handle h)
Get the length of a Python object.
Definition: pytypes.h:2446
PYBIND11_AUTO_IT
#define PYBIND11_AUTO_IT
none
Definition: pytypes.h:1786
align_3::t
Point2 t(10, 10)
implicit_conversion_from_0_to_handle
Definition: test_pytypes.cpp:53
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:87
handle_from_move_only_type_with_operator_PyObject::operator_ncnst
Definition: test_pytypes.cpp:81
external::float_::get_value
double get_value() const
Definition: test_pytypes.cpp:40
test_callbacks.value
value
Definition: test_callbacks.py:160
i
int i
Definition: BiCGSTAB_step_by_step.cpp:9
obj_class_name
const char * obj_class_name(PyObject *obj)
Definition: pytypes.h:487
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:2467


gtsam
Author(s):
autogenerated on Sat Nov 16 2024 04:07:05