test_methods_and_attributes.cpp 19 KB

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