blob: edc1e995c44f4f33ddc7d0a20400b673aafddd6d [file] [log] [blame]
Dean Moldovan83e328f2017-06-09 00:44:49 +02001/*
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 return d;
132 });
133
134 m.def("tuple_accessor", [](py::tuple existing_t) {
135 try {
136 existing_t[0] = 1;
137 } catch (const py::error_already_set &) {
138 // --> Python system error
139 // Only new tuples (refcount == 1) are mutable
140 auto new_t = py::tuple(3);
141 for (size_t i = 0; i < new_t.size(); ++i) {
142 new_t[i] = i;
143 }
144 return new_t;
145 }
146 return py::tuple();
147 });
148
149 m.def("accessor_assignment", []() {
150 auto l = py::list(1);
151 l[0] = 0;
152
153 auto d = py::dict();
154 d["get"] = l[0];
155 auto var = l[0];
156 d["deferred_get"] = var;
157 l[0] = 1;
158 d["set"] = l[0];
159 var = 99; // this assignment should not overwrite l[0]
160 d["deferred_set"] = l[0];
161 d["var"] = var;
162
163 return d;
164 });
165
166 // test_constructors
167 m.def("default_constructors", []() {
168 return py::dict(
169 "str"_a=py::str(),
170 "bool"_a=py::bool_(),
171 "int"_a=py::int_(),
172 "float"_a=py::float_(),
173 "tuple"_a=py::tuple(),
174 "list"_a=py::list(),
175 "dict"_a=py::dict(),
176 "set"_a=py::set()
177 );
178 });
179
180 m.def("converting_constructors", [](py::dict d) {
181 return py::dict(
182 "str"_a=py::str(d["str"]),
183 "bool"_a=py::bool_(d["bool"]),
184 "int"_a=py::int_(d["int"]),
185 "float"_a=py::float_(d["float"]),
186 "tuple"_a=py::tuple(d["tuple"]),
187 "list"_a=py::list(d["list"]),
188 "dict"_a=py::dict(d["dict"]),
189 "set"_a=py::set(d["set"]),
190 "memoryview"_a=py::memoryview(d["memoryview"])
191 );
192 });
193
194 m.def("cast_functions", [](py::dict d) {
195 // When converting between Python types, obj.cast<T>() should be the same as T(obj)
196 return py::dict(
197 "str"_a=d["str"].cast<py::str>(),
198 "bool"_a=d["bool"].cast<py::bool_>(),
199 "int"_a=d["int"].cast<py::int_>(),
200 "float"_a=d["float"].cast<py::float_>(),
201 "tuple"_a=d["tuple"].cast<py::tuple>(),
202 "list"_a=d["list"].cast<py::list>(),
203 "dict"_a=d["dict"].cast<py::dict>(),
204 "set"_a=d["set"].cast<py::set>(),
205 "memoryview"_a=d["memoryview"].cast<py::memoryview>()
206 );
207 });
208
209 m.def("get_implicit_casting", []() {
210 py::dict d;
211 d["char*_i1"] = "abc";
212 const char *c2 = "abc";
213 d["char*_i2"] = c2;
214 d["char*_e"] = py::cast(c2);
215 d["char*_p"] = py::str(c2);
216
217 d["int_i1"] = 42;
218 int i = 42;
219 d["int_i2"] = i;
220 i++;
221 d["int_e"] = py::cast(i);
222 i++;
223 d["int_p"] = py::int_(i);
224
225 d["str_i1"] = std::string("str");
226 std::string s2("str1");
227 d["str_i2"] = s2;
228 s2[3] = '2';
229 d["str_e"] = py::cast(s2);
230 s2[3] = '3';
231 d["str_p"] = py::str(s2);
232
233 py::list l(2);
234 l[0] = 3;
235 l[1] = py::cast(6);
236 l.append(9);
237 l.append(py::cast(12));
238 l.append(py::int_(15));
239
240 return py::dict(
241 "d"_a=d,
242 "l"_a=l
243 );
244 });
245
246 // test_print
247 m.def("print_function", []() {
248 py::print("Hello, World!");
249 py::print(1, 2.0, "three", true, std::string("-- multiple args"));
250 auto args = py::make_tuple("and", "a", "custom", "separator");
251 py::print("*args", *args, "sep"_a="-");
252 py::print("no new line here", "end"_a=" -- ");
253 py::print("next print");
254
255 auto py_stderr = py::module::import("sys").attr("stderr");
256 py::print("this goes to stderr", "file"_a=py_stderr);
257
258 py::print("flush", "flush"_a=true);
259
260 py::print("{a} + {b} = {c}"_s.format("a"_a="py::print", "b"_a="str.format", "c"_a="this"));
261 });
262
263 m.def("print_failure", []() { py::print(42, UnregisteredType()); });
264}