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) 15template <typename... Args> 16using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>; 17#endif 18 19class ExampleMandA { 20public: 21 ExampleMandA() { print_default_created(this); } 22 ExampleMandA(int value) : value(value) { print_created(this, value); } 23 ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); } 24 ExampleMandA(ExampleMandA &&e) : value(e.value) { print_move_created(this); } 25 ~ExampleMandA() { print_destroyed(this); } 26 27 std::string toString() { 28 return "ExampleMandA[value=" + std::to_string(value) + "]"; 29 } 30 31 void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; } 32 void operator=(ExampleMandA &&e) { print_move_assigned(this); value = e.value; } 33 34 void add1(ExampleMandA other) { value += other.value; } // passing by value 35 void add2(ExampleMandA &other) { value += other.value; } // passing by reference 36 void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference 37 void add4(ExampleMandA *other) { value += other->value; } // passing by pointer 38 void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer 39 40 void add6(int other) { value += other; } // passing by value 41 void add7(int &other) { value += other; } // passing by reference 42 void add8(const int &other) { value += other; } // passing by const reference 43 void add9(int *other) { value += *other; } // passing by pointer 44 void add10(const int *other) { value += *other; } // passing by const pointer 45 46 ExampleMandA self1() { return *this; } // return by value 47 ExampleMandA &self2() { return *this; } // return by reference 48 const ExampleMandA &self3() { return *this; } // return by const reference 49 ExampleMandA *self4() { return this; } // return by pointer 50 const ExampleMandA *self5() { return this; } // return by const pointer 51 52 int internal1() { return value; } // return by value 53 int &internal2() { return value; } // return by reference 54 const int &internal3() { return value; } // return by const reference 55 int *internal4() { return &value; } // return by pointer 56 const int *internal5() { return &value; } // return by const pointer 57 58 py::str overloaded() { return "()"; } 59 py::str overloaded(int) { return "(int)"; } 60 py::str overloaded(int, float) { return "(int, float)"; } 61 py::str overloaded(float, int) { return "(float, int)"; } 62 py::str overloaded(int, int) { return "(int, int)"; } 63 py::str overloaded(float, float) { return "(float, float)"; } 64 py::str overloaded(int) const { return "(int) const"; } 65 py::str overloaded(int, float) const { return "(int, float) const"; } 66 py::str overloaded(float, int) const { return "(float, int) const"; } 67 py::str overloaded(int, int) const { return "(int, int) const"; } 68 py::str overloaded(float, float) const { return "(float, float) const"; } 69 70 static py::str overloaded(float) { return "static float"; } 71 72 int value = 0; 73}; 74 75struct TestProperties { 76 int value = 1; 77 static int static_value; 78 79 int get() const { return value; } 80 void set(int v) { value = v; } 81 82 static int static_get() { return static_value; } 83 static void static_set(int v) { static_value = v; } 84}; 85int TestProperties::static_value = 1; 86 87struct TestPropertiesOverride : TestProperties { 88 int value = 99; 89 static int static_value; 90}; 91int TestPropertiesOverride::static_value = 99; 92 93struct TestPropRVP { 94 UserType v1{1}; 95 UserType v2{1}; 96 static UserType sv1; 97 static UserType sv2; 98 99 const UserType &get1() const { return v1; } 100 const UserType &get2() const { return v2; } 101 UserType get_rvalue() const { return v2; } 102 void set1(int v) { v1.set(v); } 103 void set2(int v) { v2.set(v); } 104}; 105UserType TestPropRVP::sv1(1); 106UserType TestPropRVP::sv2(1); 107 108// py::arg/py::arg_v testing: these arguments just record their argument when invoked 109class ArgInspector1 { public: std::string arg = "(default arg inspector 1)"; }; 110class ArgInspector2 { public: std::string arg = "(default arg inspector 2)"; }; 111class ArgAlwaysConverts { }; 112namespace pybind11 { namespace detail { 113template <> struct type_caster<ArgInspector1> { 114public: 115 PYBIND11_TYPE_CASTER(ArgInspector1, _("ArgInspector1")); 116 117 bool load(handle src, bool convert) { 118 value.arg = "loading ArgInspector1 argument " + 119 std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. " 120 "Argument value = " + (std::string) str(src); 121 return true; 122 } 123 124 static handle cast(const ArgInspector1 &src, return_value_policy, handle) { 125 return str(src.arg).release(); 126 } 127}; 128template <> struct type_caster<ArgInspector2> { 129public: 130 PYBIND11_TYPE_CASTER(ArgInspector2, _("ArgInspector2")); 131 132 bool load(handle src, bool convert) { 133 value.arg = "loading ArgInspector2 argument " + 134 std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. " 135 "Argument value = " + (std::string) str(src); 136 return true; 137 } 138 139 static handle cast(const ArgInspector2 &src, return_value_policy, handle) { 140 return str(src.arg).release(); 141 } 142}; 143template <> struct type_caster<ArgAlwaysConverts> { 144public: 145 PYBIND11_TYPE_CASTER(ArgAlwaysConverts, _("ArgAlwaysConverts")); 146 147 bool load(handle, bool convert) { 148 return convert; 149 } 150 151 static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) { 152 return py::none().release(); 153 } 154}; 155}} 156 157// test_custom_caster_destruction 158class DestructionTester { 159public: 160 DestructionTester() { print_default_created(this); } 161 ~DestructionTester() { print_destroyed(this); } 162 DestructionTester(const DestructionTester &) { print_copy_created(this); } 163 DestructionTester(DestructionTester &&) { print_move_created(this); } 164 DestructionTester &operator=(const DestructionTester &) { print_copy_assigned(this); return *this; } 165 DestructionTester &operator=(DestructionTester &&) { print_move_assigned(this); return *this; } 166}; 167namespace pybind11 { namespace detail { 168template <> struct type_caster<DestructionTester> { 169 PYBIND11_TYPE_CASTER(DestructionTester, _("DestructionTester")); 170 bool load(handle, bool) { return true; } 171 172 static handle cast(const DestructionTester &, return_value_policy, handle) { 173 return py::bool_(true).release(); 174 } 175}; 176}} 177 178// Test None-allowed py::arg argument policy 179class NoneTester { public: int answer = 42; }; 180int none1(const NoneTester &obj) { return obj.answer; } 181int none2(NoneTester *obj) { return obj ? obj->answer : -1; } 182int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; } 183int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; } 184int none5(std::shared_ptr<NoneTester> obj) { return obj ? obj->answer : -1; } 185 186struct StrIssue { 187 int val = -1; 188 189 StrIssue() = default; 190 StrIssue(int i) : val{i} {} 191}; 192 193// Issues #854, #910: incompatible function args when member function/pointer is in unregistered base class 194class UnregisteredBase { 195public: 196 void do_nothing() const {} 197 void increase_value() { rw_value++; ro_value += 0.25; } 198 void set_int(int v) { rw_value = v; } 199 int get_int() const { return rw_value; } 200 double get_double() const { return ro_value; } 201 int rw_value = 42; 202 double ro_value = 1.25; 203}; 204class RegisteredDerived : public UnregisteredBase { 205public: 206 using UnregisteredBase::UnregisteredBase; 207 double sum() const { return rw_value + ro_value; } 208}; 209 210TEST_SUBMODULE(methods_and_attributes, m) { 211 // test_methods_and_attributes 212 py::class_<ExampleMandA> emna(m, "ExampleMandA"); 213 emna.def(py::init<>()) 214 .def(py::init<int>()) 215 .def(py::init<const ExampleMandA&>()) 216 .def("add1", &ExampleMandA::add1) 217 .def("add2", &ExampleMandA::add2) 218 .def("add3", &ExampleMandA::add3) 219 .def("add4", &ExampleMandA::add4) 220 .def("add5", &ExampleMandA::add5) 221 .def("add6", &ExampleMandA::add6) 222 .def("add7", &ExampleMandA::add7) 223 .def("add8", &ExampleMandA::add8) 224 .def("add9", &ExampleMandA::add9) 225 .def("add10", &ExampleMandA::add10) 226 .def("self1", &ExampleMandA::self1) 227 .def("self2", &ExampleMandA::self2) 228 .def("self3", &ExampleMandA::self3) 229 .def("self4", &ExampleMandA::self4) 230 .def("self5", &ExampleMandA::self5) 231 .def("internal1", &ExampleMandA::internal1) 232 .def("internal2", &ExampleMandA::internal2) 233 .def("internal3", &ExampleMandA::internal3) 234 .def("internal4", &ExampleMandA::internal4) 235 .def("internal5", &ExampleMandA::internal5) 236#if defined(PYBIND11_OVERLOAD_CAST) 237 .def("overloaded", py::overload_cast<>(&ExampleMandA::overloaded)) 238 .def("overloaded", py::overload_cast<int>(&ExampleMandA::overloaded)) 239 .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded)) 240 .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded)) 241 .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded)) 242 .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded)) 243 .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded)) 244 .def("overloaded_const", py::overload_cast<int >(&ExampleMandA::overloaded, py::const_)) 245 .def("overloaded_const", py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_)) 246 .def("overloaded_const", py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_)) 247 .def("overloaded_const", py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_)) 248 .def("overloaded_const", py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_)) 249#else 250 // Use both the traditional static_cast method and the C++11 compatible overload_cast_ 251 .def("overloaded", overload_cast_<>()(&ExampleMandA::overloaded)) 252 .def("overloaded", overload_cast_<int>()(&ExampleMandA::overloaded)) 253 .def("overloaded", overload_cast_<int, float>()(&ExampleMandA::overloaded)) 254 .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, int)>(&ExampleMandA::overloaded)) 255 .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded)) 256 .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded)) 257 .def("overloaded_float", overload_cast_<float, float>()(&ExampleMandA::overloaded)) 258 .def("overloaded_const", overload_cast_<int >()(&ExampleMandA::overloaded, py::const_)) 259 .def("overloaded_const", overload_cast_<int, float>()(&ExampleMandA::overloaded, py::const_)) 260 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded)) 261 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, int) const>(&ExampleMandA::overloaded)) 262 .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded)) 263#endif 264 // test_no_mixed_overloads 265 // Raise error if trying to mix static/non-static overloads on the same name: 266 .def_static("add_mixed_overloads1", []() { 267 auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module::import("pybind11_tests.methods_and_attributes").attr("ExampleMandA")); 268 emna.def ("overload_mixed1", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded)) 269 .def_static("overload_mixed1", static_cast<py::str ( *)(float )>(&ExampleMandA::overloaded)); 270 }) 271 .def_static("add_mixed_overloads2", []() { 272 auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module::import("pybind11_tests.methods_and_attributes").attr("ExampleMandA")); 273 emna.def_static("overload_mixed2", static_cast<py::str ( *)(float )>(&ExampleMandA::overloaded)) 274 .def ("overload_mixed2", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded)); 275 }) 276 .def("__str__", &ExampleMandA::toString) 277 .def_readwrite("value", &ExampleMandA::value); 278 279 // test_copy_method 280 // Issue #443: can't call copied methods in Python 3 281 emna.attr("add2b") = emna.attr("add2"); 282 283 // test_properties, test_static_properties, test_static_cls 284 py::class_<TestProperties>(m, "TestProperties") 285 .def(py::init<>()) 286 .def_readonly("def_readonly", &TestProperties::value) 287 .def_readwrite("def_readwrite", &TestProperties::value) 288 .def_property("def_writeonly", nullptr, 289 [](TestProperties& s,int v) { s.value = v; } ) 290 .def_property("def_property_writeonly", nullptr, &TestProperties::set) 291 .def_property_readonly("def_property_readonly", &TestProperties::get) 292 .def_property("def_property", &TestProperties::get, &TestProperties::set) 293 .def_property("def_property_impossible", nullptr, nullptr) 294 .def_readonly_static("def_readonly_static", &TestProperties::static_value) 295 .def_readwrite_static("def_readwrite_static", &TestProperties::static_value) 296 .def_property_static("def_writeonly_static", nullptr, 297 [](py::object, int v) { TestProperties::static_value = v; }) 298 .def_property_readonly_static("def_property_readonly_static", 299 [](py::object) { return TestProperties::static_get(); }) 300 .def_property_static("def_property_writeonly_static", nullptr, 301 [](py::object, int v) { return TestProperties::static_set(v); }) 302 .def_property_static("def_property_static", 303 [](py::object) { return TestProperties::static_get(); }, 304 [](py::object, int v) { TestProperties::static_set(v); }) 305 .def_property_static("static_cls", 306 [](py::object cls) { return cls; }, 307 [](py::object cls, py::function f) { f(cls); }); 308 309 py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride") 310 .def(py::init<>()) 311 .def_readonly("def_readonly", &TestPropertiesOverride::value) 312 .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value); 313 314 auto static_get1 = [](py::object) -> const UserType & { return TestPropRVP::sv1; }; 315 auto static_get2 = [](py::object) -> const UserType & { return TestPropRVP::sv2; }; 316 auto static_set1 = [](py::object, int v) { TestPropRVP::sv1.set(v); }; 317 auto static_set2 = [](py::object, int v) { TestPropRVP::sv2.set(v); }; 318 auto rvp_copy = py::return_value_policy::copy; 319 320 // test_property_return_value_policies 321 py::class_<TestPropRVP>(m, "TestPropRVP") 322 .def(py::init<>()) 323 .def_property_readonly("ro_ref", &TestPropRVP::get1) 324 .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy) 325 .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy)) 326 .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1) 327 .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy) 328 .def_property("rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2) 329 .def_property_readonly_static("static_ro_ref", static_get1) 330 .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy) 331 .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy)) 332 .def_property_static("static_rw_ref", static_get1, static_set1) 333 .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy) 334 .def_property_static("static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2) 335 // test_property_rvalue_policy 336 .def_property_readonly("rvalue", &TestPropRVP::get_rvalue) 337 .def_property_readonly_static("static_rvalue", [](py::object) { return UserType(1); }); 338 339 // test_metaclass_override 340 struct MetaclassOverride { }; 341 py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type)) 342 .def_property_readonly_static("readonly", [](py::object) { return 1; }); 343 344#if !defined(PYPY_VERSION) 345 // test_dynamic_attributes 346 class DynamicClass { 347 public: 348 DynamicClass() { print_default_created(this); } 349 ~DynamicClass() { print_destroyed(this); } 350 }; 351 py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr()) 352 .def(py::init()); 353 354 class CppDerivedDynamicClass : public DynamicClass { }; 355 py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass") 356 .def(py::init()); 357#endif 358 359 // test_noconvert_args 360 // 361 // Test converting. The ArgAlwaysConverts is just there to make the first no-conversion pass 362 // fail so that our call always ends up happening via the second dispatch (the one that allows 363 // some conversion). 364 class ArgInspector { 365 public: 366 ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; } 367 std::string g(ArgInspector1 a, const ArgInspector1 &b, int c, ArgInspector2 *d, ArgAlwaysConverts) { 368 return a.arg + "\n" + b.arg + "\n" + std::to_string(c) + "\n" + d->arg; 369 } 370 static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; } 371 }; 372 py::class_<ArgInspector>(m, "ArgInspector") 373 .def(py::init<>()) 374 .def("f", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts()) 375 .def("g", &ArgInspector::g, "a"_a.noconvert(), "b"_a, "c"_a.noconvert()=13, "d"_a=ArgInspector2(), py::arg() = ArgAlwaysConverts()) 376 .def_static("h", &ArgInspector::h, py::arg().noconvert(), py::arg() = ArgAlwaysConverts()) 377 ; 378 m.def("arg_inspect_func", [](ArgInspector2 a, ArgInspector1 b, ArgAlwaysConverts) { return a.arg + "\n" + b.arg; }, 379 py::arg().noconvert(false), py::arg_v(nullptr, ArgInspector1()).noconvert(true), py::arg() = ArgAlwaysConverts()); 380 381 m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f")); 382 m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert()); 383 m.def("ints_preferred", [](int i) { return i / 2; }, py::arg("i")); 384 m.def("ints_only", [](int i) { return i / 2; }, py::arg("i").noconvert()); 385 386 // test_bad_arg_default 387 // Issue/PR #648: bad arg default debugging output 388#if !defined(NDEBUG) 389 m.attr("debug_enabled") = true; 390#else 391 m.attr("debug_enabled") = false; 392#endif 393 m.def("bad_arg_def_named", []{ 394 auto m = py::module::import("pybind11_tests"); 395 m.def("should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg("a") = UnregisteredType()); 396 }); 397 m.def("bad_arg_def_unnamed", []{ 398 auto m = py::module::import("pybind11_tests"); 399 m.def("should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg() = UnregisteredType()); 400 }); 401 402 // test_accepts_none 403 py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester") 404 .def(py::init<>()); 405 m.def("no_none1", &none1, py::arg().none(false)); 406 m.def("no_none2", &none2, py::arg().none(false)); 407 m.def("no_none3", &none3, py::arg().none(false)); 408 m.def("no_none4", &none4, py::arg().none(false)); 409 m.def("no_none5", &none5, py::arg().none(false)); 410 m.def("ok_none1", &none1); 411 m.def("ok_none2", &none2, py::arg().none(true)); 412 m.def("ok_none3", &none3); 413 m.def("ok_none4", &none4, py::arg().none(true)); 414 m.def("ok_none5", &none5); 415 416 // test_str_issue 417 // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid 418 py::class_<StrIssue>(m, "StrIssue") 419 .def(py::init<int>()) 420 .def(py::init<>()) 421 .def("__str__", [](const StrIssue &si) { 422 return "StrIssue[" + std::to_string(si.val) + "]"; } 423 ); 424 425 // test_unregistered_base_implementations 426 // 427 // Issues #854/910: incompatible function args when member function/pointer is in unregistered 428 // base class The methods and member pointers below actually resolve to members/pointers in 429 // UnregisteredBase; before this test/fix they would be registered via lambda with a first 430 // argument of an unregistered type, and thus uncallable. 431 py::class_<RegisteredDerived>(m, "RegisteredDerived") 432 .def(py::init<>()) 433 .def("do_nothing", &RegisteredDerived::do_nothing) 434 .def("increase_value", &RegisteredDerived::increase_value) 435 .def_readwrite("rw_value", &RegisteredDerived::rw_value) 436 .def_readonly("ro_value", &RegisteredDerived::ro_value) 437 // These should trigger a static_assert if uncommented 438 //.def_readwrite("fails", &UserType::value) // should trigger a static_assert if uncommented 439 //.def_readonly("fails", &UserType::value) // should trigger a static_assert if uncommented 440 .def_property("rw_value_prop", &RegisteredDerived::get_int, &RegisteredDerived::set_int) 441 .def_property_readonly("ro_value_prop", &RegisteredDerived::get_double) 442 // This one is in the registered class: 443 .def("sum", &RegisteredDerived::sum) 444 ; 445 446 using Adapted = decltype(py::method_adaptor<RegisteredDerived>(&RegisteredDerived::do_nothing)); 447 static_assert(std::is_same<Adapted, void (RegisteredDerived::*)() const>::value, ""); 448 449 // test_custom_caster_destruction 450 // Test that `take_ownership` works on types with a custom type caster when given a pointer 451 452 // default policy: don't take ownership: 453 m.def("custom_caster_no_destroy", []() { static auto *dt = new DestructionTester(); return dt; }); 454 455 m.def("custom_caster_destroy", []() { return new DestructionTester(); }, 456 py::return_value_policy::take_ownership); // Takes ownership: destroy when finished 457 m.def("custom_caster_destroy_const", []() -> const DestructionTester * { return new DestructionTester(); }, 458 py::return_value_policy::take_ownership); // Likewise (const doesn't inhibit destruction) 459 m.def("destruction_tester_cstats", &ConstructorStats::get<DestructionTester>, py::return_value_policy::reference); 460} 461