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


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