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 13TEST_SUBMODULE(pytypes, m) { 14 // test_list 15 m.def("get_list", []() { 16 py::list list; 17 list.append("value"); 18 py::print("Entry at position 0:", list[0]); 19 list[0] = py::str("overwritten"); 20 list.insert(0, "inserted-0"); 21 list.insert(2, "inserted-2"); 22 return list; 23 }); 24 m.def("print_list", [](py::list list) { 25 int index = 0; 26 for (auto item : list) 27 py::print("list item {}: {}"_s.format(index++, item)); 28 }); 29 30 // test_set 31 m.def("get_set", []() { 32 py::set set; 33 set.add(py::str("key1")); 34 set.add("key2"); 35 set.add(std::string("key3")); 36 return set; 37 }); 38 m.def("print_set", [](py::set set) { 39 for (auto item : set) 40 py::print("key:", item); 41 }); 42 m.def("set_contains", [](py::set set, py::object key) { 43 return set.contains(key); 44 }); 45 m.def("set_contains", [](py::set set, const char* key) { 46 return set.contains(key); 47 }); 48 49 // test_dict 50 m.def("get_dict", []() { return py::dict("key"_a="value"); }); 51 m.def("print_dict", [](py::dict dict) { 52 for (auto item : dict) 53 py::print("key: {}, value={}"_s.format(item.first, item.second)); 54 }); 55 m.def("dict_keyword_constructor", []() { 56 auto d1 = py::dict("x"_a=1, "y"_a=2); 57 auto d2 = py::dict("z"_a=3, **d1); 58 return d2; 59 }); 60 m.def("dict_contains", [](py::dict dict, py::object val) { 61 return dict.contains(val); 62 }); 63 m.def("dict_contains", [](py::dict dict, const char* val) { 64 return dict.contains(val); 65 }); 66 67 // test_str 68 m.def("str_from_string", []() { return py::str(std::string("baz")); }); 69 m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); }); 70 m.def("str_from_object", [](const py::object& obj) { return py::str(obj); }); 71 m.def("repr_from_object", [](const py::object& obj) { return py::repr(obj); }); 72 73 m.def("str_format", []() { 74 auto s1 = "{} + {} = {}"_s.format(1, 2, 3); 75 auto s2 = "{a} + {b} = {c}"_s.format("a"_a=1, "b"_a=2, "c"_a=3); 76 return py::make_tuple(s1, s2); 77 }); 78 79 // test_bytes 80 m.def("bytes_from_string", []() { return py::bytes(std::string("foo")); }); 81 m.def("bytes_from_str", []() { return py::bytes(py::str("bar", 3)); }); 82 83 // test_capsule 84 m.def("return_capsule_with_destructor", []() { 85 py::print("creating capsule"); 86 return py::capsule([]() { 87 py::print("destructing capsule"); 88 }); 89 }); 90 91 m.def("return_capsule_with_destructor_2", []() { 92 py::print("creating capsule"); 93 return py::capsule((void *) 1234, [](void *ptr) { 94 py::print("destructing capsule: {}"_s.format((size_t) ptr)); 95 }); 96 }); 97 98 m.def("return_capsule_with_name_and_destructor", []() { 99 auto capsule = py::capsule((void *) 1234, "pointer type description", [](PyObject *ptr) { 100 if (ptr) { 101 auto name = PyCapsule_GetName(ptr); 102 py::print("destructing capsule ({}, '{}')"_s.format( 103 (size_t) PyCapsule_GetPointer(ptr, name), name 104 )); 105 } 106 }); 107 void *contents = capsule; 108 py::print("created capsule ({}, '{}')"_s.format((size_t) contents, capsule.name())); 109 return capsule; 110 }); 111 112 // test_accessors 113 m.def("accessor_api", [](py::object o) { 114 auto d = py::dict(); 115 116 d["basic_attr"] = o.attr("basic_attr"); 117 118 auto l = py::list(); 119 for (const auto &item : o.attr("begin_end")) { 120 l.append(item); 121 } 122 d["begin_end"] = l; 123 124 d["operator[object]"] = o.attr("d")["operator[object]"_s]; 125 d["operator[char *]"] = o.attr("d")["operator[char *]"]; 126 127 d["attr(object)"] = o.attr("sub").attr("attr_obj"); 128 d["attr(char *)"] = o.attr("sub").attr("attr_char"); 129 try { 130 o.attr("sub").attr("missing").ptr(); 131 } catch (const py::error_already_set &) { 132 d["missing_attr_ptr"] = "raised"_s; 133 } 134 try { 135 o.attr("missing").attr("doesn't matter"); 136 } catch (const py::error_already_set &) { 137 d["missing_attr_chain"] = "raised"_s; 138 } 139 140 d["is_none"] = o.attr("basic_attr").is_none(); 141 142 d["operator()"] = o.attr("func")(1); 143 d["operator*"] = o.attr("func")(*o.attr("begin_end")); 144 145 // Test implicit conversion 146 py::list implicit_list = o.attr("begin_end"); 147 d["implicit_list"] = implicit_list; 148 py::dict implicit_dict = o.attr("__dict__"); 149 d["implicit_dict"] = implicit_dict; 150 151 return d; 152 }); 153 154 m.def("tuple_accessor", [](py::tuple existing_t) { 155 try { 156 existing_t[0] = 1; 157 } catch (const py::error_already_set &) { 158 // --> Python system error 159 // Only new tuples (refcount == 1) are mutable 160 auto new_t = py::tuple(3); 161 for (size_t i = 0; i < new_t.size(); ++i) { 162 new_t[i] = i; 163 } 164 return new_t; 165 } 166 return py::tuple(); 167 }); 168 169 m.def("accessor_assignment", []() { 170 auto l = py::list(1); 171 l[0] = 0; 172 173 auto d = py::dict(); 174 d["get"] = l[0]; 175 auto var = l[0]; 176 d["deferred_get"] = var; 177 l[0] = 1; 178 d["set"] = l[0]; 179 var = 99; // this assignment should not overwrite l[0] 180 d["deferred_set"] = l[0]; 181 d["var"] = var; 182 183 return d; 184 }); 185 186 // test_constructors 187 m.def("default_constructors", []() { 188 return py::dict( 189 "str"_a=py::str(), 190 "bool"_a=py::bool_(), 191 "int"_a=py::int_(), 192 "float"_a=py::float_(), 193 "tuple"_a=py::tuple(), 194 "list"_a=py::list(), 195 "dict"_a=py::dict(), 196 "set"_a=py::set() 197 ); 198 }); 199 200 m.def("converting_constructors", [](py::dict d) { 201 return py::dict( 202 "str"_a=py::str(d["str"]), 203 "bool"_a=py::bool_(d["bool"]), 204 "int"_a=py::int_(d["int"]), 205 "float"_a=py::float_(d["float"]), 206 "tuple"_a=py::tuple(d["tuple"]), 207 "list"_a=py::list(d["list"]), 208 "dict"_a=py::dict(d["dict"]), 209 "set"_a=py::set(d["set"]), 210 "memoryview"_a=py::memoryview(d["memoryview"]) 211 ); 212 }); 213 214 m.def("cast_functions", [](py::dict d) { 215 // When converting between Python types, obj.cast<T>() should be the same as T(obj) 216 return py::dict( 217 "str"_a=d["str"].cast<py::str>(), 218 "bool"_a=d["bool"].cast<py::bool_>(), 219 "int"_a=d["int"].cast<py::int_>(), 220 "float"_a=d["float"].cast<py::float_>(), 221 "tuple"_a=d["tuple"].cast<py::tuple>(), 222 "list"_a=d["list"].cast<py::list>(), 223 "dict"_a=d["dict"].cast<py::dict>(), 224 "set"_a=d["set"].cast<py::set>(), 225 "memoryview"_a=d["memoryview"].cast<py::memoryview>() 226 ); 227 }); 228 229 m.def("get_implicit_casting", []() { 230 py::dict d; 231 d["char*_i1"] = "abc"; 232 const char *c2 = "abc"; 233 d["char*_i2"] = c2; 234 d["char*_e"] = py::cast(c2); 235 d["char*_p"] = py::str(c2); 236 237 d["int_i1"] = 42; 238 int i = 42; 239 d["int_i2"] = i; 240 i++; 241 d["int_e"] = py::cast(i); 242 i++; 243 d["int_p"] = py::int_(i); 244 245 d["str_i1"] = std::string("str"); 246 std::string s2("str1"); 247 d["str_i2"] = s2; 248 s2[3] = '2'; 249 d["str_e"] = py::cast(s2); 250 s2[3] = '3'; 251 d["str_p"] = py::str(s2); 252 253 py::list l(2); 254 l[0] = 3; 255 l[1] = py::cast(6); 256 l.append(9); 257 l.append(py::cast(12)); 258 l.append(py::int_(15)); 259 260 return py::dict( 261 "d"_a=d, 262 "l"_a=l 263 ); 264 }); 265 266 // test_print 267 m.def("print_function", []() { 268 py::print("Hello, World!"); 269 py::print(1, 2.0, "three", true, std::string("-- multiple args")); 270 auto args = py::make_tuple("and", "a", "custom", "separator"); 271 py::print("*args", *args, "sep"_a="-"); 272 py::print("no new line here", "end"_a=" -- "); 273 py::print("next print"); 274 275 auto py_stderr = py::module::import("sys").attr("stderr"); 276 py::print("this goes to stderr", "file"_a=py_stderr); 277 278 py::print("flush", "flush"_a=true); 279 280 py::print("{a} + {b} = {c}"_s.format("a"_a="py::print", "b"_a="str.format", "c"_a="this")); 281 }); 282 283 m.def("print_failure", []() { py::print(42, UnregisteredType()); }); 284 285 m.def("hash_function", [](py::object obj) { return py::hash(obj); }); 286 287 m.def("test_number_protocol", [](py::object a, py::object b) { 288 py::list l; 289 l.append(a.equal(b)); 290 l.append(a.not_equal(b)); 291 l.append(a < b); 292 l.append(a <= b); 293 l.append(a > b); 294 l.append(a >= b); 295 l.append(a + b); 296 l.append(a - b); 297 l.append(a * b); 298 l.append(a / b); 299 l.append(a | b); 300 l.append(a & b); 301 l.append(a ^ b); 302 l.append(a >> b); 303 l.append(a << b); 304 return l; 305 }); 306 307 m.def("test_list_slicing", [](py::list a) { 308 return a[py::slice(0, -1, 2)]; 309 }); 310} 311