Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 10:17:54

0001 /*
0002     tests/test_methods_and_attributes.cpp -- constructors, deconstructors, attribute access,
0003     __str__, argument and return value conventions
0004 
0005     Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
0006 
0007     All rights reserved. Use of this source code is governed by a
0008     BSD-style license that can be found in the LICENSE file.
0009 */
0010 
0011 #include "constructor_stats.h"
0012 #include "pybind11_tests.h"
0013 
0014 #if !defined(PYBIND11_OVERLOAD_CAST)
0015 template <typename... Args>
0016 using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>;
0017 #endif
0018 
0019 class ExampleMandA {
0020 public:
0021     ExampleMandA() { print_default_created(this); }
0022     explicit ExampleMandA(int value) : value(value) { print_created(this, value); }
0023     ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); }
0024     explicit ExampleMandA(std::string &&) {}
0025     ExampleMandA(ExampleMandA &&e) noexcept : value(e.value) { print_move_created(this); }
0026     ~ExampleMandA() { print_destroyed(this); }
0027 
0028     std::string toString() const { return "ExampleMandA[value=" + std::to_string(value) + "]"; }
0029 
0030     void operator=(const ExampleMandA &e) {
0031         print_copy_assigned(this);
0032         value = e.value;
0033     }
0034     void operator=(ExampleMandA &&e) noexcept {
0035         print_move_assigned(this);
0036         value = e.value;
0037     }
0038 
0039     // NOLINTNEXTLINE(performance-unnecessary-value-param)
0040     void add1(ExampleMandA other) { value += other.value; }         // passing by value
0041     void add2(ExampleMandA &other) { value += other.value; }        // passing by reference
0042     void add3(const ExampleMandA &other) { value += other.value; }  // passing by const reference
0043     void add4(ExampleMandA *other) { value += other->value; }       // passing by pointer
0044     void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer
0045 
0046     void add6(int other) { value += other; }        // passing by value
0047     void add7(int &other) { value += other; }       // passing by reference
0048     void add8(const int &other) { value += other; } // passing by const reference
0049     // NOLINTNEXTLINE(readability-non-const-parameter) Deliberately non-const for testing
0050     void add9(int *other) { value += *other; }        // passing by pointer
0051     void add10(const int *other) { value += *other; } // passing by const pointer
0052 
0053     void consume_str(std::string &&) {}
0054 
0055     ExampleMandA self1() { return *this; }              // return by value
0056     ExampleMandA &self2() { return *this; }             // return by reference
0057     const ExampleMandA &self3() const { return *this; } // return by const reference
0058     ExampleMandA *self4() { return this; }              // return by pointer
0059     const ExampleMandA *self5() const { return this; }  // return by const pointer
0060 
0061     int internal1() const { return value; }        // return by value
0062     int &internal2() { return value; }             // return by reference
0063     const int &internal3() const { return value; } // return by const reference
0064     int *internal4() { return &value; }            // return by pointer
0065     const int *internal5() { return &value; }      // return by const pointer
0066 
0067     py::str overloaded() { return "()"; }
0068     py::str overloaded(int) { return "(int)"; }
0069     py::str overloaded(int, float) { return "(int, float)"; }
0070     py::str overloaded(float, int) { return "(float, int)"; }
0071     py::str overloaded(int, int) { return "(int, int)"; }
0072     py::str overloaded(float, float) { return "(float, float)"; }
0073     py::str overloaded(int) const { return "(int) const"; }
0074     py::str overloaded(int, float) const { return "(int, float) const"; }
0075     py::str overloaded(float, int) const { return "(float, int) const"; }
0076     py::str overloaded(int, int) const { return "(int, int) const"; }
0077     py::str overloaded(float, float) const { return "(float, float) const"; }
0078 
0079     static py::str overloaded(float) { return "static float"; }
0080 
0081     int value = 0;
0082 };
0083 
0084 struct TestProperties {
0085     int value = 1;
0086     static int static_value;
0087 
0088     int get() const { return value; }
0089     void set(int v) { value = v; }
0090 
0091     static int static_get() { return static_value; }
0092     static void static_set(int v) { static_value = v; }
0093 };
0094 int TestProperties::static_value = 1;
0095 
0096 struct TestPropertiesOverride : TestProperties {
0097     int value = 99;
0098     static int static_value;
0099 };
0100 int TestPropertiesOverride::static_value = 99;
0101 
0102 struct TestPropRVP {
0103     UserType v1{1};
0104     UserType v2{1};
0105     static UserType sv1;
0106     static UserType sv2;
0107 
0108     const UserType &get1() const { return v1; }
0109     const UserType &get2() const { return v2; }
0110     UserType get_rvalue() const { return v2; }
0111     void set1(int v) { v1.set(v); }
0112     void set2(int v) { v2.set(v); }
0113 };
0114 UserType TestPropRVP::sv1(1);
0115 UserType TestPropRVP::sv2(1);
0116 
0117 // Test None-allowed py::arg argument policy
0118 class NoneTester {
0119 public:
0120     int answer = 42;
0121 };
0122 int none1(const NoneTester &obj) { return obj.answer; }
0123 int none2(NoneTester *obj) { return obj ? obj->answer : -1; }
0124 int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
0125 int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; }
0126 int none5(const std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; }
0127 
0128 // Issue #2778: implicit casting from None to object (not pointer)
0129 class NoneCastTester {
0130 public:
0131     int answer = -1;
0132     NoneCastTester() = default;
0133     explicit NoneCastTester(int v) : answer(v) {}
0134 };
0135 
0136 struct StrIssue {
0137     int val = -1;
0138 
0139     StrIssue() = default;
0140     explicit StrIssue(int i) : val{i} {}
0141 };
0142 
0143 // Issues #854, #910: incompatible function args when member function/pointer is in unregistered
0144 // base class
0145 class UnregisteredBase {
0146 public:
0147     void do_nothing() const {}
0148     void increase_value() {
0149         rw_value++;
0150         ro_value += 0.25;
0151     }
0152     void set_int(int v) { rw_value = v; }
0153     int get_int() const { return rw_value; }
0154     double get_double() const { return ro_value; }
0155     int rw_value = 42;
0156     double ro_value = 1.25;
0157 };
0158 class RegisteredDerived : public UnregisteredBase {
0159 public:
0160     using UnregisteredBase::UnregisteredBase;
0161     double sum() const { return rw_value + ro_value; }
0162 };
0163 
0164 // Test explicit lvalue ref-qualification
0165 struct RefQualified {
0166     int value = 0;
0167 
0168     void refQualified(int other) & { value += other; }
0169     int constRefQualified(int other) const & { return value + other; }
0170 };
0171 
0172 // Test rvalue ref param
0173 struct RValueRefParam {
0174     std::size_t func1(std::string &&s) { return s.size(); }
0175     std::size_t func2(std::string &&s) const { return s.size(); }
0176     std::size_t func3(std::string &&s) & { return s.size(); }
0177     std::size_t func4(std::string &&s) const & { return s.size(); }
0178 };
0179 
0180 TEST_SUBMODULE(methods_and_attributes, m) {
0181     // test_methods_and_attributes
0182     py::class_<ExampleMandA> emna(m, "ExampleMandA");
0183     emna.def(py::init<>())
0184         .def(py::init<int>())
0185         .def(py::init<std::string &&>())
0186         .def(py::init<const ExampleMandA &>())
0187         .def("add1", &ExampleMandA::add1)
0188         .def("add2", &ExampleMandA::add2)
0189         .def("add3", &ExampleMandA::add3)
0190         .def("add4", &ExampleMandA::add4)
0191         .def("add5", &ExampleMandA::add5)
0192         .def("add6", &ExampleMandA::add6)
0193         .def("add7", &ExampleMandA::add7)
0194         .def("add8", &ExampleMandA::add8)
0195         .def("add9", &ExampleMandA::add9)
0196         .def("add10", &ExampleMandA::add10)
0197         .def("consume_str", &ExampleMandA::consume_str)
0198         .def("self1", &ExampleMandA::self1)
0199         .def("self2", &ExampleMandA::self2)
0200         .def("self3", &ExampleMandA::self3)
0201         .def("self4", &ExampleMandA::self4)
0202         .def("self5", &ExampleMandA::self5)
0203         .def("internal1", &ExampleMandA::internal1)
0204         .def("internal2", &ExampleMandA::internal2)
0205         .def("internal3", &ExampleMandA::internal3)
0206         .def("internal4", &ExampleMandA::internal4)
0207         .def("internal5", &ExampleMandA::internal5)
0208 #if defined(PYBIND11_OVERLOAD_CAST)
0209         .def("overloaded", py::overload_cast<>(&ExampleMandA::overloaded))
0210         .def("overloaded", py::overload_cast<int>(&ExampleMandA::overloaded))
0211         .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded))
0212         .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded))
0213         .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded))
0214         .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded))
0215         .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded))
0216         .def("overloaded_const", py::overload_cast<int>(&ExampleMandA::overloaded, py::const_))
0217         .def("overloaded_const",
0218              py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_))
0219         .def("overloaded_const",
0220              py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_))
0221         .def("overloaded_const",
0222              py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_))
0223         .def("overloaded_const",
0224              py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))
0225 #else
0226         // Use both the traditional static_cast method and the C++11 compatible overload_cast_
0227         .def("overloaded", overload_cast_<>()(&ExampleMandA::overloaded))
0228         .def("overloaded", overload_cast_<int>()(&ExampleMandA::overloaded))
0229         .def("overloaded", overload_cast_<int,   float>()(&ExampleMandA::overloaded))
0230         .def("overloaded", static_cast<py::str (ExampleMandA::*)(float,   int)>(&ExampleMandA::overloaded))
0231         .def("overloaded", static_cast<py::str (ExampleMandA::*)(int,     int)>(&ExampleMandA::overloaded))
0232         .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
0233         .def("overloaded_float", overload_cast_<float, float>()(&ExampleMandA::overloaded))
0234         .def("overloaded_const", overload_cast_<int         >()(&ExampleMandA::overloaded, py::const_))
0235         .def("overloaded_const", overload_cast_<int,   float>()(&ExampleMandA::overloaded, py::const_))
0236         .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float,   int) const>(&ExampleMandA::overloaded))
0237         .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int,     int) const>(&ExampleMandA::overloaded))
0238         .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))
0239 #endif
0240         // test_no_mixed_overloads
0241         // Raise error if trying to mix static/non-static overloads on the same name:
0242         .def_static("add_mixed_overloads1",
0243                     []() {
0244                         auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(
0245                             py::module_::import("pybind11_tests.methods_and_attributes")
0246                                 .attr("ExampleMandA"));
0247                         emna.def("overload_mixed1",
0248                                  static_cast<py::str (ExampleMandA::*)(int, int)>(
0249                                      &ExampleMandA::overloaded))
0250                             .def_static(
0251                                 "overload_mixed1",
0252                                 static_cast<py::str (*)(float)>(&ExampleMandA::overloaded));
0253                     })
0254         .def_static("add_mixed_overloads2",
0255                     []() {
0256                         auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>(
0257                             py::module_::import("pybind11_tests.methods_and_attributes")
0258                                 .attr("ExampleMandA"));
0259                         emna.def_static("overload_mixed2",
0260                                         static_cast<py::str (*)(float)>(&ExampleMandA::overloaded))
0261                             .def("overload_mixed2",
0262                                  static_cast<py::str (ExampleMandA::*)(int, int)>(
0263                                      &ExampleMandA::overloaded));
0264                     })
0265         .def("__str__", &ExampleMandA::toString)
0266         .def_readwrite("value", &ExampleMandA::value);
0267 
0268     // test_copy_method
0269     // Issue #443: can't call copied methods in Python 3
0270     emna.attr("add2b") = emna.attr("add2");
0271 
0272     // test_properties, test_static_properties, test_static_cls
0273     py::class_<TestProperties>(m, "TestProperties")
0274         .def(py::init<>())
0275         .def_readonly("def_readonly", &TestProperties::value)
0276         .def_readwrite("def_readwrite", &TestProperties::value)
0277         .def_property("def_writeonly", nullptr, [](TestProperties &s, int v) { s.value = v; })
0278         .def_property("def_property_writeonly", nullptr, &TestProperties::set)
0279         .def_property_readonly("def_property_readonly", &TestProperties::get)
0280         .def_property("def_property", &TestProperties::get, &TestProperties::set)
0281         .def_property("def_property_impossible", nullptr, nullptr)
0282         .def_readonly_static("def_readonly_static", &TestProperties::static_value)
0283         .def_readwrite_static("def_readwrite_static", &TestProperties::static_value)
0284         .def_property_static("def_writeonly_static",
0285                              nullptr,
0286                              [](const py::object &, int v) { TestProperties::static_value = v; })
0287         .def_property_readonly_static(
0288             "def_property_readonly_static",
0289             [](const py::object &) { return TestProperties::static_get(); })
0290         .def_property_static(
0291             "def_property_writeonly_static",
0292             nullptr,
0293             [](const py::object &, int v) { return TestProperties::static_set(v); })
0294         .def_property_static(
0295             "def_property_static",
0296             [](const py::object &) { return TestProperties::static_get(); },
0297             [](const py::object &, int v) { TestProperties::static_set(v); })
0298         .def_property_static(
0299             "static_cls",
0300             [](py::object cls) { return cls; },
0301             [](const py::object &cls, const py::function &f) { f(cls); });
0302 
0303     py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride")
0304         .def(py::init<>())
0305         .def_readonly("def_readonly", &TestPropertiesOverride::value)
0306         .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value);
0307 
0308     auto static_get1 = [](const py::object &) -> const UserType & { return TestPropRVP::sv1; };
0309     auto static_get2 = [](const py::object &) -> const UserType & { return TestPropRVP::sv2; };
0310     auto static_set1 = [](const py::object &, int v) { TestPropRVP::sv1.set(v); };
0311     auto static_set2 = [](const py::object &, int v) { TestPropRVP::sv2.set(v); };
0312     auto rvp_copy = py::return_value_policy::copy;
0313 
0314     // test_property_return_value_policies
0315     py::class_<TestPropRVP>(m, "TestPropRVP")
0316         .def(py::init<>())
0317         .def_property_readonly("ro_ref", &TestPropRVP::get1)
0318         .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy)
0319         .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy))
0320         .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1)
0321         .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy)
0322         .def_property(
0323             "rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2)
0324         .def_property_readonly_static("static_ro_ref", static_get1)
0325         .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy)
0326         .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy))
0327         .def_property_static("static_rw_ref", static_get1, static_set1)
0328         .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy)
0329         .def_property_static(
0330             "static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2)
0331         // test_property_rvalue_policy
0332         .def_property_readonly("rvalue", &TestPropRVP::get_rvalue)
0333         .def_property_readonly_static("static_rvalue",
0334                                       [](const py::object &) { return UserType(1); });
0335 
0336     // test_metaclass_override
0337     struct MetaclassOverride {};
0338     py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type))
0339         .def_property_readonly_static("readonly", [](const py::object &) { return 1; });
0340 
0341     // test_overload_ordering
0342     m.def("overload_order", [](const std::string &) { return 1; });
0343     m.def("overload_order", [](const std::string &) { return 2; });
0344     m.def("overload_order", [](int) { return 3; });
0345     m.def(
0346         "overload_order", [](int) { return 4; }, py::prepend{});
0347 
0348 #if !defined(PYPY_VERSION)
0349     // test_dynamic_attributes
0350     class DynamicClass {
0351     public:
0352         DynamicClass() { print_default_created(this); }
0353         DynamicClass(const DynamicClass &) = delete;
0354         ~DynamicClass() { print_destroyed(this); }
0355     };
0356     py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr()).def(py::init());
0357 
0358     class CppDerivedDynamicClass : public DynamicClass {};
0359     py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass").def(py::init());
0360 #endif
0361 
0362     // test_bad_arg_default
0363     // Issue/PR #648: bad arg default debugging output
0364 #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
0365     m.attr("detailed_error_messages_enabled") = true;
0366 #else
0367     m.attr("detailed_error_messages_enabled") = false;
0368 #endif
0369     m.def("bad_arg_def_named", [] {
0370         auto m = py::module_::import("pybind11_tests");
0371         m.def(
0372             "should_fail",
0373             [](int, UnregisteredType) {},
0374             py::arg(),
0375             py::arg("a") = UnregisteredType());
0376     });
0377     m.def("bad_arg_def_unnamed", [] {
0378         auto m = py::module_::import("pybind11_tests");
0379         m.def(
0380             "should_fail",
0381             [](int, UnregisteredType) {},
0382             py::arg(),
0383             py::arg() = UnregisteredType());
0384     });
0385 
0386     // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works.
0387 
0388     // test_accepts_none
0389     py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester").def(py::init<>());
0390     m.def("no_none1", &none1, py::arg{}.none(false));
0391     m.def("no_none2", &none2, py::arg{}.none(false));
0392     m.def("no_none3", &none3, py::arg{}.none(false));
0393     m.def("no_none4", &none4, py::arg{}.none(false));
0394     m.def("no_none5", &none5, py::arg{}.none(false));
0395     m.def("ok_none1", &none1);
0396     m.def("ok_none2", &none2, py::arg{}.none(true));
0397     m.def("ok_none3", &none3);
0398     m.def("ok_none4", &none4, py::arg{}.none(true));
0399     m.def("ok_none5", &none5);
0400 
0401     m.def("no_none_kwarg", &none2, "a"_a.none(false));
0402     m.def("no_none_kwarg_kw_only", &none2, py::kw_only(), "a"_a.none(false));
0403 
0404     // test_casts_none
0405     // Issue #2778: implicit casting from None to object (not pointer)
0406     py::class_<NoneCastTester>(m, "NoneCastTester")
0407         .def(py::init<>())
0408         .def(py::init<int>())
0409         .def(py::init([](py::none const &) { return NoneCastTester{}; }));
0410     py::implicitly_convertible<py::none, NoneCastTester>();
0411     m.def("ok_obj_or_none", [](NoneCastTester const &foo) { return foo.answer; });
0412 
0413     // test_str_issue
0414     // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid
0415     py::class_<StrIssue>(m, "StrIssue")
0416         .def(py::init<int>())
0417         .def(py::init<>())
0418         .def("__str__",
0419              [](const StrIssue &si) { return "StrIssue[" + std::to_string(si.val) + "]"; });
0420 
0421     // test_unregistered_base_implementations
0422     //
0423     // Issues #854/910: incompatible function args when member function/pointer is in unregistered
0424     // base class The methods and member pointers below actually resolve to members/pointers in
0425     // UnregisteredBase; before this test/fix they would be registered via lambda with a first
0426     // argument of an unregistered type, and thus uncallable.
0427     py::class_<RegisteredDerived>(m, "RegisteredDerived")
0428         .def(py::init<>())
0429         .def("do_nothing", &RegisteredDerived::do_nothing)
0430         .def("increase_value", &RegisteredDerived::increase_value)
0431         .def_readwrite("rw_value", &RegisteredDerived::rw_value)
0432         .def_readonly("ro_value", &RegisteredDerived::ro_value)
0433         // Uncommenting the next line should trigger a static_assert:
0434         // .def_readwrite("fails", &UserType::value)
0435         // Uncommenting the next line should trigger a static_assert:
0436         // .def_readonly("fails", &UserType::value)
0437         .def_property("rw_value_prop", &RegisteredDerived::get_int, &RegisteredDerived::set_int)
0438         .def_property_readonly("ro_value_prop", &RegisteredDerived::get_double)
0439         // This one is in the registered class:
0440         .def("sum", &RegisteredDerived::sum);
0441 
0442     using Adapted
0443         = decltype(py::method_adaptor<RegisteredDerived>(&RegisteredDerived::do_nothing));
0444     static_assert(std::is_same<Adapted, void (RegisteredDerived::*)() const>::value, "");
0445 
0446     // test_methods_and_attributes
0447     py::class_<RefQualified>(m, "RefQualified")
0448         .def(py::init<>())
0449         .def_readonly("value", &RefQualified::value)
0450         .def("refQualified", &RefQualified::refQualified)
0451         .def("constRefQualified", &RefQualified::constRefQualified);
0452 
0453     py::class_<RValueRefParam>(m, "RValueRefParam")
0454         .def(py::init<>())
0455         .def("func1", &RValueRefParam::func1)
0456         .def("func2", &RValueRefParam::func2)
0457         .def("func3", &RValueRefParam::func3)
0458         .def("func4", &RValueRefParam::func4);
0459 }