16 bool check(PyObject *o) {
return PyFloat_Check(o) != 0; }
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);
26 PyErr_SetString(PyExc_TypeError,
"Unexpected type");
38 double get_value()
const {
return PyFloat_AsDouble(this->ptr()); }
50 PyObject *ptr = Py_None;
54 PyObject *
const ptr = Py_None;
73 operator PyObject *() {
return Py_None; }
79 operator PyObject *()
const {
return Py_None; }
84 auto h = py::handle(obj);
85 return h.ptr() == Py_None;
90 auto h = py::handle(obj);
91 return h.ptr() == Py_None;
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);
107 m.def(
"get_bool", [] {
return py::bool_(
false); });
109 m.def(
"get_int", [] {
return py::int_(0); });
111 m.def(
"get_iterator", [] {
return py::iterator(); });
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); });
120 m.def(
"get_float", [] {
return py::float_(0.0
f); });
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", []() {
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");
136 m.def(
"print_list", [](
const py::list &list) {
138 for (
auto item : list) {
139 py::print(
"list item {}: {}"_s.format(index++, item));
143 m.def(
"get_none", [] {
return py::none(); });
144 m.def(
"print_none", [](
const py::none &
none) {
py::print(
"none: {}"_s.format(
none)); });
147 m.def(
"get_set", []() {
151 set.add(std::string(
"key3"));
154 m.def(
"get_frozenset", []() {
158 set.add(std::string(
"key3"));
159 return py::frozenset(
set);
161 m.def(
"print_anyset", [](
const py::anyset &
set) {
162 for (
auto item :
set) {
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); });
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));
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);
187 m.def(
"dict_contains",
188 [](
const py::dict &
dict,
const py::object &val) {
return dict.
contains(val); });
189 m.def(
"dict_contains",
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"); });
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);
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); });
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); });
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)); });
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);
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)); });
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(); });
242 m.def(
"return_capsule_with_destructor", []() {
244 return py::capsule([]() {
py::print(
"destructing capsule"); });
247 m.def(
"return_renamed_capsule_with_destructor", []() {
249 auto cap = py::capsule([]() {
py::print(
"destructing capsule"); });
250 static const char *capsule_name =
"test_name1";
252 cap.set_name(capsule_name);
256 m.def(
"return_capsule_with_destructor_2", []() {
258 return py::capsule((
void *) 1234, [](
void *ptr) {
259 py::print(
"destructing capsule: {}"_s.format((
size_t) ptr));
263 m.def(
"return_capsule_with_destructor_3", []() {
265 auto cap = py::capsule((
void *) 1233,
"oname", [](
void *ptr) {
266 py::print(
"destructing capsule: {}"_s.format((
size_t) ptr));
268 py::print(
"original name: {}"_s.format(cap.name()));
272 m.def(
"return_renamed_capsule_with_destructor_2", []() {
274 auto cap = py::capsule((
void *) 1234, [](
void *ptr) {
275 py::print(
"destructing capsule: {}"_s.format((
size_t) ptr));
277 static const char *capsule_name =
"test_name2";
279 cap.set_name(capsule_name);
283 m.def(
"return_capsule_with_name_and_destructor", []() {
284 auto capsule = py::capsule((
void *) 12345,
"pointer type description", [](PyObject *ptr) {
286 const auto *
name = PyCapsule_GetName(ptr);
287 py::print(
"destructing capsule ({}, '{}')"_s.format(
288 (
size_t) PyCapsule_GetPointer(ptr,
name),
name));
292 capsule.set_pointer((
void *) 1234);
295 void *contents1 =
static_cast<void *
>(
capsule);
296 void *contents2 =
capsule.get_pointer();
297 void *contents3 =
capsule.get_pointer<
void>();
299 auto result1 =
reinterpret_cast<size_t>(contents1);
300 auto result2 =
reinterpret_cast<size_t>(contents2);
301 auto result3 =
reinterpret_cast<size_t>(contents3);
304 "created capsule ({}, '{}')"_s.format(result1 & result2 & result3,
capsule.name()));
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));
315 m.def(
"accessor_api", [](
const py::object &o) {
318 d[
"basic_attr"] = o.attr(
"basic_attr");
321 for (
auto item : o.attr(
"begin_end")) {
326 d[
"operator[object]"] = o.attr(
"d")[
"operator[object]"_s];
327 d[
"operator[char *]"] = o.attr(
"d")[
"operator[char *]"];
329 d[
"attr(object)"] = o.attr(
"sub").attr(
"attr_obj");
330 d[
"attr(char *)"] = o.attr(
"sub").attr(
"attr_char");
332 o.attr(
"sub").attr(
"missing").ptr();
333 }
catch (
const py::error_already_set &) {
334 d[
"missing_attr_ptr"] =
"raised"_s;
337 o.attr(
"missing").attr(
"doesn't matter");
338 }
catch (
const py::error_already_set &) {
339 d[
"missing_attr_chain"] =
"raised"_s;
342 d[
"is_none"] = o.attr(
"basic_attr").is_none();
344 d[
"operator()"] = o.attr(
"func")(1);
345 d[
"operator*"] = o.attr(
"func")(*o.attr(
"begin_end"));
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;
356 m.def(
"tuple_accessor", [](
const py::tuple &existing_t) {
359 }
catch (
const py::error_already_set &) {
362 auto new_t = py::tuple(3);
363 for (
size_t i = 0;
i < new_t.size(); ++
i) {
371 m.def(
"accessor_assignment", []() {
372 auto l = py::list(1);
378 d[
"deferred_get"] = var;
382 d[
"deferred_set"] =
l[0];
388 m.def(
"accessor_moves", []() {
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);
397 py::sequence
seq(tup);
402 # define PYBIND11_LOCAL_DEF(...) \
404 std::size_t inc_refs = py::handle::inc_ref_counter(); \
406 inc_refs = py::handle::inc_ref_counter() - inc_refs; \
407 return_list.append(inc_refs); \
410 PYBIND11_LOCAL_DEF(tup[py_int_0])
411 PYBIND11_LOCAL_DEF(tup[py::int_(0)])
413 PYBIND11_LOCAL_DEF(tup.attr(py_str_count))
414 PYBIND11_LOCAL_DEF(tup.attr(
py::str(
"count")))
416 PYBIND11_LOCAL_DEF(
seq[py_int_0])
417 PYBIND11_LOCAL_DEF(
seq[py::int_(0)])
419 PYBIND11_LOCAL_DEF(
seq.attr(py_str_count))
420 PYBIND11_LOCAL_DEF(
seq.attr(
py::str(
"count")))
422 PYBIND11_LOCAL_DEF(lst[py_int_0])
423 PYBIND11_LOCAL_DEF(lst[py::int_(0)])
425 PYBIND11_LOCAL_DEF(lst.attr(py_str_count))
426 PYBIND11_LOCAL_DEF(lst.attr(
py::str(
"count")))
428 auto lst_acc = lst[py::int_(0)];
429 lst_acc = py::int_(42);
430 PYBIND11_LOCAL_DEF(lst_acc = py_int_42)
431 PYBIND11_LOCAL_DEF(lst_acc = py::int_(42))
432 # undef PYBIND11_LOCAL_DEF
438 m.def(
"default_constructors", []() {
439 return py::dict(
"bytes"_a = py::bytes(),
440 "bytearray"_a = py::bytearray(),
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(),
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"]),
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"]),
462 "frozenset"_a = py::frozenset(
d[
"frozenset"]),
463 "memoryview"_a = py::memoryview(
d[
"memoryview"]));
466 m.def(
"cast_functions", [](
const py::dict &
d) {
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>());
482 m.def(
"convert_to_pybind11_str", [](
const py::object &o) {
return py::str(o); });
484 m.def(
"nonconverting_constructor",
485 [](
const std::string &
type, py::object
value,
bool move) -> py::object {
486 if (
type ==
"bytes") {
489 if (
type ==
"none") {
492 if (
type ==
"ellipsis") {
493 return move ? py::ellipsis(std::move(
value)) : py::ellipsis(
value);
495 if (
type ==
"type") {
498 throw std::runtime_error(
"Invalid type");
501 m.def(
"get_implicit_casting", []() {
503 d[
"char*_i1"] =
"abc";
504 const char *
c2 =
"abc";
515 d[
"int_p"] = py::int_(
i);
517 d[
"str_i1"] = std::string(
"str");
518 std::string s2(
"str1");
530 l.append(py::int_(15));
532 return py::dict(
"d"_a =
d,
"l"_a =
l);
536 m.def(
"print_function", []() {
538 py::print(1, 2.0,
"three",
true, std::string(
"-- multiple args"));
541 py::print(
"no new line here",
"end"_a =
" -- ");
544 auto py_stderr = py::module_::import(
"sys").attr(
"stderr");
545 py::print(
"this goes to stderr",
"file"_a = py_stderr);
550 "{a} + {b} = {c}"_s.format(
"a"_a =
"py::print",
"b"_a =
"str.format",
"c"_a =
"this"));
555 m.def(
"hash_function", [](py::object obj) {
return py::hash(std::move(obj)); });
557 m.def(
"obj_contains",
558 [](py::object &obj,
const py::object &
key) {
return obj.contains(
key); });
560 m.def(
"test_number_protocol", [](
const py::object &
a,
const py::object &
b) {
562 l.append(
a.equal(
b));
563 l.append(
a.not_equal(
b));
580 m.def(
"test_list_slicing", [](
const py::list &
a) {
return a[py::slice(0, -1, 2)]; });
583 m.def(
"issue2361_str_implicit_copy_none", []() {
584 py::str is_this_none = py::none();
587 m.def(
"issue2361_dict_implicit_copy_none", []() {
588 py::dict is_this_none = py::none();
592 m.def(
"test_memoryview_object", [](
const py::buffer &
b) {
return py::memoryview(
b); });
594 m.def(
"test_memoryview_buffer_info",
595 [](
const py::buffer &
b) {
return py::memoryview(
b.request()); });
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};
601 return py::memoryview::from_buffer(ui16, {4}, {
sizeof(
uint16_t)});
603 return py::memoryview::from_buffer(si16, {5}, {
sizeof(
int16_t)});
606 m.def(
"test_memoryview_from_buffer_nativeformat", []() {
607 static const char *
format =
"@i";
612 m.def(
"test_memoryview_from_buffer_empty_shape", []() {
613 static const char *buf =
"";
614 return py::memoryview::from_buffer(buf, 1,
"B", {}, {});
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}, {});
622 m.def(
"test_memoryview_from_buffer_nullptr", []() {
623 return py::memoryview::from_buffer(
static_cast<void *
>(
nullptr), 1,
"B", {}, {});
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)));
632 m.def(
"get_len", [](py::handle
h) {
return py::len(
h); });
634 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
635 m.attr(
"PYBIND11_STR_LEGACY_PERMISSIVE") =
true;
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)); });
643 m.def(
"pass_to_pybind11_bytes", [](py::bytes
b) {
return py::len(std::move(
b)); });
645 m.def(
"pass_to_std_string", [](
const std::string &
s) {
return s.size(); });
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)); });
659 #if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION)
661 # define PYBIND11_AUTO_IT auto it
665 # define PYBIND11_AUTO_IT auto &it
668 m.def(
"tuple_iterator", []() {
672 tup_sum += it.cast<
int>();
677 m.def(
"dict_iterator", []() {
679 dct[py::int_(3)] = 5;
680 dct[py::int_(7)] = 11;
683 kv_sum += it.first.cast<
int>() * 100 + it.second.cast<
int>();
688 m.def(
"passed_iterator", [](
const py::iterator &py_it) {
691 elem_sum += it.cast<
int>();
696 #undef PYBIND11_AUTO_IT
700 m.def(
"sequence_item_get_ssize_t", [](
const py::object &o) {
703 m.def(
"sequence_item_set_ssize_t", [](
const py::object &o) {
707 m.def(
"sequence_item_get_size_t", [](
const py::object &o) {
710 m.def(
"sequence_item_set_size_t", [](
const py::object &o) {
714 m.def(
"list_item_get_ssize_t", [](
const py::object &o) {
717 m.def(
"list_item_set_ssize_t", [](
const py::object &o) {
721 m.def(
"list_item_get_size_t", [](
const py::object &o) {
724 m.def(
"list_item_set_size_t", [](
const py::object &o) {
728 m.def(
"tuple_item_get_ssize_t", [](
const py::object &o) {
731 m.def(
"tuple_item_set_ssize_t", []() {
733 auto s1 =
py::str{
"edmond", 6};
734 auto o = py::tuple{2};
739 m.def(
"tuple_item_get_size_t", [](
const py::object &o) {
742 m.def(
"tuple_item_set_size_t", []() {
745 auto o = py::tuple{2};
752 double v =
x.get_value();
756 m.def(
"tuple_rvalue_getter", [](
const py::tuple &tup) {
758 for (
size_t i = 0;
i < tup.size();
i++) {
759 auto o = py::handle(tup[py::int_(
i)]);
761 throw py::value_error(
"tuple is malformed");
766 m.def(
"list_rvalue_getter", [](
const py::list &
l) {
768 for (
size_t i = 0;
i <
l.size();
i++) {
769 auto o = py::handle(
l[py::int_(
i)]);
771 throw py::value_error(
"list is malformed");
776 m.def(
"populate_dict_rvalue", [](
int population) {
778 for (
int i = 0;
i < population;
i++) {
779 d[py::int_(
i)] = py::int_(
i);
783 m.def(
"populate_obj_str_attrs", [](py::object &o,
int population) {
784 for (
int i = 0;
i < population;
i++) {
791 m.def(
"inplace_append", [](py::object &
a,
const py::object &
b) {
795 m.def(
"inplace_subtract", [](py::object &
a,
const py::object &
b) {
799 m.def(
"inplace_multiply", [](py::object &
a,
const py::object &
b) {
803 m.def(
"inplace_divide", [](py::object &
a,
const py::object &
b) {
807 m.def(
"inplace_or", [](py::object &
a,
const py::object &
b) {
811 m.def(
"inplace_and", [](py::object &
a,
const py::object &
b) {
815 m.def(
"inplace_lshift", [](py::object &
a,
const py::object &
b) {
819 m.def(
"inplace_rshift", [](py::object &
a,
const py::object &
b) {