test_class.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. tests/test_class.cpp -- test py::class_ definitions and basic functionality
  3. Copyright (c) 2016 Wenzel Jakob <[email protected]>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #include "pybind11_tests.h"
  8. #include "constructor_stats.h"
  9. #include "local_bindings.h"
  10. #include <pybind11/stl.h>
  11. // test_brace_initialization
  12. struct NoBraceInitialization {
  13. NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
  14. template <typename T>
  15. NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
  16. std::vector<int> vec;
  17. };
  18. TEST_SUBMODULE(class_, m) {
  19. // test_instance
  20. struct NoConstructor {
  21. static NoConstructor *new_instance() {
  22. auto *ptr = new NoConstructor();
  23. print_created(ptr, "via new_instance");
  24. return ptr;
  25. }
  26. ~NoConstructor() { print_destroyed(this); }
  27. };
  28. py::class_<NoConstructor>(m, "NoConstructor")
  29. .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
  30. // test_inheritance
  31. class Pet {
  32. public:
  33. Pet(const std::string &name, const std::string &species)
  34. : m_name(name), m_species(species) {}
  35. std::string name() const { return m_name; }
  36. std::string species() const { return m_species; }
  37. private:
  38. std::string m_name;
  39. std::string m_species;
  40. };
  41. class Dog : public Pet {
  42. public:
  43. Dog(const std::string &name) : Pet(name, "dog") {}
  44. std::string bark() const { return "Woof!"; }
  45. };
  46. class Rabbit : public Pet {
  47. public:
  48. Rabbit(const std::string &name) : Pet(name, "parrot") {}
  49. };
  50. class Hamster : public Pet {
  51. public:
  52. Hamster(const std::string &name) : Pet(name, "rodent") {}
  53. };
  54. class Chimera : public Pet {
  55. Chimera() : Pet("Kimmy", "chimera") {}
  56. };
  57. py::class_<Pet> pet_class(m, "Pet");
  58. pet_class
  59. .def(py::init<std::string, std::string>())
  60. .def("name", &Pet::name)
  61. .def("species", &Pet::species);
  62. /* One way of declaring a subclass relationship: reference parent's class_ object */
  63. py::class_<Dog>(m, "Dog", pet_class)
  64. .def(py::init<std::string>());
  65. /* Another way of declaring a subclass relationship: reference parent's C++ type */
  66. py::class_<Rabbit, Pet>(m, "Rabbit")
  67. .def(py::init<std::string>());
  68. /* And another: list parent in class template arguments */
  69. py::class_<Hamster, Pet>(m, "Hamster")
  70. .def(py::init<std::string>());
  71. /* Constructors are not inherited by default */
  72. py::class_<Chimera, Pet>(m, "Chimera");
  73. m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
  74. m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
  75. // test_automatic_upcasting
  76. struct BaseClass { virtual ~BaseClass() {} };
  77. struct DerivedClass1 : BaseClass { };
  78. struct DerivedClass2 : BaseClass { };
  79. py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
  80. py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
  81. py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
  82. m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
  83. m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
  84. m.def("return_class_n", [](int n) -> BaseClass* {
  85. if (n == 1) return new DerivedClass1();
  86. if (n == 2) return new DerivedClass2();
  87. return new BaseClass();
  88. });
  89. m.def("return_none", []() -> BaseClass* { return nullptr; });
  90. // test_isinstance
  91. m.def("check_instances", [](py::list l) {
  92. return py::make_tuple(
  93. py::isinstance<py::tuple>(l[0]),
  94. py::isinstance<py::dict>(l[1]),
  95. py::isinstance<Pet>(l[2]),
  96. py::isinstance<Pet>(l[3]),
  97. py::isinstance<Dog>(l[4]),
  98. py::isinstance<Rabbit>(l[5]),
  99. py::isinstance<UnregisteredType>(l[6])
  100. );
  101. });
  102. // test_mismatched_holder
  103. struct MismatchBase1 { };
  104. struct MismatchDerived1 : MismatchBase1 { };
  105. struct MismatchBase2 { };
  106. struct MismatchDerived2 : MismatchBase2 { };
  107. m.def("mismatched_holder_1", []() {
  108. auto mod = py::module::import("__main__");
  109. py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
  110. py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
  111. });
  112. m.def("mismatched_holder_2", []() {
  113. auto mod = py::module::import("__main__");
  114. py::class_<MismatchBase2>(mod, "MismatchBase2");
  115. py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
  116. MismatchBase2>(mod, "MismatchDerived2");
  117. });
  118. // test_override_static
  119. // #511: problem with inheritance + overwritten def_static
  120. struct MyBase {
  121. static std::unique_ptr<MyBase> make() {
  122. return std::unique_ptr<MyBase>(new MyBase());
  123. }
  124. };
  125. struct MyDerived : MyBase {
  126. static std::unique_ptr<MyDerived> make() {
  127. return std::unique_ptr<MyDerived>(new MyDerived());
  128. }
  129. };
  130. py::class_<MyBase>(m, "MyBase")
  131. .def_static("make", &MyBase::make);
  132. py::class_<MyDerived, MyBase>(m, "MyDerived")
  133. .def_static("make", &MyDerived::make)
  134. .def_static("make2", &MyDerived::make);
  135. // test_implicit_conversion_life_support
  136. struct ConvertibleFromUserType {
  137. int i;
  138. ConvertibleFromUserType(UserType u) : i(u.value()) { }
  139. };
  140. py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
  141. .def(py::init<UserType>());
  142. py::implicitly_convertible<UserType, ConvertibleFromUserType>();
  143. m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
  144. m.def("implicitly_convert_variable", [](py::object o) {
  145. // `o` is `UserType` and `r` is a reference to a temporary created by implicit
  146. // conversion. This is valid when called inside a bound function because the temp
  147. // object is attached to the same life support system as the arguments.
  148. const auto &r = o.cast<const ConvertibleFromUserType &>();
  149. return r.i;
  150. });
  151. m.add_object("implicitly_convert_variable_fail", [&] {
  152. auto f = [](PyObject *, PyObject *args) -> PyObject * {
  153. auto o = py::reinterpret_borrow<py::tuple>(args)[0];
  154. try { // It should fail here because there is no life support.
  155. o.cast<const ConvertibleFromUserType &>();
  156. } catch (const py::cast_error &e) {
  157. return py::str(e.what()).release().ptr();
  158. }
  159. return py::str().release().ptr();
  160. };
  161. auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
  162. return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
  163. }());
  164. // test_operator_new_delete
  165. struct HasOpNewDel {
  166. std::uint64_t i;
  167. static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
  168. static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
  169. static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
  170. };
  171. struct HasOpNewDelSize {
  172. std::uint32_t i;
  173. static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
  174. static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
  175. static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
  176. };
  177. struct AliasedHasOpNewDelSize {
  178. std::uint64_t i;
  179. static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
  180. static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
  181. static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
  182. virtual ~AliasedHasOpNewDelSize() = default;
  183. };
  184. struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
  185. PyAliasedHasOpNewDelSize() = default;
  186. PyAliasedHasOpNewDelSize(int) { }
  187. std::uint64_t j;
  188. };
  189. struct HasOpNewDelBoth {
  190. std::uint32_t i[8];
  191. static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
  192. static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
  193. static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
  194. static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
  195. };
  196. py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
  197. py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
  198. py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
  199. py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
  200. aliased.def(py::init<>());
  201. aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
  202. aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
  203. // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
  204. // definition in a different compilation unit within the same module:
  205. bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
  206. // test_bind_protected_functions
  207. class ProtectedA {
  208. protected:
  209. int foo() const { return value; }
  210. private:
  211. int value = 42;
  212. };
  213. class PublicistA : public ProtectedA {
  214. public:
  215. using ProtectedA::foo;
  216. };
  217. py::class_<ProtectedA>(m, "ProtectedA")
  218. .def(py::init<>())
  219. #if !defined(_MSC_VER) || _MSC_VER >= 1910
  220. .def("foo", &PublicistA::foo);
  221. #else
  222. .def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
  223. #endif
  224. class ProtectedB {
  225. public:
  226. virtual ~ProtectedB() = default;
  227. protected:
  228. virtual int foo() const { return value; }
  229. private:
  230. int value = 42;
  231. };
  232. class TrampolineB : public ProtectedB {
  233. public:
  234. int foo() const override { PYBIND11_OVERLOAD(int, ProtectedB, foo, ); }
  235. };
  236. class PublicistB : public ProtectedB {
  237. public:
  238. using ProtectedB::foo;
  239. };
  240. py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
  241. .def(py::init<>())
  242. #if !defined(_MSC_VER) || _MSC_VER >= 1910
  243. .def("foo", &PublicistB::foo);
  244. #else
  245. .def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
  246. #endif
  247. // test_brace_initialization
  248. struct BraceInitialization {
  249. int field1;
  250. std::string field2;
  251. };
  252. py::class_<BraceInitialization>(m, "BraceInitialization")
  253. .def(py::init<int, const std::string &>())
  254. .def_readwrite("field1", &BraceInitialization::field1)
  255. .def_readwrite("field2", &BraceInitialization::field2);
  256. // We *don't* want to construct using braces when the given constructor argument maps to a
  257. // constructor, because brace initialization could go to the wrong place (in particular when
  258. // there is also an `initializer_list<T>`-accept constructor):
  259. py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
  260. .def(py::init<std::vector<int>>())
  261. .def_readonly("vec", &NoBraceInitialization::vec);
  262. // test_reentrant_implicit_conversion_failure
  263. // #1035: issue with runaway reentrant implicit conversion
  264. struct BogusImplicitConversion {
  265. BogusImplicitConversion(const BogusImplicitConversion &) { }
  266. };
  267. py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
  268. .def(py::init<const BogusImplicitConversion &>());
  269. py::implicitly_convertible<int, BogusImplicitConversion>();
  270. // test_qualname
  271. // #1166: nested class docstring doesn't show nested name
  272. // Also related: tests that __qualname__ is set properly
  273. struct NestBase {};
  274. struct Nested {};
  275. py::class_<NestBase> base(m, "NestBase");
  276. base.def(py::init<>());
  277. py::class_<Nested>(base, "Nested")
  278. .def(py::init<>())
  279. .def("fn", [](Nested &, int, NestBase &, Nested &) {})
  280. .def("fa", [](Nested &, int, NestBase &, Nested &) {},
  281. "a"_a, "b"_a, "c"_a);
  282. base.def("g", [](NestBase &, Nested &) {});
  283. base.def("h", []() { return NestBase(); });
  284. }
  285. template <int N> class BreaksBase { public: virtual ~BreaksBase() = default; };
  286. template <int N> class BreaksTramp : public BreaksBase<N> {};
  287. // These should all compile just fine:
  288. typedef py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>> DoesntBreak1;
  289. typedef py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>> DoesntBreak2;
  290. typedef py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>> DoesntBreak3;
  291. typedef py::class_<BreaksBase<4>, BreaksTramp<4>> DoesntBreak4;
  292. typedef py::class_<BreaksBase<5>> DoesntBreak5;
  293. typedef py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>> DoesntBreak6;
  294. typedef py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>> DoesntBreak7;
  295. typedef py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>> DoesntBreak8;
  296. #define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
  297. "DoesntBreak" #N " has wrong type!")
  298. CHECK_BASE(1); CHECK_BASE(2); CHECK_BASE(3); CHECK_BASE(4); CHECK_BASE(5); CHECK_BASE(6); CHECK_BASE(7); CHECK_BASE(8);
  299. #define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
  300. "DoesntBreak" #N " has wrong type_alias!")
  301. #define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
  302. "DoesntBreak" #N " has type alias, but shouldn't!")
  303. CHECK_ALIAS(1); CHECK_ALIAS(2); CHECK_NOALIAS(3); CHECK_ALIAS(4); CHECK_NOALIAS(5); CHECK_ALIAS(6); CHECK_ALIAS(7); CHECK_NOALIAS(8);
  304. #define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
  305. "DoesntBreak" #N " has wrong holder_type!")
  306. CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
  307. CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
  308. // There's no nice way to test that these fail because they fail to compile; leave them here,
  309. // though, so that they can be manually tested by uncommenting them (and seeing that compilation
  310. // failures occurs).
  311. // We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
  312. #define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
  313. "Breaks1 has wrong type!");
  314. //// Two holder classes:
  315. //typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
  316. //CHECK_BROKEN(1);
  317. //// Two aliases:
  318. //typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
  319. //CHECK_BROKEN(2);
  320. //// Holder + 2 aliases
  321. //typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
  322. //CHECK_BROKEN(3);
  323. //// Alias + 2 holders
  324. //typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
  325. //CHECK_BROKEN(4);
  326. //// Invalid option (not a subclass or holder)
  327. //typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
  328. //CHECK_BROKEN(5);
  329. //// Invalid option: multiple inheritance not supported:
  330. //template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
  331. //typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
  332. //CHECK_BROKEN(8);