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);
105 m.def(
"get_bool", [] {
return py::bool_(
false); });
107 m.def(
"get_int", [] {
return py::int_(0); });
109 m.def(
"get_iterator", [] {
return py::iterator(); });
111 m.def(
"get_iterable", [] {
return py::iterable(); });
113 m.def(
"get_float", [] {
return py::float_(0.0
f); });
115 m.def(
"list_no_args", []() {
return py::list{}; });
116 m.def(
"list_ssize_t", []() {
return py::list{(
py::ssize_t) 0}; });
117 m.def(
"list_size_t", []() {
return py::list{(
py::size_t) 0}; });
118 m.def(
"list_insert_ssize_t", [](py::list *
l) {
return l->insert((
py::ssize_t) 1, 83); });
119 m.def(
"list_insert_size_t", [](py::list *l) {
return l->insert((
py::size_t) 3, 57); });
120 m.def(
"get_list", []() {
122 list.append(
"value");
123 py::print(
"Entry at position 0:", list[0]);
124 list[0] =
py::str(
"overwritten");
125 list.insert(0,
"inserted-0");
126 list.insert(2,
"inserted-2");
129 m.def(
"print_list", [](
const py::list &list) {
131 for (
auto item : list) {
132 py::print(
"list item {}: {}"_s.format(index++, item));
136 m.def(
"get_none", [] {
return py::none(); });
137 m.def(
"print_none", [](
const py::none &
none) {
py::print(
"none: {}"_s.format(none)); });
140 m.def(
"get_set", []() {
144 set.add(std::string(
"key3"));
147 m.def(
"get_frozenset", []() {
151 set.add(std::string(
"key3"));
152 return py::frozenset(
set);
154 m.def(
"print_anyset", [](
const py::anyset &
set) {
155 for (
auto item :
set) {
159 m.def(
"anyset_size", [](
const py::anyset &
set) {
return set.size(); });
160 m.def(
"anyset_empty", [](
const py::anyset &
set) {
return set.empty(); });
161 m.def(
"anyset_contains",
162 [](
const py::anyset &
set,
const py::object &
key) {
return set.contains(key); });
163 m.def(
"anyset_contains",
164 [](
const py::anyset &
set,
const char *key) {
return set.contains(key); });
165 m.def(
"set_add", [](
py::set &
set,
const py::object &key) {
set.add(key); });
166 m.def(
"set_clear", [](
py::set &
set) {
set.clear(); });
169 m.def(
"get_dict", []() {
return py::dict(
"key"_a =
"value"); });
170 m.def(
"print_dict", [](
const py::dict &
dict) {
171 for (
auto item : dict) {
172 py::print(
"key: {}, value={}"_s.format(item.first, item.second));
175 m.def(
"dict_keyword_constructor", []() {
176 auto d1 = py::dict(
"x"_a = 1,
"y"_a = 2);
177 auto d2 = py::dict(
"z"_a = 3, **d1);
180 m.def(
"dict_contains",
181 [](
const py::dict &dict, py::object val) {
return dict.contains(val); });
182 m.def(
"dict_contains",
183 [](
const py::dict &dict,
const char *val) {
return dict.contains(val); });
186 m.def(
"tuple_no_args", []() {
return py::tuple{}; });
187 m.def(
"tuple_ssize_t", []() {
return py::tuple{(
py::ssize_t) 0}; });
188 m.def(
"tuple_size_t", []() {
return py::tuple{(
py::size_t) 0}; });
189 m.def(
"get_tuple", []() {
return py::make_tuple(42, py::none(),
"spam"); });
192 m.def(
"get_simple_namespace", []() {
193 auto ns = py::module_::import(
"types").attr(
"SimpleNamespace")(
194 "attr"_a = 42,
"x"_a =
"foo",
"wrong"_a = 1);
203 m.def(
"str_from_string", []() {
return py::str(std::string(
"baz")); });
204 m.def(
"str_from_bytes", []() {
return py::str(py::bytes(
"boo", 3)); });
205 m.def(
"str_from_object", [](
const py::object &obj) {
return py::str(obj); });
206 m.def(
"repr_from_object", [](
const py::object &obj) {
return py::repr(obj); });
207 m.def(
"str_from_handle", [](py::handle
h) {
return py::str(h); });
208 m.def(
"str_from_string_from_str",
209 [](
const py::str &obj) {
return py::str(static_cast<std::string>(obj)); });
211 m.def(
"str_format", []() {
212 auto s1 =
"{} + {} = {}"_s.format(1, 2, 3);
213 auto s2 =
"{a} + {b} = {c}"_s.format(
"a"_a = 1,
"b"_a = 2,
"c"_a = 3);
218 m.def(
"bytes_from_char_ssize_t", []() {
return py::bytes{
"green", (
py::ssize_t) 5}; });
219 m.def(
"bytes_from_char_size_t", []() {
return py::bytes{
"purple", (
py::size_t) 6}; });
220 m.def(
"bytes_from_string", []() {
return py::bytes(std::string(
"foo")); });
221 m.def(
"bytes_from_str", []() {
return py::bytes(
py::str(
"bar", 3)); });
224 m.def(
"bytearray_from_char_ssize_t", []() {
return py::bytearray{
"$%", (
py::ssize_t) 2}; });
225 m.def(
"bytearray_from_char_size_t", []() {
return py::bytearray{
"@$!", (
py::size_t) 3}; });
226 m.def(
"bytearray_from_string", []() {
return py::bytearray(std::string(
"foo")); });
227 m.def(
"bytearray_size", []() {
return py::bytearray(
"foo").size(); });
230 m.def(
"return_capsule_with_destructor", []() {
232 return py::capsule([]() {
py::print(
"destructing capsule"); });
235 m.def(
"return_renamed_capsule_with_destructor", []() {
237 auto cap = py::capsule([]() {
py::print(
"destructing capsule"); });
238 static const char *capsule_name =
"test_name1";
240 cap.set_name(capsule_name);
244 m.def(
"return_capsule_with_destructor_2", []() {
246 return py::capsule((
void *) 1234, [](
void *ptr) {
247 py::print(
"destructing capsule: {}"_s.format((
size_t) ptr));
251 m.def(
"return_renamed_capsule_with_destructor_2", []() {
253 auto cap = py::capsule((
void *) 1234, [](
void *ptr) {
254 py::print(
"destructing capsule: {}"_s.format((
size_t) ptr));
256 static const char *capsule_name =
"test_name2";
258 cap.set_name(capsule_name);
262 m.def(
"return_capsule_with_name_and_destructor", []() {
263 auto capsule = py::capsule((
void *) 12345,
"pointer type description", [](PyObject *ptr) {
265 const auto *
name = PyCapsule_GetName(ptr);
266 py::print(
"destructing capsule ({}, '{}')"_s.format(
267 (
size_t) PyCapsule_GetPointer(ptr,
name),
name));
271 capsule.set_pointer((
void *) 1234);
274 void *contents1 =
static_cast<void *
>(
capsule);
275 void *contents2 =
capsule.get_pointer();
276 void *contents3 =
capsule.get_pointer<
void>();
278 auto result1 =
reinterpret_cast<size_t>(contents1);
279 auto result2 =
reinterpret_cast<size_t>(contents2);
280 auto result3 =
reinterpret_cast<size_t>(contents3);
283 "created capsule ({}, '{}')"_s.format(result1 & result2 & result3,
capsule.name()));
288 m.def(
"accessor_api", [](
const py::object &o) {
291 d[
"basic_attr"] = o.attr(
"basic_attr");
294 for (
auto item : o.attr(
"begin_end")) {
299 d[
"operator[object]"] = o.attr(
"d")[
"operator[object]"_s];
300 d[
"operator[char *]"] = o.attr(
"d")[
"operator[char *]"];
302 d[
"attr(object)"] = o.attr(
"sub").attr(
"attr_obj");
303 d[
"attr(char *)"] = o.attr(
"sub").attr(
"attr_char");
305 o.attr(
"sub").attr(
"missing").ptr();
306 }
catch (
const py::error_already_set &) {
307 d[
"missing_attr_ptr"] =
"raised"_s;
310 o.attr(
"missing").attr(
"doesn't matter");
311 }
catch (
const py::error_already_set &) {
312 d[
"missing_attr_chain"] =
"raised"_s;
315 d[
"is_none"] = o.attr(
"basic_attr").is_none();
317 d[
"operator()"] = o.attr(
"func")(1);
318 d[
"operator*"] = o.attr(
"func")(*o.attr(
"begin_end"));
321 py::list implicit_list = o.attr(
"begin_end");
322 d[
"implicit_list"] = implicit_list;
323 py::dict implicit_dict = o.attr(
"__dict__");
324 d[
"implicit_dict"] = implicit_dict;
329 m.def(
"tuple_accessor", [](
const py::tuple &existing_t) {
332 }
catch (
const py::error_already_set &) {
335 auto new_t = py::tuple(3);
336 for (
size_t i = 0;
i < new_t.size(); ++
i) {
344 m.def(
"accessor_assignment", []() {
345 auto l = py::list(1);
351 d[
"deferred_get"] = var;
355 d[
"deferred_set"] = l[0];
361 m.def(
"accessor_moves", []() {
362 py::list return_list;
363 #ifdef PYBIND11_HANDLE_REF_DEBUG 364 py::int_ py_int_0(0);
365 py::int_ py_int_42(42);
370 py::sequence
seq(tup);
375 # define PYBIND11_LOCAL_DEF(...) \ 377 std::size_t inc_refs = py::handle::inc_ref_counter(); \ 379 inc_refs = py::handle::inc_ref_counter() - inc_refs; \ 380 return_list.append(inc_refs); \ 383 PYBIND11_LOCAL_DEF(tup[py_int_0])
384 PYBIND11_LOCAL_DEF(tup[py::int_(0)])
386 PYBIND11_LOCAL_DEF(tup.attr(py_str_count))
387 PYBIND11_LOCAL_DEF(tup.attr(
py::str(
"count")))
389 PYBIND11_LOCAL_DEF(seq[py_int_0])
390 PYBIND11_LOCAL_DEF(seq[py::int_(0)])
392 PYBIND11_LOCAL_DEF(seq.attr(py_str_count))
393 PYBIND11_LOCAL_DEF(seq.attr(
py::str(
"count")))
395 PYBIND11_LOCAL_DEF(lst[py_int_0])
396 PYBIND11_LOCAL_DEF(lst[py::int_(0)])
398 PYBIND11_LOCAL_DEF(lst.attr(py_str_count))
399 PYBIND11_LOCAL_DEF(lst.attr(
py::str(
"count")))
401 auto lst_acc = lst[py::int_(0)];
402 lst_acc = py::int_(42);
403 PYBIND11_LOCAL_DEF(lst_acc = py_int_42)
404 PYBIND11_LOCAL_DEF(lst_acc = py::int_(42))
405 # undef PYBIND11_LOCAL_DEF 411 m.def(
"default_constructors", []() {
412 return py::dict(
"bytes"_a = py::bytes(),
413 "bytearray"_a = py::bytearray(),
415 "bool"_a = py::bool_(),
416 "int"_a = py::int_(),
417 "float"_a = py::float_(),
418 "tuple"_a = py::tuple(),
419 "list"_a = py::list(),
420 "dict"_a = py::dict(),
424 m.def(
"converting_constructors", [](
const py::dict &
d) {
425 return py::dict(
"bytes"_a = py::bytes(d[
"bytes"]),
426 "bytearray"_a = py::bytearray(d[
"bytearray"]),
428 "bool"_a = py::bool_(d[
"bool"]),
429 "int"_a = py::int_(d[
"int"]),
430 "float"_a = py::float_(d[
"float"]),
431 "tuple"_a = py::tuple(d[
"tuple"]),
432 "list"_a = py::list(d[
"list"]),
433 "dict"_a = py::dict(d[
"dict"]),
435 "frozenset"_a = py::frozenset(d[
"frozenset"]),
436 "memoryview"_a = py::memoryview(d[
"memoryview"]));
439 m.def(
"cast_functions", [](
const py::dict &d) {
441 return py::dict(
"bytes"_a = d[
"bytes"].cast<py::bytes>(),
442 "bytearray"_a = d[
"bytearray"].cast<py::bytearray>(),
443 "str"_a = d[
"str"].cast<py::str>(),
444 "bool"_a = d[
"bool"].cast<py::bool_>(),
445 "int"_a = d[
"int"].cast<py::int_>(),
446 "float"_a = d[
"float"].cast<py::float_>(),
447 "tuple"_a = d[
"tuple"].cast<py::tuple>(),
448 "list"_a = d[
"list"].cast<py::list>(),
449 "dict"_a = d[
"dict"].cast<py::dict>(),
450 "set"_a = d[
"set"].cast<py::set>(),
451 "frozenset"_a = d[
"frozenset"].cast<py::frozenset>(),
452 "memoryview"_a = d[
"memoryview"].cast<py::memoryview>());
455 m.def(
"convert_to_pybind11_str", [](
const py::object &o) {
return py::str(o); });
457 m.def(
"nonconverting_constructor",
458 [](
const std::string &
type, py::object
value,
bool move) -> py::object {
459 if (type ==
"bytes") {
460 return move ? py::bytes(std::move(value)) : py::bytes(value);
462 if (type ==
"none") {
463 return move ? py::none(std::move(value)) : py::none(value);
465 if (type ==
"ellipsis") {
466 return move ? py::ellipsis(std::move(value)) : py::ellipsis(value);
468 if (type ==
"type") {
471 throw std::runtime_error(
"Invalid type");
474 m.def(
"get_implicit_casting", []() {
476 d[
"char*_i1"] =
"abc";
477 const char *c2 =
"abc";
488 d[
"int_p"] = py::int_(i);
490 d[
"str_i1"] = std::string(
"str");
491 std::string s2(
"str1");
503 l.append(py::int_(15));
505 return py::dict(
"d"_a = d,
"l"_a = l);
509 m.def(
"print_function", []() {
511 py::print(1, 2.0,
"three",
true, std::string(
"-- multiple args"));
514 py::print(
"no new line here",
"end"_a =
" -- ");
517 auto py_stderr = py::module_::import(
"sys").attr(
"stderr");
518 py::print(
"this goes to stderr",
"file"_a = py_stderr);
523 "{a} + {b} = {c}"_s.format(
"a"_a =
"py::print",
"b"_a =
"str.format",
"c"_a =
"this"));
528 m.def(
"hash_function", [](py::object obj) {
return py::hash(std::move(obj)); });
530 m.def(
"test_number_protocol", [](
const py::object &
a,
const py::object &
b) {
532 l.append(a.equal(b));
533 l.append(a.not_equal(b));
550 m.def(
"test_list_slicing", [](
const py::list &a) {
return a[py::slice(0, -1, 2)]; });
553 m.def(
"issue2361_str_implicit_copy_none", []() {
554 py::str is_this_none = py::none();
557 m.def(
"issue2361_dict_implicit_copy_none", []() {
558 py::dict is_this_none = py::none();
562 m.def(
"test_memoryview_object", [](
const py::buffer &b) {
return py::memoryview(b); });
564 m.def(
"test_memoryview_buffer_info",
565 [](
const py::buffer &b) {
return py::memoryview(b.request()); });
567 m.def(
"test_memoryview_from_buffer", [](
bool is_unsigned) {
568 static const int16_t si16[] = {3, 1, 4, 1, 5};
569 static const uint16_t ui16[] = {2, 7, 1, 8};
571 return py::memoryview::from_buffer(ui16, {4}, {
sizeof(
uint16_t)});
573 return py::memoryview::from_buffer(si16, {5}, {
sizeof(
int16_t)});
576 m.def(
"test_memoryview_from_buffer_nativeformat", []() {
577 static const char *
format =
"@i";
579 return py::memoryview::from_buffer(arr,
sizeof(
int32_t), format, {3}, {
sizeof(
int32_t)});
582 m.def(
"test_memoryview_from_buffer_empty_shape", []() {
583 static const char *buf =
"";
584 return py::memoryview::from_buffer(buf, 1,
"B", {}, {});
587 m.def(
"test_memoryview_from_buffer_invalid_strides", []() {
588 static const char *buf =
"\x02\x03\x04";
589 return py::memoryview::from_buffer(buf, 1,
"B", {3}, {});
592 m.def(
"test_memoryview_from_buffer_nullptr", []() {
593 return py::memoryview::from_buffer(static_cast<void *>(
nullptr), 1,
"B", {}, {});
596 m.def(
"test_memoryview_from_memory", []() {
597 const char *buf =
"\xff\xe1\xab\x37";
598 return py::memoryview::from_memory(buf, static_cast<py::ssize_t>(strlen(buf)));
602 m.def(
"get_len", [](py::handle h) {
return py::len(h); });
604 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE 605 m.attr(
"PYBIND11_STR_LEGACY_PERMISSIVE") =
true;
608 m.def(
"isinstance_pybind11_bytes",
609 [](py::object o) {
return py::isinstance<py::bytes>(std::move(o)); });
610 m.def(
"isinstance_pybind11_str",
611 [](py::object o) {
return py::isinstance<py::str>(std::move(o)); });
613 m.def(
"pass_to_pybind11_bytes", [](py::bytes b) {
return py::len(std::move(b)); });
614 m.def(
"pass_to_pybind11_str", [](
py::str s) {
return py::len(std::move(s)); });
615 m.def(
"pass_to_std_string", [](
const std::string &s) {
return s.size(); });
618 m.def(
"weakref_from_handle", [](py::handle h) {
return py::weakref(h); });
619 m.def(
"weakref_from_handle_and_function",
620 [](py::handle h, py::function
f) {
return py::weakref(h, std::move(f)); });
621 m.def(
"weakref_from_object", [](
const py::object &o) {
return py::weakref(o); });
622 m.def(
"weakref_from_object_and_function",
623 [](py::object o, py::function f) {
return py::weakref(std::move(o), std::move(f)); });
629 #if (defined(__APPLE__) && defined(__clang__)) || defined(PYPY_VERSION) 631 # define PYBIND11_AUTO_IT auto it 635 # define PYBIND11_AUTO_IT auto &it 638 m.def(
"tuple_iterator", []() {
642 tup_sum += it.cast<
int>();
647 m.def(
"dict_iterator", []() {
649 dct[py::int_(3)] = 5;
650 dct[py::int_(7)] = 11;
653 kv_sum += it.first.cast<
int>() * 100 + it.second.cast<
int>();
658 m.def(
"passed_iterator", [](
const py::iterator &py_it) {
661 elem_sum += it.cast<
int>();
666 #undef PYBIND11_AUTO_IT 670 m.def(
"sequence_item_get_ssize_t", [](
const py::object &o) {
673 m.def(
"sequence_item_set_ssize_t", [](
const py::object &o) {
677 m.def(
"sequence_item_get_size_t", [](
const py::object &o) {
680 m.def(
"sequence_item_set_size_t", [](
const py::object &o) {
684 m.def(
"list_item_get_ssize_t", [](
const py::object &o) {
687 m.def(
"list_item_set_ssize_t", [](
const py::object &o) {
688 auto s =
py::str{
"rebecca", 7};
691 m.def(
"list_item_get_size_t", [](
const py::object &o) {
694 m.def(
"list_item_set_size_t", [](
const py::object &o) {
695 auto s =
py::str{
"richard", 7};
698 m.def(
"tuple_item_get_ssize_t", [](
const py::object &o) {
701 m.def(
"tuple_item_set_ssize_t", []() {
703 auto s1 =
py::str{
"edmond", 6};
704 auto o = py::tuple{2};
709 m.def(
"tuple_item_get_size_t", [](
const py::object &o) {
712 m.def(
"tuple_item_set_size_t", []() {
715 auto o = py::tuple{2};
726 m.def(
"tuple_rvalue_getter", [](
const py::tuple &tup) {
728 for (
size_t i = 0;
i < tup.size();
i++) {
729 auto o = py::handle(tup[py::int_(
i)]);
731 throw py::value_error(
"tuple is malformed");
736 m.def(
"list_rvalue_getter", [](
const py::list &l) {
738 for (
size_t i = 0;
i < l.size();
i++) {
739 auto o = py::handle(l[py::int_(
i)]);
741 throw py::value_error(
"list is malformed");
746 m.def(
"populate_dict_rvalue", [](
int population) {
748 for (
int i = 0;
i < population;
i++) {
749 d[py::int_(
i)] = py::int_(
i);
753 m.def(
"populate_obj_str_attrs", [](py::object &o,
int population) {
754 for (
int i = 0;
i < population;
i++) {
const gtsam::Symbol key('X', 0)
PyObject * conv(PyObject *o)
void pure_compile_tests_for_handle_from_PyObject_pointers()
EIGEN_STRONG_INLINE Packet4f print(const Packet4f &a)
PyObject * default_constructed()
void delattr(handle obj, handle name)
#define PYBIND11_OBJECT_CVT(Name, Parent, CheckFun, ConvertFun)
void m_defs(py::module_ &m)
TEST_SUBMODULE(pytypes, m)
Dummy type which is not exported anywhere – something to trigger a conversion error.
detail::enable_if_t<!detail::move_never< T >::value, T > move(object &&obj)
static const Line3 l(Rot3(), 1, 1)
Array< int, Dynamic, 1 > v
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
void set(Container &c, Position position, const Value &value)
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)
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Annotation for function names.
Container::iterator get(Container &c, Position position)
size_t len(handle h)
Get the length of a Python object.
set noclip points set clip one set noclip two set bar set border lt lw set xdata set ydata set zdata set x2data set y2data set boxwidth set dummy x
void setattr(handle obj, handle name, handle value)