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 "constructor_stats.h"
12 #include "pybind11_tests.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  explicit ExampleMandA(int value) : value(value) { print_created(this, value); }
24  explicit ExampleMandA(std::string &&) {}
25  ExampleMandA(ExampleMandA &&e) noexcept : value(e.value) { print_move_created(this); }
27 
28  std::string toString() const { return "ExampleMandA[value=" + std::to_string(value) + "]"; }
29 
30  void operator=(const ExampleMandA &e) {
31  print_copy_assigned(this);
32  value = e.value;
33  }
34  void operator=(ExampleMandA &&e) noexcept {
35  print_move_assigned(this);
36  value = e.value;
37  }
38 
39  // NOLINTNEXTLINE(performance-unnecessary-value-param)
40  void add1(ExampleMandA other) { value += other.value; } // passing by value
41  void add2(ExampleMandA &other) { value += other.value; } // passing by reference
42  void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference
43  void add4(ExampleMandA *other) { value += other->value; } // passing by pointer
44  void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer
45 
46  void add6(int other) { value += other; } // passing by value
47  void add7(int &other) { value += other; } // passing by reference
48  void add8(const int &other) { value += other; } // passing by const reference
49  // NOLINTNEXTLINE(readability-non-const-parameter) Deliberately non-const for testing
50  void add9(int *other) { value += *other; } // passing by pointer
51  void add10(const int *other) { value += *other; } // passing by const pointer
52 
53  void consume_str(std::string &&) {}
54 
55  ExampleMandA self1() { return *this; } // return by value
56  ExampleMandA &self2() { return *this; } // return by reference
57  const ExampleMandA &self3() const { return *this; } // return by const reference
58  ExampleMandA *self4() { return this; } // return by pointer
59  const ExampleMandA *self5() const { return this; } // return by const pointer
60 
61  int internal1() const { return value; } // return by value
62  int &internal2() { return value; } // return by reference
63  const int &internal3() const { return value; } // return by const reference
64  int *internal4() { return &value; } // return by pointer
65  const int *internal5() { return &value; } // return by const pointer
66 
67  py::str overloaded() { return "()"; }
68  py::str overloaded(int) { return "(int)"; }
69  py::str overloaded(int, float) { return "(int, float)"; }
70  py::str overloaded(float, int) { return "(float, int)"; }
71  py::str overloaded(int, int) { return "(int, int)"; }
72  py::str overloaded(float, float) { return "(float, float)"; }
73  py::str overloaded(int) const { return "(int) const"; }
74  py::str overloaded(int, float) const { return "(int, float) const"; }
75  py::str overloaded(float, int) const { return "(float, int) const"; }
76  py::str overloaded(int, int) const { return "(int, int) const"; }
77  py::str overloaded(float, float) const { return "(float, float) const"; }
78 
79  static py::str overloaded(float) { return "static float"; }
80 
81  int value = 0;
82 };
83 
85  int value = 1;
86  static int static_value;
87 
88  int get() const { return value; }
89  void set(int v) { value = v; }
90 
91  static int static_get() { return static_value; }
92  static void static_set(int v) { static_value = v; }
93 };
95 
97  int value = 99;
98  static int static_value;
99 };
101 
102 struct TestPropRVP {
103  UserType v1{1};
104  UserType v2{1};
105  static UserType sv1;
106  static UserType sv2;
107 
108  const UserType &get1() const { return v1; }
109  const UserType &get2() const { return v2; }
110  UserType get_rvalue() const { return v2; }
111  void set1(int v) { v1.set(v); }
112  void set2(int v) { v2.set(v); }
113 };
114 UserType TestPropRVP::sv1(1);
115 UserType TestPropRVP::sv2(1);
116 
117 // Test None-allowed py::arg argument policy
118 class NoneTester {
119 public:
120  int answer = 42;
121 };
122 int none1(const NoneTester &obj) { return obj.answer; }
123 int none2(NoneTester *obj) { return obj ? obj->answer : -1; }
124 int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
125 int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; }
126 int none5(const std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
127 
128 // Issue #2778: implicit casting from None to object (not pointer)
130 public:
131  int answer = -1;
132  NoneCastTester() = default;
133  explicit NoneCastTester(int v) : answer(v) {}
134 };
135 
136 struct StrIssue {
137  int val = -1;
138 
139  StrIssue() = default;
140  explicit StrIssue(int i) : val{i} {}
141 };
142 
143 // Issues #854, #910: incompatible function args when member function/pointer is in unregistered
144 // base class
146 public:
147  void do_nothing() const {}
148  void increase_value() {
149  rw_value++;
150  ro_value += 0.25;
151  }
152  void set_int(int v) { rw_value = v; }
153  int get_int() const { return rw_value; }
154  double get_double() const { return ro_value; }
155  int rw_value = 42;
156  double ro_value = 1.25;
157 };
159 public:
160  using UnregisteredBase::UnregisteredBase;
161  double sum() const { return rw_value + ro_value; }
162 };
163 
164 // Test explicit lvalue ref-qualification
165 struct RefQualified {
166  int value = 0;
167 
168  void refQualified(int other) & { value += other; }
169  int constRefQualified(int other) const & { return value + other; }
170 };
171 
172 // Test rvalue ref param
174  std::size_t func1(std::string &&s) { return s.size(); }
175  std::size_t func2(std::string &&s) const { return s.size(); }
176  std::size_t func3(std::string &&s) & { return s.size(); }
177  std::size_t func4(std::string &&s) const & { return s.size(); }
178 };
179 
180 TEST_SUBMODULE(methods_and_attributes, m) {
181  // test_methods_and_attributes
182  py::class_<ExampleMandA> emna(m, "ExampleMandA");
183  emna.def(py::init<>())
184  .def(py::init<int>())
185  .def(py::init<std::string &&>())
186  .def(py::init<const ExampleMandA &>())
187  .def("add1", &ExampleMandA::add1)
188  .def("add2", &ExampleMandA::add2)
189  .def("add3", &ExampleMandA::add3)
190  .def("add4", &ExampleMandA::add4)
191  .def("add5", &ExampleMandA::add5)
192  .def("add6", &ExampleMandA::add6)
193  .def("add7", &ExampleMandA::add7)
194  .def("add8", &ExampleMandA::add8)
195  .def("add9", &ExampleMandA::add9)
196  .def("add10", &ExampleMandA::add10)
197  .def("consume_str", &ExampleMandA::consume_str)
198  .def("self1", &ExampleMandA::self1)
199  .def("self2", &ExampleMandA::self2)
200  .def("self3", &ExampleMandA::self3)
201  .def("self4", &ExampleMandA::self4)
202  .def("self5", &ExampleMandA::self5)
203  .def("internal1", &ExampleMandA::internal1)
204  .def("internal2", &ExampleMandA::internal2)
205  .def("internal3", &ExampleMandA::internal3)
206  .def("internal4", &ExampleMandA::internal4)
207  .def("internal5", &ExampleMandA::internal5)
208 #if defined(PYBIND11_OVERLOAD_CAST)
209  .def("overloaded", py::overload_cast<>(&ExampleMandA::overloaded))
210  .def("overloaded", py::overload_cast<int>(&ExampleMandA::overloaded))
211  .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded))
212  .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded))
213  .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded))
214  .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded))
215  .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded))
216  .def("overloaded_const", py::overload_cast<int>(&ExampleMandA::overloaded, py::const_))
217  .def("overloaded_const",
218  py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_))
219  .def("overloaded_const",
220  py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_))
221  .def("overloaded_const",
222  py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_))
223  .def("overloaded_const",
224  py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))
225 #else
226  // Use both the traditional static_cast method and the C++11 compatible overload_cast_
227  .def("overloaded", overload_cast_<>()(&ExampleMandA::overloaded))
228  .def("overloaded", overload_cast_<int>()(&ExampleMandA::overloaded))
230  .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, int)>(&ExampleMandA::overloaded))
231  .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded))
232  .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
233  .def("overloaded_float", overload_cast_<float, float>()(&ExampleMandA::overloaded))
234  .def("overloaded_const", overload_cast_<int >()(&ExampleMandA::overloaded, py::const_))
235  .def("overloaded_const", overload_cast_<int, float>()(&ExampleMandA::overloaded, py::const_))
236  .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded))
237  .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, int) const>(&ExampleMandA::overloaded))
238  .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))
239 #endif
240  // test_no_mixed_overloads
241  // Raise error if trying to mix static/non-static overloads on the same name:
242  .def_static("add_mixed_overloads1",
243  []() {
244  auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(
245  py::module_::import("pybind11_tests.methods_and_attributes")
246  .attr("ExampleMandA"));
247  emna.def("overload_mixed1",
248  static_cast<py::str (ExampleMandA::*)(int, int)>(
250  .def_static(
251  "overload_mixed1",
252  static_cast<py::str (*)(float)>(&ExampleMandA::overloaded));
253  })
254  .def_static("add_mixed_overloads2",
255  []() {
256  auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(
257  py::module_::import("pybind11_tests.methods_and_attributes")
258  .attr("ExampleMandA"));
259  emna.def_static("overload_mixed2",
260  static_cast<py::str (*)(float)>(&ExampleMandA::overloaded))
261  .def("overload_mixed2",
262  static_cast<py::str (ExampleMandA::*)(int, int)>(
264  })
265  .def("__str__", &ExampleMandA::toString)
266  .def_readwrite("value", &ExampleMandA::value);
267 
268  // test_copy_method
269  // Issue #443: can't call copied methods in Python 3
270  emna.attr("add2b") = emna.attr("add2");
271 
272  // test_properties, test_static_properties, test_static_cls
273  py::class_<TestProperties>(m, "TestProperties")
274  .def(py::init<>())
275  .def_readonly("def_readonly", &TestProperties::value)
276  .def_readwrite("def_readwrite", &TestProperties::value)
277  .def_property("def_writeonly", nullptr, [](TestProperties &s, int v) { s.value = v; })
278  .def_property("def_property_writeonly", nullptr, &TestProperties::set)
279  .def_property_readonly("def_property_readonly", &TestProperties::get)
280  .def_property("def_property", &TestProperties::get, &TestProperties::set)
281  .def_property("def_property_impossible", nullptr, nullptr)
282  .def_readonly_static("def_readonly_static", &TestProperties::static_value)
283  .def_readwrite_static("def_readwrite_static", &TestProperties::static_value)
284  .def_property_static("def_writeonly_static",
285  nullptr,
286  [](const py::object &, int v) { TestProperties::static_value = v; })
287  .def_property_readonly_static(
288  "def_property_readonly_static",
289  [](const py::object &) { return TestProperties::static_get(); })
290  .def_property_static(
291  "def_property_writeonly_static",
292  nullptr,
293  [](const py::object &, int v) { return TestProperties::static_set(v); })
294  .def_property_static(
295  "def_property_static",
296  [](const py::object &) { return TestProperties::static_get(); },
297  [](const py::object &, int v) { TestProperties::static_set(v); })
298  .def_property_static(
299  "static_cls",
300  [](py::object cls) { return cls; },
301  [](const py::object &cls, const py::function &f) { f(cls); });
302 
303  py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride")
304  .def(py::init<>())
305  .def_readonly("def_readonly", &TestPropertiesOverride::value)
306  .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value);
307 
308  auto static_get1 = [](const py::object &) -> const UserType & { return TestPropRVP::sv1; };
309  auto static_get2 = [](const py::object &) -> const UserType & { return TestPropRVP::sv2; };
310  auto static_set1 = [](const py::object &, int v) { TestPropRVP::sv1.set(v); };
311  auto static_set2 = [](const py::object &, int v) { TestPropRVP::sv2.set(v); };
312  auto rvp_copy = py::return_value_policy::copy;
313 
314  // test_property_return_value_policies
315  py::class_<TestPropRVP>(m, "TestPropRVP")
316  .def(py::init<>())
317  .def_property_readonly("ro_ref", &TestPropRVP::get1)
318  .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy)
319  .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy))
320  .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1)
321  .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy)
322  .def_property(
323  "rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2)
324  .def_property_readonly_static("static_ro_ref", static_get1)
325  .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy)
326  .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy))
327  .def_property_static("static_rw_ref", static_get1, static_set1)
328  .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy)
329  .def_property_static(
330  "static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2)
331  // test_property_rvalue_policy
332  .def_property_readonly("rvalue", &TestPropRVP::get_rvalue)
333  .def_property_readonly_static("static_rvalue",
334  [](const py::object &) { return UserType(1); });
335 
336  // test_metaclass_override
337  struct MetaclassOverride {};
338  py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type))
339  .def_property_readonly_static("readonly", [](const py::object &) { return 1; });
340 
341  // test_overload_ordering
342  m.def("overload_order", [](const std::string &) { return 1; });
343  m.def("overload_order", [](const std::string &) { return 2; });
344  m.def("overload_order", [](int) { return 3; });
345  m.def(
346  "overload_order", [](int) { return 4; }, py::prepend{});
347 
348 #if !defined(PYPY_VERSION)
349  // test_dynamic_attributes
350  class DynamicClass {
351  public:
352  DynamicClass() { print_default_created(this); }
353  DynamicClass(const DynamicClass &) = delete;
354  ~DynamicClass() { print_destroyed(this); }
355  };
356  py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr()).def(py::init());
357 
358  class CppDerivedDynamicClass : public DynamicClass {};
359  py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass").def(py::init());
360 #endif
361 
362  // test_bad_arg_default
363  // Issue/PR #648: bad arg default debugging output
364 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
365  m.attr("detailed_error_messages_enabled") = true;
366 #else
367  m.attr("detailed_error_messages_enabled") = false;
368 #endif
369  m.def("bad_arg_def_named", [] {
370  auto m = py::module_::import("pybind11_tests");
371  m.def(
372  "should_fail",
373  [](int, UnregisteredType) {},
374  py::arg(),
375  py::arg("a") = UnregisteredType());
376  });
377  m.def("bad_arg_def_unnamed", [] {
378  auto m = py::module_::import("pybind11_tests");
379  m.def(
380  "should_fail",
381  [](int, UnregisteredType) {},
382  py::arg(),
383  py::arg() = UnregisteredType());
384  });
385 
386  // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
387 
388  // test_accepts_none
389  py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester").def(py::init<>());
390  m.def("no_none1", &none1, py::arg{}.none(false));
391  m.def("no_none2", &none2, py::arg{}.none(false));
392  m.def("no_none3", &none3, py::arg{}.none(false));
393  m.def("no_none4", &none4, py::arg{}.none(false));
394  m.def("no_none5", &none5, py::arg{}.none(false));
395  m.def("ok_none1", &none1);
396  m.def("ok_none2", &none2, py::arg{}.none(true));
397  m.def("ok_none3", &none3);
398  m.def("ok_none4", &none4, py::arg{}.none(true));
399  m.def("ok_none5", &none5);
400 
401  m.def("no_none_kwarg", &none2, "a"_a.none(false));
402  m.def("no_none_kwarg_kw_only", &none2, py::kw_only(), "a"_a.none(false));
403 
404  // test_casts_none
405  // Issue #2778: implicit casting from None to object (not pointer)
406  py::class_<NoneCastTester>(m, "NoneCastTester")
407  .def(py::init<>())
408  .def(py::init<int>())
409  .def(py::init([](py::none const &) { return NoneCastTester{}; }));
410  py::implicitly_convertible<py::none, NoneCastTester>();
411  m.def("ok_obj_or_none", [](NoneCastTester const &foo) { return foo.answer; });
412 
413  // test_str_issue
414  // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
415  py::class_<StrIssue>(m, "StrIssue")
416  .def(py::init<int>())
417  .def(py::init<>())
418  .def("__str__",
419  [](const StrIssue &si) { return "StrIssue[" + std::to_string(si.val) + "]"; });
420 
421  // test_unregistered_base_implementations
422  //
423  // Issues #854/910: incompatible function args when member function/pointer is in unregistered
424  // base class The methods and member pointers below actually resolve to members/pointers in
425  // UnregisteredBase; before this test/fix they would be registered via lambda with a first
426  // argument of an unregistered type, and thus uncallable.
427  py::class_<RegisteredDerived>(m, "RegisteredDerived")
428  .def(py::init<>())
429  .def("do_nothing", &RegisteredDerived::do_nothing)
430  .def("increase_value", &RegisteredDerived::increase_value)
431  .def_readwrite("rw_value", &RegisteredDerived::rw_value)
432  .def_readonly("ro_value", &RegisteredDerived::ro_value)
433  // Uncommenting the next line should trigger a static_assert:
434  // .def_readwrite("fails", &UserType::value)
435  // Uncommenting the next line should trigger a static_assert:
436  // .def_readonly("fails", &UserType::value)
437  .def_property("rw_value_prop", &RegisteredDerived::get_int, &RegisteredDerived::set_int)
438  .def_property_readonly("ro_value_prop", &RegisteredDerived::get_double)
439  // This one is in the registered class:
440  .def("sum", &RegisteredDerived::sum);
441 
442  using Adapted
443  = decltype(py::method_adaptor<RegisteredDerived>(&RegisteredDerived::do_nothing));
444  static_assert(std::is_same<Adapted, void (RegisteredDerived::*)() const>::value, "");
445 
446  // test_methods_and_attributes
447  py::class_<RefQualified>(m, "RefQualified")
448  .def(py::init<>())
449  .def_readonly("value", &RefQualified::value)
450  .def("refQualified", &RefQualified::refQualified)
451  .def("constRefQualified", &RefQualified::constRefQualified);
452 
453  py::class_<RValueRefParam>(m, "RValueRefParam")
454  .def(py::init<>())
455  .def("func1", &RValueRefParam::func1)
456  .def("func2", &RValueRefParam::func2)
457  .def("func3", &RValueRefParam::func3)
458  .def("func4", &RValueRefParam::func4);
459 }
std::size_t func4(std::string &&s) const &
Matrix3f m
py::str overloaded(float, int)
void refQualified(int other) &
const UserType & get2() const
Vector v2
Vector v1
void print_destroyed(T *inst, Values &&...values)
std::size_t func1(std::string &&s)
std::string toString() const
const ExampleMandA & self3() const
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_
void foo(CV_QUALIFIER Matrix3d &m)
static void static_set(int v)
void print_default_created(T *inst, Values &&...values)
const ExampleMandA * self5() const
const int & internal3() const
int none5(const std::shared_ptr< NoneTester > &obj)
void add8(const int &other)
void print_move_assigned(T *inst, Values &&...values)
void operator=(ExampleMandA &&e) noexcept
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const ArgReturnType arg() const
Array< int, Dynamic, 1 > v
Point2(* f)(const Point3 &, OptionalJacobian< 2, 3 >)
py::str overloaded(float, float) const
Array< double, 1, 3 > e(1./3., 0.5, 2.)
RealScalar s
static py::str overloaded(float)
const UserType & get1() const
ExampleMandA(const ExampleMandA &e)
int none4(std::shared_ptr< NoneTester > *obj)
py::str overloaded(int, float) const
py::str overloaded(float, int) const
int none3(std::shared_ptr< NoneTester > &obj)
std::size_t func3(std::string &&s) &
TEST_SUBMODULE(methods_and_attributes, m)
pybind11::detail::overload_cast_impl< Args... > overload_cast_
void operator=(const ExampleMandA &e)
UserType get_rvalue() const
py::str overloaded(int, int) const
void print_created(T *inst, Values &&...values)
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1882
std::size_t func2(std::string &&s) const
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)
ExampleMandA(ExampleMandA &&e) noexcept
void print_move_created(T *inst, Values &&...values)
py::str overloaded(int, float)
void add1(ExampleMandA other)
py::str overloaded(int) const
ExampleMandA(std::string &&)
void add5(const ExampleMandA *other)


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:37:46