You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

363 lines
17 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  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 <wenzel.jakob@epfl.ch>
  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. class ExampleMandA {
  11. public:
  12. ExampleMandA() { print_default_created(this); }
  13. ExampleMandA(int value) : value(value) { print_created(this, value); }
  14. ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); }
  15. ExampleMandA(ExampleMandA &&e) : value(e.value) { print_move_created(this); }
  16. ~ExampleMandA() { print_destroyed(this); }
  17. std::string toString() {
  18. return "ExampleMandA[value=" + std::to_string(value) + "]";
  19. }
  20. void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; }
  21. void operator=(ExampleMandA &&e) { print_move_assigned(this); value = e.value; }
  22. void add1(ExampleMandA other) { value += other.value; } // passing by value
  23. void add2(ExampleMandA &other) { value += other.value; } // passing by reference
  24. void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference
  25. void add4(ExampleMandA *other) { value += other->value; } // passing by pointer
  26. void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer
  27. void add6(int other) { value += other; } // passing by value
  28. void add7(int &other) { value += other; } // passing by reference
  29. void add8(const int &other) { value += other; } // passing by const reference
  30. void add9(int *other) { value += *other; } // passing by pointer
  31. void add10(const int *other) { value += *other; } // passing by const pointer
  32. ExampleMandA self1() { return *this; } // return by value
  33. ExampleMandA &self2() { return *this; } // return by reference
  34. const ExampleMandA &self3() { return *this; } // return by const reference
  35. ExampleMandA *self4() { return this; } // return by pointer
  36. const ExampleMandA *self5() { return this; } // return by const pointer
  37. int internal1() { return value; } // return by value
  38. int &internal2() { return value; } // return by reference
  39. const int &internal3() { return value; } // return by const reference
  40. int *internal4() { return &value; } // return by pointer
  41. const int *internal5() { return &value; } // return by const pointer
  42. py::str overloaded(int, float) { return "(int, float)"; }
  43. py::str overloaded(float, int) { return "(float, int)"; }
  44. py::str overloaded(int, int) { return "(int, int)"; }
  45. py::str overloaded(float, float) { return "(float, float)"; }
  46. py::str overloaded(int, float) const { return "(int, float) const"; }
  47. py::str overloaded(float, int) const { return "(float, int) const"; }
  48. py::str overloaded(int, int) const { return "(int, int) const"; }
  49. py::str overloaded(float, float) const { return "(float, float) const"; }
  50. static py::str overloaded() { return "static"; }
  51. int value = 0;
  52. };
  53. struct TestProperties {
  54. int value = 1;
  55. static int static_value;
  56. int get() const { return value; }
  57. void set(int v) { value = v; }
  58. static int static_get() { return static_value; }
  59. static void static_set(int v) { static_value = v; }
  60. };
  61. int TestProperties::static_value = 1;
  62. struct TestPropertiesOverride : TestProperties {
  63. int value = 99;
  64. static int static_value;
  65. };
  66. int TestPropertiesOverride::static_value = 99;
  67. struct SimpleValue { int value = 1; };
  68. struct TestPropRVP {
  69. SimpleValue v1;
  70. SimpleValue v2;
  71. static SimpleValue sv1;
  72. static SimpleValue sv2;
  73. const SimpleValue &get1() const { return v1; }
  74. const SimpleValue &get2() const { return v2; }
  75. SimpleValue get_rvalue() const { return v2; }
  76. void set1(int v) { v1.value = v; }
  77. void set2(int v) { v2.value = v; }
  78. };
  79. SimpleValue TestPropRVP::sv1{};
  80. SimpleValue TestPropRVP::sv2{};
  81. class DynamicClass {
  82. public:
  83. DynamicClass() { print_default_created(this); }
  84. ~DynamicClass() { print_destroyed(this); }
  85. };
  86. class CppDerivedDynamicClass : public DynamicClass { };
  87. // py::arg/py::arg_v testing: these arguments just record their argument when invoked
  88. class ArgInspector1 { public: std::string arg = "(default arg inspector 1)"; };
  89. class ArgInspector2 { public: std::string arg = "(default arg inspector 2)"; };
  90. class ArgAlwaysConverts { };
  91. namespace pybind11 { namespace detail {
  92. template <> struct type_caster<ArgInspector1> {
  93. public:
  94. PYBIND11_TYPE_CASTER(ArgInspector1, _("ArgInspector1"));
  95. bool load(handle src, bool convert) {
  96. value.arg = "loading ArgInspector1 argument " +
  97. std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. "
  98. "Argument value = " + (std::string) str(src);
  99. return true;
  100. }
  101. static handle cast(const ArgInspector1 &src, return_value_policy, handle) {
  102. return str(src.arg).release();
  103. }
  104. };
  105. template <> struct type_caster<ArgInspector2> {
  106. public:
  107. PYBIND11_TYPE_CASTER(ArgInspector2, _("ArgInspector2"));
  108. bool load(handle src, bool convert) {
  109. value.arg = "loading ArgInspector2 argument " +
  110. std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. "
  111. "Argument value = " + (std::string) str(src);
  112. return true;
  113. }
  114. static handle cast(const ArgInspector2 &src, return_value_policy, handle) {
  115. return str(src.arg).release();
  116. }
  117. };
  118. template <> struct type_caster<ArgAlwaysConverts> {
  119. public:
  120. PYBIND11_TYPE_CASTER(ArgAlwaysConverts, _("ArgAlwaysConverts"));
  121. bool load(handle, bool convert) {
  122. return convert;
  123. }
  124. static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) {
  125. return py::none();
  126. }
  127. };
  128. }}
  129. /// Issue/PR #648: bad arg default debugging output
  130. class NotRegistered {};
  131. // Test None-allowed py::arg argument policy
  132. class NoneTester { public: int answer = 42; };
  133. int none1(const NoneTester &obj) { return obj.answer; }
  134. int none2(NoneTester *obj) { return obj ? obj->answer : -1; }
  135. int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
  136. int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; }
  137. int none5(std::shared_ptr<NoneTester> obj) { return obj ? obj->answer : -1; }
  138. struct StrIssue {
  139. int val = -1;
  140. StrIssue() = default;
  141. StrIssue(int i) : val{i} {}
  142. };
  143. test_initializer methods_and_attributes([](py::module &m) {
  144. py::class_<ExampleMandA> emna(m, "ExampleMandA");
  145. emna.def(py::init<>())
  146. .def(py::init<int>())
  147. .def(py::init<const ExampleMandA&>())
  148. .def("add1", &ExampleMandA::add1)
  149. .def("add2", &ExampleMandA::add2)
  150. .def("add3", &ExampleMandA::add3)
  151. .def("add4", &ExampleMandA::add4)
  152. .def("add5", &ExampleMandA::add5)
  153. .def("add6", &ExampleMandA::add6)
  154. .def("add7", &ExampleMandA::add7)
  155. .def("add8", &ExampleMandA::add8)
  156. .def("add9", &ExampleMandA::add9)
  157. .def("add10", &ExampleMandA::add10)
  158. .def("self1", &ExampleMandA::self1)
  159. .def("self2", &ExampleMandA::self2)
  160. .def("self3", &ExampleMandA::self3)
  161. .def("self4", &ExampleMandA::self4)
  162. .def("self5", &ExampleMandA::self5)
  163. .def("internal1", &ExampleMandA::internal1)
  164. .def("internal2", &ExampleMandA::internal2)
  165. .def("internal3", &ExampleMandA::internal3)
  166. .def("internal4", &ExampleMandA::internal4)
  167. .def("internal5", &ExampleMandA::internal5)
  168. #if defined(PYBIND11_OVERLOAD_CAST)
  169. .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded))
  170. .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded))
  171. .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded))
  172. .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded))
  173. .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded))
  174. .def("overloaded_const", py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_))
  175. .def("overloaded_const", py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_))
  176. .def("overloaded_const", py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_))
  177. .def("overloaded_const", py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))
  178. #else
  179. .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, float)>(&ExampleMandA::overloaded))
  180. .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, int)>(&ExampleMandA::overloaded))
  181. .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
  182. .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
  183. .def("overloaded_float", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
  184. .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, float) const>(&ExampleMandA::overloaded))
  185. .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded))
  186. .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, int) const>(&ExampleMandA::overloaded))
  187. .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))
  188. #endif
  189. // Raise error if trying to mix static/non-static overloads on the same name:
  190. .def_static("add_mixed_overloads1", []() {
  191. auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module::import("pybind11_tests").attr("ExampleMandA"));
  192. emna.def ("overload_mixed1", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
  193. .def_static("overload_mixed1", static_cast<py::str ( *)( )>(&ExampleMandA::overloaded));
  194. })
  195. .def_static("add_mixed_overloads2", []() {
  196. auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(py::module::import("pybind11_tests").attr("ExampleMandA"));
  197. emna.def_static("overload_mixed2", static_cast<py::str ( *)( )>(&ExampleMandA::overloaded))
  198. .def ("overload_mixed2", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded));
  199. })
  200. .def("__str__", &ExampleMandA::toString)
  201. .def_readwrite("value", &ExampleMandA::value);
  202. // Issue #443: can't call copied methods in Python 3
  203. emna.attr("add2b") = emna.attr("add2");
  204. py::class_<TestProperties>(m, "TestProperties")
  205. .def(py::init<>())
  206. .def_readonly("def_readonly", &TestProperties::value)
  207. .def_readwrite("def_readwrite", &TestProperties::value)
  208. .def_property_readonly("def_property_readonly", &TestProperties::get)
  209. .def_property("def_property", &TestProperties::get, &TestProperties::set)
  210. .def_readonly_static("def_readonly_static", &TestProperties::static_value)
  211. .def_readwrite_static("def_readwrite_static", &TestProperties::static_value)
  212. .def_property_readonly_static("def_property_readonly_static",
  213. [](py::object) { return TestProperties::static_get(); })
  214. .def_property_static("def_property_static",
  215. [](py::object) { return TestProperties::static_get(); },
  216. [](py::object, int v) { TestProperties::static_set(v); })
  217. .def_property_static("static_cls",
  218. [](py::object cls) { return cls; },
  219. [](py::object cls, py::function f) { f(cls); });
  220. py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride")
  221. .def(py::init<>())
  222. .def_readonly("def_readonly", &TestPropertiesOverride::value)
  223. .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value);
  224. py::class_<SimpleValue>(m, "SimpleValue")
  225. .def_readwrite("value", &SimpleValue::value);
  226. auto static_get1 = [](py::object) -> const SimpleValue & { return TestPropRVP::sv1; };
  227. auto static_get2 = [](py::object) -> const SimpleValue & { return TestPropRVP::sv2; };
  228. auto static_set1 = [](py::object, int v) { TestPropRVP::sv1.value = v; };
  229. auto static_set2 = [](py::object, int v) { TestPropRVP::sv2.value = v; };
  230. auto rvp_copy = py::return_value_policy::copy;
  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. .def_property_readonly("rvalue", &TestPropRVP::get_rvalue)
  246. .def_property_readonly_static("static_rvalue", [](py::object) { return SimpleValue(); });
  247. struct MetaclassOverride { };
  248. py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type))
  249. .def_property_readonly_static("readonly", [](py::object) { return 1; });
  250. #if !defined(PYPY_VERSION)
  251. py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr())
  252. .def(py::init());
  253. py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass")
  254. .def(py::init());
  255. #endif
  256. // Test converting. The ArgAlwaysConverts is just there to make the first no-conversion pass
  257. // fail so that our call always ends up happening via the second dispatch (the one that allows
  258. // some conversion).
  259. class ArgInspector {
  260. public:
  261. ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; }
  262. std::string g(ArgInspector1 a, const ArgInspector1 &b, int c, ArgInspector2 *d, ArgAlwaysConverts) {
  263. return a.arg + "\n" + b.arg + "\n" + std::to_string(c) + "\n" + d->arg;
  264. }
  265. static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; }
  266. };
  267. py::class_<ArgInspector>(m, "ArgInspector")
  268. .def(py::init<>())
  269. .def("f", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts())
  270. .def("g", &ArgInspector::g, "a"_a.noconvert(), "b"_a, "c"_a.noconvert()=13, "d"_a=ArgInspector2(), py::arg() = ArgAlwaysConverts())
  271. .def_static("h", &ArgInspector::h, py::arg().noconvert(), py::arg() = ArgAlwaysConverts())
  272. ;
  273. m.def("arg_inspect_func", [](ArgInspector2 a, ArgInspector1 b, ArgAlwaysConverts) { return a.arg + "\n" + b.arg; },
  274. py::arg().noconvert(false), py::arg_v(nullptr, ArgInspector1()).noconvert(true), py::arg() = ArgAlwaysConverts());
  275. m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
  276. m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
  277. m.def("ints_preferred", [](int i) { return i / 2; }, py::arg("i"));
  278. m.def("ints_only", [](int i) { return i / 2; }, py::arg("i").noconvert());
  279. /// Issue/PR #648: bad arg default debugging output
  280. #if !defined(NDEBUG)
  281. m.attr("debug_enabled") = true;
  282. #else
  283. m.attr("debug_enabled") = false;
  284. #endif
  285. m.def("bad_arg_def_named", []{
  286. auto m = py::module::import("pybind11_tests");
  287. m.def("should_fail", [](int, NotRegistered) {}, py::arg(), py::arg("a") = NotRegistered());
  288. });
  289. m.def("bad_arg_def_unnamed", []{
  290. auto m = py::module::import("pybind11_tests");
  291. m.def("should_fail", [](int, NotRegistered) {}, py::arg(), py::arg() = NotRegistered());
  292. });
  293. py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester")
  294. .def(py::init<>());
  295. m.def("no_none1", &none1, py::arg().none(false));
  296. m.def("no_none2", &none2, py::arg().none(false));
  297. m.def("no_none3", &none3, py::arg().none(false));
  298. m.def("no_none4", &none4, py::arg().none(false));
  299. m.def("no_none5", &none5, py::arg().none(false));
  300. m.def("ok_none1", &none1);
  301. m.def("ok_none2", &none2, py::arg().none(true));
  302. m.def("ok_none3", &none3);
  303. m.def("ok_none4", &none4, py::arg().none(true));
  304. m.def("ok_none5", &none5);
  305. // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
  306. py::class_<StrIssue>(m, "StrIssue")
  307. .def(py::init<int>())
  308. .def(py::init<>())
  309. .def("__str__", [](const StrIssue &si) {
  310. return "StrIssue[" + std::to_string(si.val) + "]"; }
  311. );
  312. });