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