blob: 81b665b4d0d4f038c357ec4d71de82db5d0428bd [file] [log] [blame]
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -04001/*
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002 tests/test_methods_and_attributes.cpp -- constructors, deconstructors, attribute access,
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -04003 __str__, argument and return value conventions
4
5 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
7 All rights reserved. Use of this source code is governed by a
8 BSD-style license that can be found in the LICENSE file.
9*/
10
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020011#include "pybind11_tests.h"
12#include "constructor_stats.h"
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -040013
14class ExampleMandA {
15public:
Jason Rhinelander3f589372016-08-07 13:05:26 -040016 ExampleMandA() { print_default_created(this); }
17 ExampleMandA(int value) : value(value) { print_created(this, value); }
18 ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); }
19 ExampleMandA(ExampleMandA &&e) : value(e.value) { print_move_created(this); }
20 ~ExampleMandA() { print_destroyed(this); }
21
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -040022 std::string toString() {
23 return "ExampleMandA[value=" + std::to_string(value) + "]";
24 }
25
Jason Rhinelander3f589372016-08-07 13:05:26 -040026 void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; }
27 void operator=(ExampleMandA &&e) { print_move_assigned(this); value = e.value; }
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -040028
29 void add1(ExampleMandA other) { value += other.value; } // passing by value
30 void add2(ExampleMandA &other) { value += other.value; } // passing by reference
31 void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference
32 void add4(ExampleMandA *other) { value += other->value; } // passing by pointer
33 void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer
34
35 void add6(int other) { value += other; } // passing by value
36 void add7(int &other) { value += other; } // passing by reference
37 void add8(const int &other) { value += other; } // passing by const reference
38 void add9(int *other) { value += *other; } // passing by pointer
39 void add10(const int *other) { value += *other; } // passing by const pointer
40
41 ExampleMandA self1() { return *this; } // return by value
42 ExampleMandA &self2() { return *this; } // return by reference
43 const ExampleMandA &self3() { return *this; } // return by const reference
44 ExampleMandA *self4() { return this; } // return by pointer
45 const ExampleMandA *self5() { return this; } // return by const pointer
46
47 int internal1() { return value; } // return by value
48 int &internal2() { return value; } // return by reference
49 const int &internal3() { return value; } // return by const reference
50 int *internal4() { return &value; } // return by pointer
51 const int *internal5() { return &value; } // return by const pointer
52
Jason Rhinelandere5505892017-02-03 18:25:34 -050053 py::str overloaded(int, float) { return "(int, float)"; }
54 py::str overloaded(float, int) { return "(float, int)"; }
55 py::str overloaded(int, int) { return "(int, int)"; }
56 py::str overloaded(float, float) { return "(float, float)"; }
57 py::str overloaded(int, float) const { return "(int, float) const"; }
58 py::str overloaded(float, int) const { return "(float, int) const"; }
59 py::str overloaded(int, int) const { return "(int, int) const"; }
60 py::str overloaded(float, float) const { return "(float, float) const"; }
Dean Moldovan4e959c92016-12-08 11:07:52 +010061
Jason Rhinelanderd355f2f2017-04-16 22:31:13 -040062 static py::str overloaded() { return "static"; }
63
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -040064 int value = 0;
65};
66
Dean Moldovan5b7e1902016-10-21 18:51:14 +020067struct TestProperties {
68 int value = 1;
69 static int static_value;
70
71 int get() const { return value; }
72 void set(int v) { value = v; }
73
74 static int static_get() { return static_value; }
75 static void static_set(int v) { static_value = v; }
76};
77
78int TestProperties::static_value = 1;
79
Dean Moldovane0e2ea32017-04-06 23:45:12 +020080struct TestPropertiesOverride : TestProperties {
81 int value = 99;
82 static int static_value;
83};
84
85int TestPropertiesOverride::static_value = 99;
86
Dean Moldovan03f627e2016-11-01 11:44:57 +010087struct SimpleValue { int value = 1; };
88
89struct TestPropRVP {
90 SimpleValue v1;
91 SimpleValue v2;
92 static SimpleValue sv1;
93 static SimpleValue sv2;
94
95 const SimpleValue &get1() const { return v1; }
96 const SimpleValue &get2() const { return v2; }
97 SimpleValue get_rvalue() const { return v2; }
98 void set1(int v) { v1.value = v; }
99 void set2(int v) { v2.value = v; }
100};
101
102SimpleValue TestPropRVP::sv1{};
103SimpleValue TestPropRVP::sv2{};
104
Dean Moldovan6fccf692016-10-11 01:12:48 +0200105class DynamicClass {
106public:
107 DynamicClass() { print_default_created(this); }
108 ~DynamicClass() { print_destroyed(this); }
109};
110
Dean Moldovanb8cb5ca2016-10-14 18:01:17 +0200111class CppDerivedDynamicClass : public DynamicClass { };
112
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500113// py::arg/py::arg_v testing: these arguments just record their argument when invoked
114class ArgInspector1 { public: std::string arg = "(default arg inspector 1)"; };
115class ArgInspector2 { public: std::string arg = "(default arg inspector 2)"; };
Jason Rhinelandere5505892017-02-03 18:25:34 -0500116class ArgAlwaysConverts { };
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500117namespace pybind11 { namespace detail {
118template <> struct type_caster<ArgInspector1> {
119public:
120 PYBIND11_TYPE_CASTER(ArgInspector1, _("ArgInspector1"));
121
122 bool load(handle src, bool convert) {
123 value.arg = "loading ArgInspector1 argument " +
124 std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. "
125 "Argument value = " + (std::string) str(src);
126 return true;
127 }
128
129 static handle cast(const ArgInspector1 &src, return_value_policy, handle) {
130 return str(src.arg).release();
131 }
132};
133template <> struct type_caster<ArgInspector2> {
134public:
135 PYBIND11_TYPE_CASTER(ArgInspector2, _("ArgInspector2"));
136
137 bool load(handle src, bool convert) {
138 value.arg = "loading ArgInspector2 argument " +
139 std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. "
140 "Argument value = " + (std::string) str(src);
141 return true;
142 }
143
144 static handle cast(const ArgInspector2 &src, return_value_policy, handle) {
145 return str(src.arg).release();
146 }
147};
Jason Rhinelandere5505892017-02-03 18:25:34 -0500148template <> struct type_caster<ArgAlwaysConverts> {
149public:
150 PYBIND11_TYPE_CASTER(ArgAlwaysConverts, _("ArgAlwaysConverts"));
151
152 bool load(handle, bool convert) {
153 return convert;
154 }
155
156 static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) {
157 return py::none();
158 }
159};
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500160}}
161
Jason Rhinelander1eaacd12017-02-08 02:45:51 -0500162/// Issue/PR #648: bad arg default debugging output
163class NotRegistered {};
164
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400165// Test None-allowed py::arg argument policy
166class NoneTester { public: int answer = 42; };
167int none1(const NoneTester &obj) { return obj.answer; }
168int none2(NoneTester *obj) { return obj ? obj->answer : -1; }
169int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
170int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; }
171int none5(std::shared_ptr<NoneTester> obj) { return obj ? obj->answer : -1; }
172
Jason Rhinelander52f4be82016-09-03 14:54:22 -0400173test_initializer methods_and_attributes([](py::module &m) {
Jason Rhinelander0a90b2d2017-04-16 20:30:52 -0400174 py::class_<ExampleMandA> emna(m, "ExampleMandA");
175 emna.def(py::init<>())
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -0400176 .def(py::init<int>())
177 .def(py::init<const ExampleMandA&>())
178 .def("add1", &ExampleMandA::add1)
179 .def("add2", &ExampleMandA::add2)
180 .def("add3", &ExampleMandA::add3)
181 .def("add4", &ExampleMandA::add4)
182 .def("add5", &ExampleMandA::add5)
183 .def("add6", &ExampleMandA::add6)
184 .def("add7", &ExampleMandA::add7)
185 .def("add8", &ExampleMandA::add8)
186 .def("add9", &ExampleMandA::add9)
187 .def("add10", &ExampleMandA::add10)
188 .def("self1", &ExampleMandA::self1)
189 .def("self2", &ExampleMandA::self2)
190 .def("self3", &ExampleMandA::self3)
191 .def("self4", &ExampleMandA::self4)
192 .def("self5", &ExampleMandA::self5)
193 .def("internal1", &ExampleMandA::internal1)
194 .def("internal2", &ExampleMandA::internal2)
195 .def("internal3", &ExampleMandA::internal3)
196 .def("internal4", &ExampleMandA::internal4)
197 .def("internal5", &ExampleMandA::internal5)
Dean Moldovan4e959c92016-12-08 11:07:52 +0100198#if defined(PYBIND11_OVERLOAD_CAST)
Jason Rhinelandere5505892017-02-03 18:25:34 -0500199 .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded))
200 .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded))
201 .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded))
202 .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded))
203 .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded))
204 .def("overloaded_const", py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_))
205 .def("overloaded_const", py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_))
206 .def("overloaded_const", py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_))
207 .def("overloaded_const", py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))
Dean Moldovan4e959c92016-12-08 11:07:52 +0100208#else
Jason Rhinelandere5505892017-02-03 18:25:34 -0500209 .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, float)>(&ExampleMandA::overloaded))
210 .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, int)>(&ExampleMandA::overloaded))
211 .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
212 .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
213 .def("overloaded_float", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
214 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, float) const>(&ExampleMandA::overloaded))
215 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded))
216 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, int) const>(&ExampleMandA::overloaded))
217 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))
Dean Moldovan4e959c92016-12-08 11:07:52 +0100218#endif
Jason Rhinelanderd355f2f2017-04-16 22:31:13 -0400219 // Raise error if trying to mix static/non-static overloads on the same name:
220 .def_static("add_mixed_overloads1", []() {
221 auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module::import("pybind11_tests").attr("ExampleMandA"));
222 emna.def ("overload_mixed1", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
223 .def_static("overload_mixed1", static_cast<py::str ( *)( )>(&ExampleMandA::overloaded));
224 })
225 .def_static("add_mixed_overloads2", []() {
226 auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module::import("pybind11_tests").attr("ExampleMandA"));
227 emna.def_static("overload_mixed2", static_cast<py::str ( *)( )>(&ExampleMandA::overloaded))
228 .def ("overload_mixed2", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded));
229 })
Jason Rhinelanderb3f3d792016-07-18 16:43:18 -0400230 .def("__str__", &ExampleMandA::toString)
Wenzel Jakob1d1f81b2016-12-16 15:00:46 +0100231 .def_readwrite("value", &ExampleMandA::value);
Dean Moldovan6fccf692016-10-11 01:12:48 +0200232
Jason Rhinelander0a90b2d2017-04-16 20:30:52 -0400233 // Issue #443: can't call copied methods in Python 3
234 emna.attr("add2b") = emna.attr("add2");
235
Dean Moldovandd016652017-02-16 23:02:56 +0100236 py::class_<TestProperties>(m, "TestProperties")
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200237 .def(py::init<>())
238 .def_readonly("def_readonly", &TestProperties::value)
239 .def_readwrite("def_readwrite", &TestProperties::value)
240 .def_property_readonly("def_property_readonly", &TestProperties::get)
241 .def_property("def_property", &TestProperties::get, &TestProperties::set)
242 .def_readonly_static("def_readonly_static", &TestProperties::static_value)
243 .def_readwrite_static("def_readwrite_static", &TestProperties::static_value)
244 .def_property_readonly_static("def_property_readonly_static",
245 [](py::object) { return TestProperties::static_get(); })
246 .def_property_static("def_property_static",
247 [](py::object) { return TestProperties::static_get(); },
Dean Moldovanc91f8bd2017-02-13 18:11:24 +0100248 [](py::object, int v) { TestProperties::static_set(v); })
249 .def_property_static("static_cls",
250 [](py::object cls) { return cls; },
251 [](py::object cls, py::function f) { f(cls); });
Dean Moldovan5b7e1902016-10-21 18:51:14 +0200252
Dean Moldovane0e2ea32017-04-06 23:45:12 +0200253 py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride")
254 .def(py::init<>())
255 .def_readonly("def_readonly", &TestPropertiesOverride::value)
256 .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value);
257
Dean Moldovan03f627e2016-11-01 11:44:57 +0100258 py::class_<SimpleValue>(m, "SimpleValue")
259 .def_readwrite("value", &SimpleValue::value);
260
261 auto static_get1 = [](py::object) -> const SimpleValue & { return TestPropRVP::sv1; };
262 auto static_get2 = [](py::object) -> const SimpleValue & { return TestPropRVP::sv2; };
263 auto static_set1 = [](py::object, int v) { TestPropRVP::sv1.value = v; };
264 auto static_set2 = [](py::object, int v) { TestPropRVP::sv2.value = v; };
265 auto rvp_copy = py::return_value_policy::copy;
266
Dean Moldovandd016652017-02-16 23:02:56 +0100267 py::class_<TestPropRVP>(m, "TestPropRVP")
Dean Moldovan03f627e2016-11-01 11:44:57 +0100268 .def(py::init<>())
269 .def_property_readonly("ro_ref", &TestPropRVP::get1)
270 .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy)
271 .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy))
272 .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1)
273 .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy)
274 .def_property("rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2)
275 .def_property_readonly_static("static_ro_ref", static_get1)
276 .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy)
277 .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy))
278 .def_property_static("static_rw_ref", static_get1, static_set1)
279 .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy)
280 .def_property_static("static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2)
281 .def_property_readonly("rvalue", &TestPropRVP::get_rvalue)
282 .def_property_readonly_static("static_rvalue", [](py::object) { return SimpleValue(); });
283
Dean Moldovandd016652017-02-16 23:02:56 +0100284 struct MetaclassOverride { };
285 py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type))
286 .def_property_readonly_static("readonly", [](py::object) { return 1; });
287
Wenzel Jakob64cb6992016-12-26 13:12:10 +0100288#if !defined(PYPY_VERSION)
Dean Moldovan6fccf692016-10-11 01:12:48 +0200289 py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr())
290 .def(py::init());
Dean Moldovanb8cb5ca2016-10-14 18:01:17 +0200291
292 py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass")
293 .def(py::init());
Wenzel Jakob64cb6992016-12-26 13:12:10 +0100294#endif
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500295
Jason Rhinelandere5505892017-02-03 18:25:34 -0500296 // Test converting. The ArgAlwaysConverts is just there to make the first no-conversion pass
297 // fail so that our call always ends up happening via the second dispatch (the one that allows
298 // some conversion).
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500299 class ArgInspector {
300 public:
Jason Rhinelandere5505892017-02-03 18:25:34 -0500301 ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; }
302 std::string g(ArgInspector1 a, const ArgInspector1 &b, int c, ArgInspector2 *d, ArgAlwaysConverts) {
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500303 return a.arg + "\n" + b.arg + "\n" + std::to_string(c) + "\n" + d->arg;
304 }
Jason Rhinelandere5505892017-02-03 18:25:34 -0500305 static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; }
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500306 };
307 py::class_<ArgInspector>(m, "ArgInspector")
308 .def(py::init<>())
Jason Rhinelandere5505892017-02-03 18:25:34 -0500309 .def("f", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts())
310 .def("g", &ArgInspector::g, "a"_a.noconvert(), "b"_a, "c"_a.noconvert()=13, "d"_a=ArgInspector2(), py::arg() = ArgAlwaysConverts())
311 .def_static("h", &ArgInspector::h, py::arg().noconvert(), py::arg() = ArgAlwaysConverts())
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500312 ;
Jason Rhinelandere5505892017-02-03 18:25:34 -0500313 m.def("arg_inspect_func", [](ArgInspector2 a, ArgInspector1 b, ArgAlwaysConverts) { return a.arg + "\n" + b.arg; },
314 py::arg().noconvert(false), py::arg_v(nullptr, ArgInspector1()).noconvert(true), py::arg() = ArgAlwaysConverts());
Jason Rhinelanderabc29ca2017-01-23 03:50:00 -0500315
316 m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
317 m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
318
Jason Rhinelander1eaacd12017-02-08 02:45:51 -0500319 /// Issue/PR #648: bad arg default debugging output
320#if !defined(NDEBUG)
321 m.attr("debug_enabled") = true;
322#else
323 m.attr("debug_enabled") = false;
324#endif
325 m.def("bad_arg_def_named", []{
Jason Rhinelander2d14c1c2017-04-15 11:12:41 -0400326 auto m = py::module::import("pybind11_tests");
Jason Rhinelander1eaacd12017-02-08 02:45:51 -0500327 m.def("should_fail", [](int, NotRegistered) {}, py::arg(), py::arg("a") = NotRegistered());
328 });
329 m.def("bad_arg_def_unnamed", []{
Jason Rhinelander2d14c1c2017-04-15 11:12:41 -0400330 auto m = py::module::import("pybind11_tests");
Jason Rhinelander1eaacd12017-02-08 02:45:51 -0500331 m.def("should_fail", [](int, NotRegistered) {}, py::arg(), py::arg() = NotRegistered());
332 });
Jason Rhinelander4e1e4a52017-05-17 11:55:43 -0400333
334 py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester")
335 .def(py::init<>());
336 m.def("no_none1", &none1, py::arg().none(false));
337 m.def("no_none2", &none2, py::arg().none(false));
338 m.def("no_none3", &none3, py::arg().none(false));
339 m.def("no_none4", &none4, py::arg().none(false));
340 m.def("no_none5", &none5, py::arg().none(false));
341 m.def("ok_none1", &none1);
342 m.def("ok_none2", &none2, py::arg().none(true));
343 m.def("ok_none3", &none3);
344 m.def("ok_none4", &none4, py::arg().none(true));
345 m.def("ok_none5", &none5);
346
Jason Rhinelander52f4be82016-09-03 14:54:22 -0400347});