test_class.cpp
Go to the documentation of this file.
1 /*
2  tests/test_class.cpp -- test py::class_ definitions and basic functionality
3 
4  Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #include "pybind11_tests.h"
11 #include "constructor_stats.h"
12 #include "local_bindings.h"
13 #include <pybind11/stl.h>
14 
15 #if defined(_MSC_VER)
16 # pragma warning(disable: 4324) // warning C4324: structure was padded due to alignment specifier
17 #endif
18 
19 // test_brace_initialization
21  NoBraceInitialization(std::vector<int> v) : vec{std::move(v)} {}
22  template <typename T>
23  NoBraceInitialization(std::initializer_list<T> l) : vec(l) {}
24 
25  std::vector<int> vec;
26 };
27 
28 TEST_SUBMODULE(class_, m) {
29  // test_instance
30  struct NoConstructor {
31  NoConstructor() = default;
32  NoConstructor(const NoConstructor &) = default;
33  NoConstructor(NoConstructor &&) = default;
34  static NoConstructor *new_instance() {
35  auto *ptr = new NoConstructor();
36  print_created(ptr, "via new_instance");
37  return ptr;
38  }
39  ~NoConstructor() { print_destroyed(this); }
40  };
41 
42  py::class_<NoConstructor>(m, "NoConstructor")
43  .def_static("new_instance", &NoConstructor::new_instance, "Return an instance");
44 
45  // test_inheritance
46  class Pet {
47  public:
48  Pet(const std::string &name, const std::string &species)
49  : m_name(name), m_species(species) {}
50  std::string name() const { return m_name; }
51  std::string species() const { return m_species; }
52  private:
53  std::string m_name;
54  std::string m_species;
55  };
56 
57  class Dog : public Pet {
58  public:
59  Dog(const std::string &name) : Pet(name, "dog") {}
60  std::string bark() const { return "Woof!"; }
61  };
62 
63  class Rabbit : public Pet {
64  public:
65  Rabbit(const std::string &name) : Pet(name, "parrot") {}
66  };
67 
68  class Hamster : public Pet {
69  public:
70  Hamster(const std::string &name) : Pet(name, "rodent") {}
71  };
72 
73  class Chimera : public Pet {
74  Chimera() : Pet("Kimmy", "chimera") {}
75  };
76 
77  py::class_<Pet> pet_class(m, "Pet");
78  pet_class
79  .def(py::init<std::string, std::string>())
80  .def("name", &Pet::name)
81  .def("species", &Pet::species);
82 
83  /* One way of declaring a subclass relationship: reference parent's class_ object */
84  py::class_<Dog>(m, "Dog", pet_class)
85  .def(py::init<std::string>());
86 
87  /* Another way of declaring a subclass relationship: reference parent's C++ type */
88  py::class_<Rabbit, Pet>(m, "Rabbit")
89  .def(py::init<std::string>());
90 
91  /* And another: list parent in class template arguments */
92  py::class_<Hamster, Pet>(m, "Hamster")
93  .def(py::init<std::string>());
94 
95  /* Constructors are not inherited by default */
96  py::class_<Chimera, Pet>(m, "Chimera");
97 
98  m.def("pet_name_species", [](const Pet &pet) { return pet.name() + " is a " + pet.species(); });
99  m.def("dog_bark", [](const Dog &dog) { return dog.bark(); });
100 
101  // test_automatic_upcasting
102  struct BaseClass {
103  BaseClass() = default;
104  BaseClass(const BaseClass &) = default;
105  BaseClass(BaseClass &&) = default;
106  virtual ~BaseClass() = default;
107  };
108  struct DerivedClass1 : BaseClass { };
109  struct DerivedClass2 : BaseClass { };
110 
111  py::class_<BaseClass>(m, "BaseClass").def(py::init<>());
112  py::class_<DerivedClass1>(m, "DerivedClass1").def(py::init<>());
113  py::class_<DerivedClass2>(m, "DerivedClass2").def(py::init<>());
114 
115  m.def("return_class_1", []() -> BaseClass* { return new DerivedClass1(); });
116  m.def("return_class_2", []() -> BaseClass* { return new DerivedClass2(); });
117  m.def("return_class_n", [](int n) -> BaseClass* {
118  if (n == 1) return new DerivedClass1();
119  if (n == 2) return new DerivedClass2();
120  return new BaseClass();
121  });
122  m.def("return_none", []() -> BaseClass* { return nullptr; });
123 
124  // test_isinstance
125  m.def("check_instances", [](py::list l) {
126  return py::make_tuple(
127  py::isinstance<py::tuple>(l[0]),
128  py::isinstance<py::dict>(l[1]),
129  py::isinstance<Pet>(l[2]),
130  py::isinstance<Pet>(l[3]),
131  py::isinstance<Dog>(l[4]),
132  py::isinstance<Rabbit>(l[5]),
133  py::isinstance<UnregisteredType>(l[6])
134  );
135  });
136 
137  struct Invalid {};
138 
139  // test_type
140  m.def("check_type", [](int category) {
141  // Currently not supported (via a fail at compile time)
142  // See https://github.com/pybind/pybind11/issues/2486
143  // if (category == 2)
144  // return py::type::of<int>();
145  if (category == 1)
146  return py::type::of<DerivedClass1>();
147  else
148  return py::type::of<Invalid>();
149  });
150 
151  m.def("get_type_of", [](py::object ob) {
152  return py::type::of(ob);
153  });
154 
155  m.def("as_type", [](py::object ob) {
156  auto tp = py::type(ob);
157  if (py::isinstance<py::type>(ob))
158  return tp;
159  else
160  throw std::runtime_error("Invalid type");
161  });
162 
163  // test_mismatched_holder
164  struct MismatchBase1 { };
165  struct MismatchDerived1 : MismatchBase1 { };
166 
167  struct MismatchBase2 { };
168  struct MismatchDerived2 : MismatchBase2 { };
169 
170  m.def("mismatched_holder_1", []() {
171  auto mod = py::module::import("__main__");
172  py::class_<MismatchBase1, std::shared_ptr<MismatchBase1>>(mod, "MismatchBase1");
173  py::class_<MismatchDerived1, MismatchBase1>(mod, "MismatchDerived1");
174  });
175  m.def("mismatched_holder_2", []() {
176  auto mod = py::module::import("__main__");
177  py::class_<MismatchBase2>(mod, "MismatchBase2");
178  py::class_<MismatchDerived2, std::shared_ptr<MismatchDerived2>,
179  MismatchBase2>(mod, "MismatchDerived2");
180  });
181 
182  // test_override_static
183  // #511: problem with inheritance + overwritten def_static
184  struct MyBase {
185  static std::unique_ptr<MyBase> make() {
186  return std::unique_ptr<MyBase>(new MyBase());
187  }
188  };
189 
190  struct MyDerived : MyBase {
191  static std::unique_ptr<MyDerived> make() {
192  return std::unique_ptr<MyDerived>(new MyDerived());
193  }
194  };
195 
196  py::class_<MyBase>(m, "MyBase")
197  .def_static("make", &MyBase::make);
198 
199  py::class_<MyDerived, MyBase>(m, "MyDerived")
200  .def_static("make", &MyDerived::make)
201  .def_static("make2", &MyDerived::make);
202 
203  // test_implicit_conversion_life_support
204  struct ConvertibleFromUserType {
205  int i;
206 
207  ConvertibleFromUserType(UserType u) : i(u.value()) { }
208  };
209 
210  py::class_<ConvertibleFromUserType>(m, "AcceptsUserType")
211  .def(py::init<UserType>());
212  py::implicitly_convertible<UserType, ConvertibleFromUserType>();
213 
214  m.def("implicitly_convert_argument", [](const ConvertibleFromUserType &r) { return r.i; });
215  m.def("implicitly_convert_variable", [](py::object o) {
216  // `o` is `UserType` and `r` is a reference to a temporary created by implicit
217  // conversion. This is valid when called inside a bound function because the temp
218  // object is attached to the same life support system as the arguments.
219  const auto &r = o.cast<const ConvertibleFromUserType &>();
220  return r.i;
221  });
222  m.add_object("implicitly_convert_variable_fail", [&] {
223  auto f = [](PyObject *, PyObject *args) -> PyObject * {
224  auto o = py::reinterpret_borrow<py::tuple>(args)[0];
225  try { // It should fail here because there is no life support.
226  o.cast<const ConvertibleFromUserType &>();
227  } catch (const py::cast_error &e) {
228  return py::str(e.what()).release().ptr();
229  }
230  return py::str().release().ptr();
231  };
232 
233  auto def = new PyMethodDef{"f", f, METH_VARARGS, nullptr};
234  return py::reinterpret_steal<py::object>(PyCFunction_NewEx(def, nullptr, m.ptr()));
235  }());
236 
237  // test_operator_new_delete
238  struct HasOpNewDel {
240  static void *operator new(size_t s) { py::print("A new", s); return ::operator new(s); }
241  static void *operator new(size_t s, void *ptr) { py::print("A placement-new", s); return ptr; }
242  static void operator delete(void *p) { py::print("A delete"); return ::operator delete(p); }
243  };
244  struct HasOpNewDelSize {
246  static void *operator new(size_t s) { py::print("B new", s); return ::operator new(s); }
247  static void *operator new(size_t s, void *ptr) { py::print("B placement-new", s); return ptr; }
248  static void operator delete(void *p, size_t s) { py::print("B delete", s); return ::operator delete(p); }
249  };
250  struct AliasedHasOpNewDelSize {
252  static void *operator new(size_t s) { py::print("C new", s); return ::operator new(s); }
253  static void *operator new(size_t s, void *ptr) { py::print("C placement-new", s); return ptr; }
254  static void operator delete(void *p, size_t s) { py::print("C delete", s); return ::operator delete(p); }
255  virtual ~AliasedHasOpNewDelSize() = default;
256  AliasedHasOpNewDelSize() = default;
257  AliasedHasOpNewDelSize(const AliasedHasOpNewDelSize&) = delete;
258  };
259  struct PyAliasedHasOpNewDelSize : AliasedHasOpNewDelSize {
260  PyAliasedHasOpNewDelSize() = default;
261  PyAliasedHasOpNewDelSize(int) { }
263  };
264  struct HasOpNewDelBoth {
265  std::uint32_t i[8];
266  static void *operator new(size_t s) { py::print("D new", s); return ::operator new(s); }
267  static void *operator new(size_t s, void *ptr) { py::print("D placement-new", s); return ptr; }
268  static void operator delete(void *p) { py::print("D delete"); return ::operator delete(p); }
269  static void operator delete(void *p, size_t s) { py::print("D wrong delete", s); return ::operator delete(p); }
270  };
271  py::class_<HasOpNewDel>(m, "HasOpNewDel").def(py::init<>());
272  py::class_<HasOpNewDelSize>(m, "HasOpNewDelSize").def(py::init<>());
273  py::class_<HasOpNewDelBoth>(m, "HasOpNewDelBoth").def(py::init<>());
274  py::class_<AliasedHasOpNewDelSize, PyAliasedHasOpNewDelSize> aliased(m, "AliasedHasOpNewDelSize");
275  aliased.def(py::init<>());
276  aliased.attr("size_noalias") = py::int_(sizeof(AliasedHasOpNewDelSize));
277  aliased.attr("size_alias") = py::int_(sizeof(PyAliasedHasOpNewDelSize));
278 
279  // This test is actually part of test_local_bindings (test_duplicate_local), but we need a
280  // definition in a different compilation unit within the same module:
281  bind_local<LocalExternal, 17>(m, "LocalExternal", py::module_local());
282 
283  // test_bind_protected_functions
284  class ProtectedA {
285  protected:
286  int foo() const { return value; }
287 
288  private:
289  int value = 42;
290  };
291 
292  class PublicistA : public ProtectedA {
293  public:
294  using ProtectedA::foo;
295  };
296 
297  py::class_<ProtectedA>(m, "ProtectedA")
298  .def(py::init<>())
299 #if !defined(_MSC_VER) || _MSC_VER >= 1910
300  .def("foo", &PublicistA::foo);
301 #else
302  .def("foo", static_cast<int (ProtectedA::*)() const>(&PublicistA::foo));
303 #endif
304 
305  class ProtectedB {
306  public:
307  virtual ~ProtectedB() = default;
308  ProtectedB() = default;
309  ProtectedB(const ProtectedB &) = delete;
310 
311  protected:
312  virtual int foo() const { return value; }
313 
314  private:
315  int value = 42;
316  };
317 
318  class TrampolineB : public ProtectedB {
319  public:
320  int foo() const override { PYBIND11_OVERRIDE(int, ProtectedB, foo, ); }
321  };
322 
323  class PublicistB : public ProtectedB {
324  public:
325  using ProtectedB::foo;
326  };
327 
328  py::class_<ProtectedB, TrampolineB>(m, "ProtectedB")
329  .def(py::init<>())
330 #if !defined(_MSC_VER) || _MSC_VER >= 1910
331  .def("foo", &PublicistB::foo);
332 #else
333  .def("foo", static_cast<int (ProtectedB::*)() const>(&PublicistB::foo));
334 #endif
335 
336  // test_brace_initialization
337  struct BraceInitialization {
338  int field1;
339  std::string field2;
340  };
341 
342  py::class_<BraceInitialization>(m, "BraceInitialization")
343  .def(py::init<int, const std::string &>())
344  .def_readwrite("field1", &BraceInitialization::field1)
345  .def_readwrite("field2", &BraceInitialization::field2);
346  // We *don't* want to construct using braces when the given constructor argument maps to a
347  // constructor, because brace initialization could go to the wrong place (in particular when
348  // there is also an `initializer_list<T>`-accept constructor):
349  py::class_<NoBraceInitialization>(m, "NoBraceInitialization")
350  .def(py::init<std::vector<int>>())
351  .def_readonly("vec", &NoBraceInitialization::vec);
352 
353  // test_reentrant_implicit_conversion_failure
354  // #1035: issue with runaway reentrant implicit conversion
355  struct BogusImplicitConversion {
356  BogusImplicitConversion(const BogusImplicitConversion &) = default;
357  };
358 
359  py::class_<BogusImplicitConversion>(m, "BogusImplicitConversion")
360  .def(py::init<const BogusImplicitConversion &>());
361 
362  py::implicitly_convertible<int, BogusImplicitConversion>();
363 
364  // test_qualname
365  // #1166: nested class docstring doesn't show nested name
366  // Also related: tests that __qualname__ is set properly
367  struct NestBase {};
368  struct Nested {};
369  py::class_<NestBase> base(m, "NestBase");
370  base.def(py::init<>());
371  py::class_<Nested>(base, "Nested")
372  .def(py::init<>())
373  .def("fn", [](Nested &, int, NestBase &, Nested &) {})
374  .def("fa", [](Nested &, int, NestBase &, Nested &) {},
375  "a"_a, "b"_a, "c"_a);
376  base.def("g", [](NestBase &, Nested &) {});
377  base.def("h", []() { return NestBase(); });
378 
379  // test_error_after_conversion
380  // The second-pass path through dispatcher() previously didn't
381  // remember which overload was used, and would crash trying to
382  // generate a useful error message
383 
384  struct NotRegistered {};
385  struct StringWrapper { std::string str; };
386  m.def("test_error_after_conversions", [](int) {});
387  m.def("test_error_after_conversions",
388  [](StringWrapper) -> NotRegistered { return {}; });
389  py::class_<StringWrapper>(m, "StringWrapper").def(py::init<std::string>());
390  py::implicitly_convertible<std::string, StringWrapper>();
391 
392  #if defined(PYBIND11_CPP17)
393  struct alignas(1024) Aligned {
394  std::uintptr_t ptr() const { return (uintptr_t) this; }
395  };
396  py::class_<Aligned>(m, "Aligned")
397  .def(py::init<>())
398  .def("ptr", &Aligned::ptr);
399  #endif
400 
401  // test_final
402  struct IsFinal final {};
403  py::class_<IsFinal>(m, "IsFinal", py::is_final());
404 
405  // test_non_final_final
406  struct IsNonFinalFinal {};
407  py::class_<IsNonFinalFinal>(m, "IsNonFinalFinal", py::is_final());
408 
409  struct PyPrintDestructor {
410  PyPrintDestructor() = default;
411  ~PyPrintDestructor() {
412  py::print("Print from destructor");
413  }
414  void throw_something() { throw std::runtime_error("error"); }
415  };
416  py::class_<PyPrintDestructor>(m, "PyPrintDestructor")
417  .def(py::init<>())
418  .def("throw_something", &PyPrintDestructor::throw_something);
419 }
420 
421 template <int N> class BreaksBase { public:
422  virtual ~BreaksBase() = default;
423  BreaksBase() = default;
424  BreaksBase(const BreaksBase&) = delete;
425 };
426 template <int N> class BreaksTramp : public BreaksBase<N> {};
427 // These should all compile just fine:
428 using DoesntBreak1 = py::class_<BreaksBase<1>, std::unique_ptr<BreaksBase<1>>, BreaksTramp<1>>;
429 using DoesntBreak2 = py::class_<BreaksBase<2>, BreaksTramp<2>, std::unique_ptr<BreaksBase<2>>>;
430 using DoesntBreak3 = py::class_<BreaksBase<3>, std::unique_ptr<BreaksBase<3>>>;
431 using DoesntBreak4 = py::class_<BreaksBase<4>, BreaksTramp<4>>;
432 using DoesntBreak5 = py::class_<BreaksBase<5>>;
433 using DoesntBreak6 = py::class_<BreaksBase<6>, std::shared_ptr<BreaksBase<6>>, BreaksTramp<6>>;
434 using DoesntBreak7 = py::class_<BreaksBase<7>, BreaksTramp<7>, std::shared_ptr<BreaksBase<7>>>;
435 using DoesntBreak8 = py::class_<BreaksBase<8>, std::shared_ptr<BreaksBase<8>>>;
436 #define CHECK_BASE(N) static_assert(std::is_same<typename DoesntBreak##N::type, BreaksBase<N>>::value, \
437  "DoesntBreak" #N " has wrong type!")
439 #define CHECK_ALIAS(N) static_assert(DoesntBreak##N::has_alias && std::is_same<typename DoesntBreak##N::type_alias, BreaksTramp<N>>::value, \
440  "DoesntBreak" #N " has wrong type_alias!")
441 #define CHECK_NOALIAS(N) static_assert(!DoesntBreak##N::has_alias && std::is_void<typename DoesntBreak##N::type_alias>::value, \
442  "DoesntBreak" #N " has type alias, but shouldn't!")
444 #define CHECK_HOLDER(N, TYPE) static_assert(std::is_same<typename DoesntBreak##N::holder_type, std::TYPE##_ptr<BreaksBase<N>>>::value, \
445  "DoesntBreak" #N " has wrong holder_type!")
446 CHECK_HOLDER(1, unique); CHECK_HOLDER(2, unique); CHECK_HOLDER(3, unique); CHECK_HOLDER(4, unique); CHECK_HOLDER(5, unique);
447 CHECK_HOLDER(6, shared); CHECK_HOLDER(7, shared); CHECK_HOLDER(8, shared);
448 
449 // There's no nice way to test that these fail because they fail to compile; leave them here,
450 // though, so that they can be manually tested by uncommenting them (and seeing that compilation
451 // failures occurs).
452 
453 // We have to actually look into the type: the typedef alone isn't enough to instantiate the type:
454 #define CHECK_BROKEN(N) static_assert(std::is_same<typename Breaks##N::type, BreaksBase<-N>>::value, \
455  "Breaks1 has wrong type!");
456 
458 //typedef py::class_<BreaksBase<-1>, std::unique_ptr<BreaksBase<-1>>, std::unique_ptr<BreaksBase<-1>>> Breaks1;
459 //CHECK_BROKEN(1);
461 //typedef py::class_<BreaksBase<-2>, BreaksTramp<-2>, BreaksTramp<-2>> Breaks2;
462 //CHECK_BROKEN(2);
464 //typedef py::class_<BreaksBase<-3>, std::unique_ptr<BreaksBase<-3>>, BreaksTramp<-3>, BreaksTramp<-3>> Breaks3;
465 //CHECK_BROKEN(3);
467 //typedef py::class_<BreaksBase<-4>, std::unique_ptr<BreaksBase<-4>>, BreaksTramp<-4>, std::shared_ptr<BreaksBase<-4>>> Breaks4;
468 //CHECK_BROKEN(4);
470 //typedef py::class_<BreaksBase<-5>, BreaksTramp<-4>> Breaks5;
471 //CHECK_BROKEN(5);
473 //template <> struct BreaksBase<-8> : BreaksBase<-6>, BreaksBase<-7> {};
474 //typedef py::class_<BreaksBase<-8>, BreaksBase<-6>, BreaksBase<-7>> Breaks8;
475 //CHECK_BROKEN(8);
void print(const Matrix &A, const string &s, ostream &stream)
Definition: Matrix.cpp:155
Matrix3f m
py::class_< BreaksBase< 3 >, std::unique_ptr< BreaksBase< 3 >>> DoesntBreak3
Definition: test_class.cpp:430
py::class_< BreaksBase< 7 >, BreaksTramp< 7 >, std::shared_ptr< BreaksBase< 7 >>> DoesntBreak7
Definition: test_class.cpp:434
NoBraceInitialization(std::initializer_list< T > l)
Definition: test_class.cpp:23
static LabeledSymbol make(gtsam::Key key)
#define CHECK_NOALIAS(N)
Definition: test_class.cpp:441
#define CHECK_BASE(N)
Definition: test_class.cpp:436
NoBraceInitialization(std::vector< int > v)
Definition: test_class.cpp:21
ArrayXcf v
Definition: Cwise_arg.cpp:1
py::class_< BreaksBase< 4 >, BreaksTramp< 4 >> DoesntBreak4
Definition: test_class.cpp:431
int n
void print_destroyed(T *inst, Values &&...values)
TEST_SUBMODULE(class_, m)
Definition: test_class.cpp:28
std::vector< int > vec
Definition: test_class.cpp:25
py::class_< BreaksBase< 8 >, std::shared_ptr< BreaksBase< 8 >>> DoesntBreak8
Definition: test_class.cpp:435
#define CHECK_ALIAS(N)
Definition: test_class.cpp:439
void foo(CV_QUALIFIER Matrix3d &m)
static const Line3 l(Rot3(), 1, 1)
Tuple< Args... > make_tuple(Args...args)
Creates a tuple object, deducing the target type from the types of arguments.
py::class_< BreaksBase< 5 >> DoesntBreak5
Definition: test_class.cpp:432
float * ptr
py::class_< BreaksBase< 1 >, std::unique_ptr< BreaksBase< 1 >>, BreaksTramp< 1 >> DoesntBreak1
Definition: test_class.cpp:428
unsigned int uint32_t
Definition: ms_stdint.h:85
unsigned __int64 uint64_t
Definition: ms_stdint.h:95
py::class_< BreaksBase< 6 >, std::shared_ptr< BreaksBase< 6 >>, BreaksTramp< 6 >> DoesntBreak6
Definition: test_class.cpp:433
std::string bark() const
const mpreal mod(const mpreal &x, const mpreal &y, mp_rnd_t rnd_mode=mpreal::get_default_rnd())
Definition: mpreal.h:2415
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
Array< double, 1, 3 > e(1./3., 0.5, 2.)
RealScalar s
#define PYBIND11_OVERRIDE(ret_type, cname, fn,...)
Definition: pybind11.h:2258
_W64 unsigned int uintptr_t
Definition: ms_stdint.h:124
void print_created(T *inst, Values &&...values)
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1460
#define CHECK_HOLDER(N, TYPE)
Definition: test_class.cpp:444
float * p
py::class_< BreaksBase< 2 >, BreaksTramp< 2 >, std::unique_ptr< BreaksBase< 2 >>> DoesntBreak2
Definition: test_class.cpp:429
Annotation for function names.
Definition: attr.h:36
Annotation indicating that a class derives from another given type.
Definition: attr.h:42
std::ptrdiff_t j


gtsam
Author(s):
autogenerated on Sat May 8 2021 02:46:03