test_pytypes.cpp
Go to the documentation of this file.
1 /*
2  tests/test_pytypes.cpp -- Python type casters
3 
4  Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #include "pybind11_tests.h"
11 
12 
13 TEST_SUBMODULE(pytypes, m) {
14  // test_int
15  m.def("get_int", []{return py::int_(0);});
16  // test_iterator
17  m.def("get_iterator", []{return py::iterator();});
18  // test_iterable
19  m.def("get_iterable", []{return py::iterable();});
20  // test_list
21  m.def("get_list", []() {
22  py::list list;
23  list.append("value");
24  py::print("Entry at position 0:", list[0]);
25  list[0] = py::str("overwritten");
26  list.insert(0, "inserted-0");
27  list.insert(2, "inserted-2");
28  return list;
29  });
30  m.def("print_list", [](py::list list) {
31  int index = 0;
32  for (auto item : list)
33  py::print("list item {}: {}"_s.format(index++, item));
34  });
35  // test_none
36  m.def("get_none", []{return py::none();});
37  m.def("print_none", [](py::none none) {
38  py::print("none: {}"_s.format(none));
39  });
40 
41  // test_set
42  m.def("get_set", []() {
43  py::set set;
44  set.add(py::str("key1"));
45  set.add("key2");
46  set.add(std::string("key3"));
47  return set;
48  });
49  m.def("print_set", [](py::set set) {
50  for (auto item : set)
51  py::print("key:", item);
52  });
53  m.def("set_contains", [](py::set set, py::object key) {
54  return set.contains(key);
55  });
56  m.def("set_contains", [](py::set set, const char* key) {
57  return set.contains(key);
58  });
59 
60  // test_dict
61  m.def("get_dict", []() { return py::dict("key"_a="value"); });
62  m.def("print_dict", [](py::dict dict) {
63  for (auto item : dict)
64  py::print("key: {}, value={}"_s.format(item.first, item.second));
65  });
66  m.def("dict_keyword_constructor", []() {
67  auto d1 = py::dict("x"_a=1, "y"_a=2);
68  auto d2 = py::dict("z"_a=3, **d1);
69  return d2;
70  });
71  m.def("dict_contains", [](py::dict dict, py::object val) {
72  return dict.contains(val);
73  });
74  m.def("dict_contains", [](py::dict dict, const char* val) {
75  return dict.contains(val);
76  });
77 
78  // test_str
79  m.def("str_from_string", []() { return py::str(std::string("baz")); });
80  m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
81  m.def("str_from_object", [](const py::object& obj) { return py::str(obj); });
82  m.def("repr_from_object", [](const py::object& obj) { return py::repr(obj); });
83  m.def("str_from_handle", [](py::handle h) { return py::str(h); });
84 
85  m.def("str_format", []() {
86  auto s1 = "{} + {} = {}"_s.format(1, 2, 3);
87  auto s2 = "{a} + {b} = {c}"_s.format("a"_a=1, "b"_a=2, "c"_a=3);
88  return py::make_tuple(s1, s2);
89  });
90 
91  // test_bytes
92  m.def("bytes_from_string", []() { return py::bytes(std::string("foo")); });
93  m.def("bytes_from_str", []() { return py::bytes(py::str("bar", 3)); });
94 
95  // test_capsule
96  m.def("return_capsule_with_destructor", []() {
97  py::print("creating capsule");
98  return py::capsule([]() {
99  py::print("destructing capsule");
100  });
101  });
102 
103  m.def("return_capsule_with_destructor_2", []() {
104  py::print("creating capsule");
105  return py::capsule((void *) 1234, [](void *ptr) {
106  py::print("destructing capsule: {}"_s.format((size_t) ptr));
107  });
108  });
109 
110  m.def("return_capsule_with_name_and_destructor", []() {
111  auto capsule = py::capsule((void *) 1234, "pointer type description", [](PyObject *ptr) {
112  if (ptr) {
113  auto name = PyCapsule_GetName(ptr);
114  py::print("destructing capsule ({}, '{}')"_s.format(
115  (size_t) PyCapsule_GetPointer(ptr, name), name
116  ));
117  }
118  });
119  void *contents = capsule;
120  py::print("created capsule ({}, '{}')"_s.format((size_t) contents, capsule.name()));
121  return capsule;
122  });
123 
124  // test_accessors
125  m.def("accessor_api", [](py::object o) {
126  auto d = py::dict();
127 
128  d["basic_attr"] = o.attr("basic_attr");
129 
130  auto l = py::list();
131  for (const auto &item : o.attr("begin_end")) {
132  l.append(item);
133  }
134  d["begin_end"] = l;
135 
136  d["operator[object]"] = o.attr("d")["operator[object]"_s];
137  d["operator[char *]"] = o.attr("d")["operator[char *]"];
138 
139  d["attr(object)"] = o.attr("sub").attr("attr_obj");
140  d["attr(char *)"] = o.attr("sub").attr("attr_char");
141  try {
142  o.attr("sub").attr("missing").ptr();
143  } catch (const py::error_already_set &) {
144  d["missing_attr_ptr"] = "raised"_s;
145  }
146  try {
147  o.attr("missing").attr("doesn't matter");
148  } catch (const py::error_already_set &) {
149  d["missing_attr_chain"] = "raised"_s;
150  }
151 
152  d["is_none"] = o.attr("basic_attr").is_none();
153 
154  d["operator()"] = o.attr("func")(1);
155  d["operator*"] = o.attr("func")(*o.attr("begin_end"));
156 
157  // Test implicit conversion
158  py::list implicit_list = o.attr("begin_end");
159  d["implicit_list"] = implicit_list;
160  py::dict implicit_dict = o.attr("__dict__");
161  d["implicit_dict"] = implicit_dict;
162 
163  return d;
164  });
165 
166  m.def("tuple_accessor", [](py::tuple existing_t) {
167  try {
168  existing_t[0] = 1;
169  } catch (const py::error_already_set &) {
170  // --> Python system error
171  // Only new tuples (refcount == 1) are mutable
172  auto new_t = py::tuple(3);
173  for (size_t i = 0; i < new_t.size(); ++i) {
174  new_t[i] = i;
175  }
176  return new_t;
177  }
178  return py::tuple();
179  });
180 
181  m.def("accessor_assignment", []() {
182  auto l = py::list(1);
183  l[0] = 0;
184 
185  auto d = py::dict();
186  d["get"] = l[0];
187  auto var = l[0];
188  d["deferred_get"] = var;
189  l[0] = 1;
190  d["set"] = l[0];
191  var = 99; // this assignment should not overwrite l[0]
192  d["deferred_set"] = l[0];
193  d["var"] = var;
194 
195  return d;
196  });
197 
198  // test_constructors
199  m.def("default_constructors", []() {
200  return py::dict(
201  "bytes"_a=py::bytes(),
202  "str"_a=py::str(),
203  "bool"_a=py::bool_(),
204  "int"_a=py::int_(),
205  "float"_a=py::float_(),
206  "tuple"_a=py::tuple(),
207  "list"_a=py::list(),
208  "dict"_a=py::dict(),
209  "set"_a=py::set()
210  );
211  });
212 
213  m.def("converting_constructors", [](py::dict d) {
214  return py::dict(
215  "bytes"_a=py::bytes(d["bytes"]),
216  "str"_a=py::str(d["str"]),
217  "bool"_a=py::bool_(d["bool"]),
218  "int"_a=py::int_(d["int"]),
219  "float"_a=py::float_(d["float"]),
220  "tuple"_a=py::tuple(d["tuple"]),
221  "list"_a=py::list(d["list"]),
222  "dict"_a=py::dict(d["dict"]),
223  "set"_a=py::set(d["set"]),
224  "memoryview"_a=py::memoryview(d["memoryview"])
225  );
226  });
227 
228  m.def("cast_functions", [](py::dict d) {
229  // When converting between Python types, obj.cast<T>() should be the same as T(obj)
230  return py::dict(
231  "bytes"_a=d["bytes"].cast<py::bytes>(),
232  "str"_a=d["str"].cast<py::str>(),
233  "bool"_a=d["bool"].cast<py::bool_>(),
234  "int"_a=d["int"].cast<py::int_>(),
235  "float"_a=d["float"].cast<py::float_>(),
236  "tuple"_a=d["tuple"].cast<py::tuple>(),
237  "list"_a=d["list"].cast<py::list>(),
238  "dict"_a=d["dict"].cast<py::dict>(),
239  "set"_a=d["set"].cast<py::set>(),
240  "memoryview"_a=d["memoryview"].cast<py::memoryview>()
241  );
242  });
243 
244  m.def("convert_to_pybind11_str", [](py::object o) { return py::str(o); });
245 
246  m.def("get_implicit_casting", []() {
247  py::dict d;
248  d["char*_i1"] = "abc";
249  const char *c2 = "abc";
250  d["char*_i2"] = c2;
251  d["char*_e"] = py::cast(c2);
252  d["char*_p"] = py::str(c2);
253 
254  d["int_i1"] = 42;
255  int i = 42;
256  d["int_i2"] = i;
257  i++;
258  d["int_e"] = py::cast(i);
259  i++;
260  d["int_p"] = py::int_(i);
261 
262  d["str_i1"] = std::string("str");
263  std::string s2("str1");
264  d["str_i2"] = s2;
265  s2[3] = '2';
266  d["str_e"] = py::cast(s2);
267  s2[3] = '3';
268  d["str_p"] = py::str(s2);
269 
270  py::list l(2);
271  l[0] = 3;
272  l[1] = py::cast(6);
273  l.append(9);
274  l.append(py::cast(12));
275  l.append(py::int_(15));
276 
277  return py::dict(
278  "d"_a=d,
279  "l"_a=l
280  );
281  });
282 
283  // test_print
284  m.def("print_function", []() {
285  py::print("Hello, World!");
286  py::print(1, 2.0, "three", true, std::string("-- multiple args"));
287  auto args = py::make_tuple("and", "a", "custom", "separator");
288  py::print("*args", *args, "sep"_a="-");
289  py::print("no new line here", "end"_a=" -- ");
290  py::print("next print");
291 
292  auto py_stderr = py::module::import("sys").attr("stderr");
293  py::print("this goes to stderr", "file"_a=py_stderr);
294 
295  py::print("flush", "flush"_a=true);
296 
297  py::print("{a} + {b} = {c}"_s.format("a"_a="py::print", "b"_a="str.format", "c"_a="this"));
298  });
299 
300  m.def("print_failure", []() { py::print(42, UnregisteredType()); });
301 
302  m.def("hash_function", [](py::object obj) { return py::hash(obj); });
303 
304  m.def("test_number_protocol", [](py::object a, py::object b) {
305  py::list l;
306  l.append(a.equal(b));
307  l.append(a.not_equal(b));
308  l.append(a < b);
309  l.append(a <= b);
310  l.append(a > b);
311  l.append(a >= b);
312  l.append(a + b);
313  l.append(a - b);
314  l.append(a * b);
315  l.append(a / b);
316  l.append(a | b);
317  l.append(a & b);
318  l.append(a ^ b);
319  l.append(a >> b);
320  l.append(a << b);
321  return l;
322  });
323 
324  m.def("test_list_slicing", [](py::list a) {
325  return a[py::slice(0, -1, 2)];
326  });
327 
328  // See #2361
329  m.def("issue2361_str_implicit_copy_none", []() {
330  py::str is_this_none = py::none();
331  return is_this_none;
332  });
333  m.def("issue2361_dict_implicit_copy_none", []() {
334  py::dict is_this_none = py::none();
335  return is_this_none;
336  });
337 
338  m.def("test_memoryview_object", [](py::buffer b) {
339  return py::memoryview(b);
340  });
341 
342  m.def("test_memoryview_buffer_info", [](py::buffer b) {
343  return py::memoryview(b.request());
344  });
345 
346  m.def("test_memoryview_from_buffer", [](bool is_unsigned) {
347  static const int16_t si16[] = { 3, 1, 4, 1, 5 };
348  static const uint16_t ui16[] = { 2, 7, 1, 8 };
349  if (is_unsigned)
350  return py::memoryview::from_buffer(
351  ui16, { 4 }, { sizeof(uint16_t) });
352  else
353  return py::memoryview::from_buffer(
354  si16, { 5 }, { sizeof(int16_t) });
355  });
356 
357  m.def("test_memoryview_from_buffer_nativeformat", []() {
358  static const char* format = "@i";
359  static const int32_t arr[] = { 4, 7, 5 };
360  return py::memoryview::from_buffer(
361  arr, sizeof(int32_t), format, { 3 }, { sizeof(int32_t) });
362  });
363 
364  m.def("test_memoryview_from_buffer_empty_shape", []() {
365  static const char* buf = "";
366  return py::memoryview::from_buffer(buf, 1, "B", { }, { });
367  });
368 
369  m.def("test_memoryview_from_buffer_invalid_strides", []() {
370  static const char* buf = "\x02\x03\x04";
371  return py::memoryview::from_buffer(buf, 1, "B", { 3 }, { });
372  });
373 
374  m.def("test_memoryview_from_buffer_nullptr", []() {
375  return py::memoryview::from_buffer(
376  static_cast<void*>(nullptr), 1, "B", { }, { });
377  });
378 
379 #if PY_MAJOR_VERSION >= 3
380  m.def("test_memoryview_from_memory", []() {
381  const char* buf = "\xff\xe1\xab\x37";
382  return py::memoryview::from_memory(
383  buf, static_cast<ssize_t>(strlen(buf)));
384  });
385 #endif
386 }
void print(const Matrix &A, const string &s, ostream &stream)
Definition: Matrix.cpp:155
Matrix3f m
ssize_t hash(handle obj)
Definition: pytypes.h:457
static const Key c2
Scalar * b
Definition: benchVecAdd.cpp:17
Definition: pytypes.h:1322
unsigned short uint16_t
Definition: ms_stdint.h:84
py::array arr
signed short int16_t
Definition: ms_stdint.h:81
TEST_SUBMODULE(pytypes, m)
Dummy type which is not exported anywhere – something to trigger a conversion error.
Array33i a
static const Line3 l(Rot3(), 1, 1)
Tuple< Args... > make_tuple(Args...args)
Creates a tuple object, deducing the target type from the types of arguments.
float * ptr
EIGEN_DEVICE_FUNC NewType cast(const OldType &x)
signed int int32_t
Definition: ms_stdint.h:82
void set(Container &c, Position position, const Value &value)
const double h
Definition: pytypes.h:1255
Annotation for function names.
Definition: attr.h:36
str repr(handle h)
Definition: pytypes.h:1536


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:46:04