1 /*
2 tests/test_methods_and_attributes.cpp -- constructors, deconstructors, attribute access,
3 __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
11 #include "pybind11_tests.h"
12 #include "constructor_stats.h"
13
14 #if !defined(PYBIND11_OVERLOAD_CAST)
15 template <typename... Args>
16 using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
17 #endif
18
19 class ExampleMandA {
20 public:
ExampleMandA()21 ExampleMandA() { print_default_created(this); }
ExampleMandA(int value)22 ExampleMandA(int value) : value(value) { print_created(this, value); }
ExampleMandA(const ExampleMandA & e)23 ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); }
ExampleMandA(std::string &&)24 ExampleMandA(std::string&&) {}
ExampleMandA(ExampleMandA && e)25 ExampleMandA(ExampleMandA &&e) : value(e.value) { print_move_created(this); }
~ExampleMandA()26 ~ExampleMandA() { print_destroyed(this); }
27
toString()28 std::string toString() {
29 return "ExampleMandA[value=" + std::to_string(value) + "]";
30 }
31
operator =(const ExampleMandA & e)32 void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; }
operator =(ExampleMandA && e)33 void operator=(ExampleMandA &&e) { print_move_assigned(this); value = e.value; }
34
add1(ExampleMandA other)35 void add1(ExampleMandA other) { value += other.value; } // passing by value
add2(ExampleMandA & other)36 void add2(ExampleMandA &other) { value += other.value; } // passing by reference
add3(const ExampleMandA & other)37 void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference
add4(ExampleMandA * other)38 void add4(ExampleMandA *other) { value += other->value; } // passing by pointer
add5(const ExampleMandA * other)39 void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer
40
add6(int other)41 void add6(int other) { value += other; } // passing by value
add7(int & other)42 void add7(int &other) { value += other; } // passing by reference
add8(const int & other)43 void add8(const int &other) { value += other; } // passing by const reference
add9(int * other)44 void add9(int *other) { value += *other; } // passing by pointer
add10(const int * other)45 void add10(const int *other) { value += *other; } // passing by const pointer
46
consume_str(std::string &&)47 void consume_str(std::string&&) {}
48
self1()49 ExampleMandA self1() { return *this; } // return by value
self2()50 ExampleMandA &self2() { return *this; } // return by reference
self3()51 const ExampleMandA &self3() { return *this; } // return by const reference
self4()52 ExampleMandA *self4() { return this; } // return by pointer
self5()53 const ExampleMandA *self5() { return this; } // return by const pointer
54
internal1()55 int internal1() { return value; } // return by value
internal2()56 int &internal2() { return value; } // return by reference
internal3()57 const int &internal3() { return value; } // return by const reference
internal4()58 int *internal4() { return &value; } // return by pointer
internal5()59 const int *internal5() { return &value; } // return by const pointer
60
overloaded()61 py::str overloaded() { return "()"; }
overloaded(int)62 py::str overloaded(int) { return "(int)"; }
overloaded(int,float)63 py::str overloaded(int, float) { return "(int, float)"; }
overloaded(float,int)64 py::str overloaded(float, int) { return "(float, int)"; }
overloaded(int,int)65 py::str overloaded(int, int) { return "(int, int)"; }
overloaded(float,float)66 py::str overloaded(float, float) { return "(float, float)"; }
overloaded(int) const67 py::str overloaded(int) const { return "(int) const"; }
overloaded(int,float) const68 py::str overloaded(int, float) const { return "(int, float) const"; }
overloaded(float,int) const69 py::str overloaded(float, int) const { return "(float, int) const"; }
overloaded(int,int) const70 py::str overloaded(int, int) const { return "(int, int) const"; }
overloaded(float,float) const71 py::str overloaded(float, float) const { return "(float, float) const"; }
72
overloaded(float)73 static py::str overloaded(float) { return "static float"; }
74
75 int value = 0;
76 };
77
78 struct TestProperties {
79 int value = 1;
80 static int static_value;
81
getTestProperties82 int get() const { return value; }
setTestProperties83 void set(int v) { value = v; }
84
static_getTestProperties85 static int static_get() { return static_value; }
static_setTestProperties86 static void static_set(int v) { static_value = v; }
87 };
88 int TestProperties::static_value = 1;
89
90 struct TestPropertiesOverride : TestProperties {
91 int value = 99;
92 static int static_value;
93 };
94 int TestPropertiesOverride::static_value = 99;
95
96 struct TestPropRVP {
97 UserType v1{1};
98 UserType v2{1};
99 static UserType sv1;
100 static UserType sv2;
101
get1TestPropRVP102 const UserType &get1() const { return v1; }
get2TestPropRVP103 const UserType &get2() const { return v2; }
get_rvalueTestPropRVP104 UserType get_rvalue() const { return v2; }
set1TestPropRVP105 void set1(int v) { v1.set(v); }
set2TestPropRVP106 void set2(int v) { v2.set(v); }
107 };
108 UserType TestPropRVP::sv1(1);
109 UserType TestPropRVP::sv2(1);
110
111 // Test None-allowed py::arg argument policy
112 class NoneTester { public: int answer = 42; };
none1(const NoneTester & obj)113 int none1(const NoneTester &obj) { return obj.answer; }
none2(NoneTester * obj)114 int none2(NoneTester *obj) { return obj ? obj->answer : -1; }
none3(std::shared_ptr<NoneTester> & obj)115 int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
none4(std::shared_ptr<NoneTester> * obj)116 int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; }
none5(std::shared_ptr<NoneTester> obj)117 int none5(std::shared_ptr<NoneTester> obj) { return obj ? obj->answer : -1; }
118
119 struct StrIssue {
120 int val = -1;
121
122 StrIssue() = default;
StrIssueStrIssue123 StrIssue(int i) : val{i} {}
124 };
125
126 // Issues #854, #910: incompatible function args when member function/pointer is in unregistered base class
127 class UnregisteredBase {
128 public:
do_nothing() const129 void do_nothing() const {}
increase_value()130 void increase_value() { rw_value++; ro_value += 0.25; }
set_int(int v)131 void set_int(int v) { rw_value = v; }
get_int() const132 int get_int() const { return rw_value; }
get_double() const133 double get_double() const { return ro_value; }
134 int rw_value = 42;
135 double ro_value = 1.25;
136 };
137 class RegisteredDerived : public UnregisteredBase {
138 public:
139 using UnregisteredBase::UnregisteredBase;
sum() const140 double sum() const { return rw_value + ro_value; }
141 };
142
143 // Test explicit lvalue ref-qualification
144 struct RefQualified {
145 int value = 0;
146
refQualifiedRefQualified147 void refQualified(int other) & { value += other; }
constRefQualifiedRefQualified148 int constRefQualified(int other) const & { return value + other; }
149 };
150
TEST_SUBMODULE(methods_and_attributes,m)151 TEST_SUBMODULE(methods_and_attributes, m) {
152 // test_methods_and_attributes
153 py::class_<ExampleMandA> emna(m, "ExampleMandA");
154 emna.def(py::init<>())
155 .def(py::init<int>())
156 .def(py::init<std::string&&>())
157 .def(py::init<const ExampleMandA&>())
158 .def("add1", &ExampleMandA::add1)
159 .def("add2", &ExampleMandA::add2)
160 .def("add3", &ExampleMandA::add3)
161 .def("add4", &ExampleMandA::add4)
162 .def("add5", &ExampleMandA::add5)
163 .def("add6", &ExampleMandA::add6)
164 .def("add7", &ExampleMandA::add7)
165 .def("add8", &ExampleMandA::add8)
166 .def("add9", &ExampleMandA::add9)
167 .def("add10", &ExampleMandA::add10)
168 .def("consume_str", &ExampleMandA::consume_str)
169 .def("self1", &ExampleMandA::self1)
170 .def("self2", &ExampleMandA::self2)
171 .def("self3", &ExampleMandA::self3)
172 .def("self4", &ExampleMandA::self4)
173 .def("self5", &ExampleMandA::self5)
174 .def("internal1", &ExampleMandA::internal1)
175 .def("internal2", &ExampleMandA::internal2)
176 .def("internal3", &ExampleMandA::internal3)
177 .def("internal4", &ExampleMandA::internal4)
178 .def("internal5", &ExampleMandA::internal5)
179 #if defined(PYBIND11_OVERLOAD_CAST)
180 .def("overloaded", py::overload_cast<>(&ExampleMandA::overloaded))
181 .def("overloaded", py::overload_cast<int>(&ExampleMandA::overloaded))
182 .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded))
183 .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded))
184 .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded))
185 .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded))
186 .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded))
187 .def("overloaded_const", py::overload_cast<int >(&ExampleMandA::overloaded, py::const_))
188 .def("overloaded_const", py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_))
189 .def("overloaded_const", py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_))
190 .def("overloaded_const", py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_))
191 .def("overloaded_const", py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))
192 #else
193 // Use both the traditional static_cast method and the C++11 compatible overload_cast_
194 .def("overloaded", overload_cast_<>()(&ExampleMandA::overloaded))
195 .def("overloaded", overload_cast_<int>()(&ExampleMandA::overloaded))
196 .def("overloaded", overload_cast_<int, float>()(&ExampleMandA::overloaded))
197 .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, int)>(&ExampleMandA::overloaded))
198 .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
199 .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
200 .def("overloaded_float", overload_cast_<float, float>()(&ExampleMandA::overloaded))
201 .def("overloaded_const", overload_cast_<int >()(&ExampleMandA::overloaded, py::const_))
202 .def("overloaded_const", overload_cast_<int, float>()(&ExampleMandA::overloaded, py::const_))
203 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded))
204 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, int) const>(&ExampleMandA::overloaded))
205 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))
206 #endif
207 // test_no_mixed_overloads
208 // Raise error if trying to mix static/non-static overloads on the same name:
209 .def_static("add_mixed_overloads1", []() {
210 auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module_::import("pybind11_tests.methods_and_attributes").attr("ExampleMandA"));
211 emna.def ("overload_mixed1", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
212 .def_static("overload_mixed1", static_cast<py::str ( *)(float )>(&ExampleMandA::overloaded));
213 })
214 .def_static("add_mixed_overloads2", []() {
215 auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module_::import("pybind11_tests.methods_and_attributes").attr("ExampleMandA"));
216 emna.def_static("overload_mixed2", static_cast<py::str ( *)(float )>(&ExampleMandA::overloaded))
217 .def ("overload_mixed2", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded));
218 })
219 .def("__str__", &ExampleMandA::toString)
220 .def_readwrite("value", &ExampleMandA::value);
221
222 // test_copy_method
223 // Issue #443: can't call copied methods in Python 3
224 emna.attr("add2b") = emna.attr("add2");
225
226 // test_properties, test_static_properties, test_static_cls
227 py::class_<TestProperties>(m, "TestProperties")
228 .def(py::init<>())
229 .def_readonly("def_readonly", &TestProperties::value)
230 .def_readwrite("def_readwrite", &TestProperties::value)
231 .def_property("def_writeonly", nullptr,
232 [](TestProperties& s,int v) { s.value = v; } )
233 .def_property("def_property_writeonly", nullptr, &TestProperties::set)
234 .def_property_readonly("def_property_readonly", &TestProperties::get)
235 .def_property("def_property", &TestProperties::get, &TestProperties::set)
236 .def_property("def_property_impossible", nullptr, nullptr)
237 .def_readonly_static("def_readonly_static", &TestProperties::static_value)
238 .def_readwrite_static("def_readwrite_static", &TestProperties::static_value)
239 .def_property_static("def_writeonly_static", nullptr,
240 [](py::object, int v) { TestProperties::static_value = v; })
241 .def_property_readonly_static("def_property_readonly_static",
242 [](py::object) { return TestProperties::static_get(); })
243 .def_property_static("def_property_writeonly_static", nullptr,
244 [](py::object, int v) { return TestProperties::static_set(v); })
245 .def_property_static("def_property_static",
246 [](py::object) { return TestProperties::static_get(); },
247 [](py::object, int v) { TestProperties::static_set(v); })
248 .def_property_static("static_cls",
249 [](py::object cls) { return cls; },
250 [](py::object cls, py::function f) { f(cls); });
251
252 py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride")
253 .def(py::init<>())
254 .def_readonly("def_readonly", &TestPropertiesOverride::value)
255 .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value);
256
257 auto static_get1 = [](py::object) -> const UserType & { return TestPropRVP::sv1; };
258 auto static_get2 = [](py::object) -> const UserType & { return TestPropRVP::sv2; };
259 auto static_set1 = [](py::object, int v) { TestPropRVP::sv1.set(v); };
260 auto static_set2 = [](py::object, int v) { TestPropRVP::sv2.set(v); };
261 auto rvp_copy = py::return_value_policy::copy;
262
263 // test_property_return_value_policies
264 py::class_<TestPropRVP>(m, "TestPropRVP")
265 .def(py::init<>())
266 .def_property_readonly("ro_ref", &TestPropRVP::get1)
267 .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy)
268 .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy))
269 .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1)
270 .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy)
271 .def_property("rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2)
272 .def_property_readonly_static("static_ro_ref", static_get1)
273 .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy)
274 .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy))
275 .def_property_static("static_rw_ref", static_get1, static_set1)
276 .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy)
277 .def_property_static("static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2)
278 // test_property_rvalue_policy
279 .def_property_readonly("rvalue", &TestPropRVP::get_rvalue)
280 .def_property_readonly_static("static_rvalue", [](py::object) { return UserType(1); });
281
282 // test_metaclass_override
283 struct MetaclassOverride { };
284 py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type))
285 .def_property_readonly_static("readonly", [](py::object) { return 1; });
286
287 // test_overload_ordering
288 m.def("overload_order", [](std::string) { return 1; });
289 m.def("overload_order", [](std::string) { return 2; });
290 m.def("overload_order", [](int) { return 3; });
291 m.def("overload_order", [](int) { return 4; }, py::prepend{});
292
293 #if !defined(PYPY_VERSION)
294 // test_dynamic_attributes
295 class DynamicClass {
296 public:
297 DynamicClass() { print_default_created(this); }
298 DynamicClass(const DynamicClass&) = delete;
299 ~DynamicClass() { print_destroyed(this); }
300 };
301 py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr())
302 .def(py::init());
303
304 class CppDerivedDynamicClass : public DynamicClass { };
305 py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass")
306 .def(py::init());
307 #endif
308
309 // test_bad_arg_default
310 // Issue/PR #648: bad arg default debugging output
311 #if !defined(NDEBUG)
312 m.attr("debug_enabled") = true;
313 #else
314 m.attr("debug_enabled") = false;
315 #endif
316 m.def("bad_arg_def_named", []{
317 auto m = py::module_::import("pybind11_tests");
318 m.def("should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg("a") = UnregisteredType());
319 });
320 m.def("bad_arg_def_unnamed", []{
321 auto m = py::module_::import("pybind11_tests");
322 m.def("should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg() = UnregisteredType());
323 });
324
325 // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
326
327 // test_accepts_none
328 py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester")
329 .def(py::init<>());
330 m.def("no_none1", &none1, py::arg{}.none(false));
331 m.def("no_none2", &none2, py::arg{}.none(false));
332 m.def("no_none3", &none3, py::arg{}.none(false));
333 m.def("no_none4", &none4, py::arg{}.none(false));
334 m.def("no_none5", &none5, py::arg{}.none(false));
335 m.def("ok_none1", &none1);
336 m.def("ok_none2", &none2, py::arg{}.none(true));
337 m.def("ok_none3", &none3);
338 m.def("ok_none4", &none4, py::arg{}.none(true));
339 m.def("ok_none5", &none5);
340
341 m.def("no_none_kwarg", &none2, "a"_a.none(false));
342 m.def("no_none_kwarg_kw_only", &none2, py::kw_only(), "a"_a.none(false));
343
344 // test_str_issue
345 // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
346 py::class_<StrIssue>(m, "StrIssue")
347 .def(py::init<int>())
348 .def(py::init<>())
349 .def("__str__", [](const StrIssue &si) {
350 return "StrIssue[" + std::to_string(si.val) + "]"; }
351 );
352
353 // test_unregistered_base_implementations
354 //
355 // Issues #854/910: incompatible function args when member function/pointer is in unregistered
356 // base class The methods and member pointers below actually resolve to members/pointers in
357 // UnregisteredBase; before this test/fix they would be registered via lambda with a first
358 // argument of an unregistered type, and thus uncallable.
359 py::class_<RegisteredDerived>(m, "RegisteredDerived")
360 .def(py::init<>())
361 .def("do_nothing", &RegisteredDerived::do_nothing)
362 .def("increase_value", &RegisteredDerived::increase_value)
363 .def_readwrite("rw_value", &RegisteredDerived::rw_value)
364 .def_readonly("ro_value", &RegisteredDerived::ro_value)
365 // These should trigger a static_assert if uncommented
366 //.def_readwrite("fails", &UserType::value) // should trigger a static_assert if uncommented
367 //.def_readonly("fails", &UserType::value) // should trigger a static_assert if uncommented
368 .def_property("rw_value_prop", &RegisteredDerived::get_int, &RegisteredDerived::set_int)
369 .def_property_readonly("ro_value_prop", &RegisteredDerived::get_double)
370 // This one is in the registered class:
371 .def("sum", &RegisteredDerived::sum)
372 ;
373
374 using Adapted = decltype(py::method_adaptor<RegisteredDerived>(&RegisteredDerived::do_nothing));
375 static_assert(std::is_same<Adapted, void (RegisteredDerived::*)() const>::value, "");
376
377 // test_methods_and_attributes
378 py::class_<RefQualified>(m, "RefQualified")
379 .def(py::init<>())
380 .def_readonly("value", &RefQualified::value)
381 .def("refQualified", &RefQualified::refQualified)
382 .def("constRefQualified", &RefQualified::constRefQualified);
383 }
384