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


gtsam
Author(s):
autogenerated on Wed Mar 19 2025 03:06:17