test_methods_and_attributes.cpp revision 12037:d28054ac6ec9
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
14class ExampleMandA {
15public:
16    ExampleMandA() { print_default_created(this); }
17    ExampleMandA(int value) : value(value) { print_created(this, value); }
18    ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); }
19    ExampleMandA(ExampleMandA &&e) : value(e.value) { print_move_created(this); }
20    ~ExampleMandA() { print_destroyed(this); }
21
22    std::string toString() {
23        return "ExampleMandA[value=" + std::to_string(value) + "]";
24    }
25
26    void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; }
27    void operator=(ExampleMandA &&e) { print_move_assigned(this); value = e.value; }
28
29    void add1(ExampleMandA other) { value += other.value; }           // passing by value
30    void add2(ExampleMandA &other) { value += other.value; }          // passing by reference
31    void add3(const ExampleMandA &other) { value += other.value; }    // passing by const reference
32    void add4(ExampleMandA *other) { value += other->value; }         // passing by pointer
33    void add5(const ExampleMandA *other) { value += other->value; }   // passing by const pointer
34
35    void add6(int other) { value += other; }                      // passing by value
36    void add7(int &other) { value += other; }                     // passing by reference
37    void add8(const int &other) { value += other; }               // passing by const reference
38    void add9(int *other) { value += *other; }                    // passing by pointer
39    void add10(const int *other) { value += *other; }             // passing by const pointer
40
41    ExampleMandA self1() { return *this; }                            // return by value
42    ExampleMandA &self2() { return *this; }                           // return by reference
43    const ExampleMandA &self3() { return *this; }                     // return by const reference
44    ExampleMandA *self4() { return this; }                            // return by pointer
45    const ExampleMandA *self5() { return this; }                      // return by const pointer
46
47    int internal1() { return value; }                             // return by value
48    int &internal2() { return value; }                            // return by reference
49    const int &internal3() { return value; }                      // return by const reference
50    int *internal4() { return &value; }                           // return by pointer
51    const int *internal5() { return &value; }                     // return by const pointer
52
53    py::str overloaded(int, float)   { return "(int, float)"; }
54    py::str overloaded(float, int)   { return "(float, int)"; }
55    py::str overloaded(int, int)     { return "(int, int)"; }
56    py::str overloaded(float, float) { return "(float, float)"; }
57    py::str overloaded(int, float)   const { return "(int, float) const"; }
58    py::str overloaded(float, int)   const { return "(float, int) const"; }
59    py::str overloaded(int, int)     const { return "(int, int) const"; }
60    py::str overloaded(float, float) const { return "(float, float) const"; }
61
62    int value = 0;
63};
64
65struct TestProperties {
66    int value = 1;
67    static int static_value;
68
69    int get() const { return value; }
70    void set(int v) { value = v; }
71
72    static int static_get() { return static_value; }
73    static void static_set(int v) { static_value = v; }
74};
75
76int TestProperties::static_value = 1;
77
78struct SimpleValue { int value = 1; };
79
80struct TestPropRVP {
81    SimpleValue v1;
82    SimpleValue v2;
83    static SimpleValue sv1;
84    static SimpleValue sv2;
85
86    const SimpleValue &get1() const { return v1; }
87    const SimpleValue &get2() const { return v2; }
88    SimpleValue get_rvalue() const { return v2; }
89    void set1(int v) { v1.value = v; }
90    void set2(int v) { v2.value = v; }
91};
92
93SimpleValue TestPropRVP::sv1{};
94SimpleValue TestPropRVP::sv2{};
95
96class DynamicClass {
97public:
98    DynamicClass() { print_default_created(this); }
99    ~DynamicClass() { print_destroyed(this); }
100};
101
102class CppDerivedDynamicClass : public DynamicClass { };
103
104// py::arg/py::arg_v testing: these arguments just record their argument when invoked
105class ArgInspector1 { public: std::string arg = "(default arg inspector 1)"; };
106class ArgInspector2 { public: std::string arg = "(default arg inspector 2)"; };
107class ArgAlwaysConverts { };
108namespace pybind11 { namespace detail {
109template <> struct type_caster<ArgInspector1> {
110public:
111    PYBIND11_TYPE_CASTER(ArgInspector1, _("ArgInspector1"));
112
113    bool load(handle src, bool convert) {
114        value.arg = "loading ArgInspector1 argument " +
115            std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed.  "
116            "Argument value = " + (std::string) str(src);
117        return true;
118    }
119
120    static handle cast(const ArgInspector1 &src, return_value_policy, handle) {
121        return str(src.arg).release();
122    }
123};
124template <> struct type_caster<ArgInspector2> {
125public:
126    PYBIND11_TYPE_CASTER(ArgInspector2, _("ArgInspector2"));
127
128    bool load(handle src, bool convert) {
129        value.arg = "loading ArgInspector2 argument " +
130            std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed.  "
131            "Argument value = " + (std::string) str(src);
132        return true;
133    }
134
135    static handle cast(const ArgInspector2 &src, return_value_policy, handle) {
136        return str(src.arg).release();
137    }
138};
139template <> struct type_caster<ArgAlwaysConverts> {
140public:
141    PYBIND11_TYPE_CASTER(ArgAlwaysConverts, _("ArgAlwaysConverts"));
142
143    bool load(handle, bool convert) {
144        return convert;
145    }
146
147    static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) {
148        return py::none();
149    }
150};
151}}
152
153/// Issue/PR #648: bad arg default debugging output
154class NotRegistered {};
155
156test_initializer methods_and_attributes([](py::module &m) {
157    py::class_<ExampleMandA>(m, "ExampleMandA")
158        .def(py::init<>())
159        .def(py::init<int>())
160        .def(py::init<const ExampleMandA&>())
161        .def("add1", &ExampleMandA::add1)
162        .def("add2", &ExampleMandA::add2)
163        .def("add3", &ExampleMandA::add3)
164        .def("add4", &ExampleMandA::add4)
165        .def("add5", &ExampleMandA::add5)
166        .def("add6", &ExampleMandA::add6)
167        .def("add7", &ExampleMandA::add7)
168        .def("add8", &ExampleMandA::add8)
169        .def("add9", &ExampleMandA::add9)
170        .def("add10", &ExampleMandA::add10)
171        .def("self1", &ExampleMandA::self1)
172        .def("self2", &ExampleMandA::self2)
173        .def("self3", &ExampleMandA::self3)
174        .def("self4", &ExampleMandA::self4)
175        .def("self5", &ExampleMandA::self5)
176        .def("internal1", &ExampleMandA::internal1)
177        .def("internal2", &ExampleMandA::internal2)
178        .def("internal3", &ExampleMandA::internal3)
179        .def("internal4", &ExampleMandA::internal4)
180        .def("internal5", &ExampleMandA::internal5)
181#if defined(PYBIND11_OVERLOAD_CAST)
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,   float>(&ExampleMandA::overloaded, py::const_))
188        .def("overloaded_const", py::overload_cast<float,   int>(&ExampleMandA::overloaded, py::const_))
189        .def("overloaded_const", py::overload_cast<int,     int>(&ExampleMandA::overloaded, py::const_))
190        .def("overloaded_const", py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_))
191#else
192        .def("overloaded", static_cast<py::str (ExampleMandA::*)(int,   float)>(&ExampleMandA::overloaded))
193        .def("overloaded", static_cast<py::str (ExampleMandA::*)(float,   int)>(&ExampleMandA::overloaded))
194        .def("overloaded", static_cast<py::str (ExampleMandA::*)(int,     int)>(&ExampleMandA::overloaded))
195        .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
196        .def("overloaded_float", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded))
197        .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int,   float) const>(&ExampleMandA::overloaded))
198        .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float,   int) const>(&ExampleMandA::overloaded))
199        .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int,     int) const>(&ExampleMandA::overloaded))
200        .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded))
201#endif
202        .def("__str__", &ExampleMandA::toString)
203        .def_readwrite("value", &ExampleMandA::value);
204
205    py::class_<TestProperties>(m, "TestProperties")
206        .def(py::init<>())
207        .def_readonly("def_readonly", &TestProperties::value)
208        .def_readwrite("def_readwrite", &TestProperties::value)
209        .def_property_readonly("def_property_readonly", &TestProperties::get)
210        .def_property("def_property", &TestProperties::get, &TestProperties::set)
211        .def_readonly_static("def_readonly_static", &TestProperties::static_value)
212        .def_readwrite_static("def_readwrite_static", &TestProperties::static_value)
213        .def_property_readonly_static("def_property_readonly_static",
214                                      [](py::object) { return TestProperties::static_get(); })
215        .def_property_static("def_property_static",
216                             [](py::object) { return TestProperties::static_get(); },
217                             [](py::object, int v) { TestProperties::static_set(v); })
218        .def_property_static("static_cls",
219                             [](py::object cls) { return cls; },
220                             [](py::object cls, py::function f) { f(cls); });
221
222    py::class_<SimpleValue>(m, "SimpleValue")
223        .def_readwrite("value", &SimpleValue::value);
224
225    auto static_get1 = [](py::object) -> const SimpleValue & { return TestPropRVP::sv1; };
226    auto static_get2 = [](py::object) -> const SimpleValue & { return TestPropRVP::sv2; };
227    auto static_set1 = [](py::object, int v) { TestPropRVP::sv1.value = v; };
228    auto static_set2 = [](py::object, int v) { TestPropRVP::sv2.value = v; };
229    auto rvp_copy = py::return_value_policy::copy;
230
231    py::class_<TestPropRVP>(m, "TestPropRVP")
232        .def(py::init<>())
233        .def_property_readonly("ro_ref", &TestPropRVP::get1)
234        .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy)
235        .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy))
236        .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1)
237        .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy)
238        .def_property("rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2)
239        .def_property_readonly_static("static_ro_ref", static_get1)
240        .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy)
241        .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy))
242        .def_property_static("static_rw_ref", static_get1, static_set1)
243        .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy)
244        .def_property_static("static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2)
245        .def_property_readonly("rvalue", &TestPropRVP::get_rvalue)
246        .def_property_readonly_static("static_rvalue", [](py::object) { return SimpleValue(); });
247
248    struct MetaclassOverride { };
249    py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type))
250        .def_property_readonly_static("readonly", [](py::object) { return 1; });
251
252#if !defined(PYPY_VERSION)
253    py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr())
254        .def(py::init());
255
256    py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass")
257        .def(py::init());
258#endif
259
260    // Test converting.  The ArgAlwaysConverts is just there to make the first no-conversion pass
261    // fail so that our call always ends up happening via the second dispatch (the one that allows
262    // some conversion).
263    class ArgInspector {
264    public:
265        ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; }
266        std::string g(ArgInspector1 a, const ArgInspector1 &b, int c, ArgInspector2 *d, ArgAlwaysConverts) {
267            return a.arg + "\n" + b.arg + "\n" + std::to_string(c) + "\n" + d->arg;
268        }
269        static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; }
270    };
271    py::class_<ArgInspector>(m, "ArgInspector")
272        .def(py::init<>())
273        .def("f", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts())
274        .def("g", &ArgInspector::g, "a"_a.noconvert(), "b"_a, "c"_a.noconvert()=13, "d"_a=ArgInspector2(), py::arg() = ArgAlwaysConverts())
275        .def_static("h", &ArgInspector::h, py::arg().noconvert(), py::arg() = ArgAlwaysConverts())
276        ;
277    m.def("arg_inspect_func", [](ArgInspector2 a, ArgInspector1 b, ArgAlwaysConverts) { return a.arg + "\n" + b.arg; },
278            py::arg().noconvert(false), py::arg_v(nullptr, ArgInspector1()).noconvert(true), py::arg() = ArgAlwaysConverts());
279
280    m.def("floats_preferred", [](double f) { return 0.5 * f; }, py::arg("f"));
281    m.def("floats_only", [](double f) { return 0.5 * f; }, py::arg("f").noconvert());
282
283    /// Issue/PR #648: bad arg default debugging output
284#if !defined(NDEBUG)
285    m.attr("debug_enabled") = true;
286#else
287    m.attr("debug_enabled") = false;
288#endif
289    m.def("bad_arg_def_named", []{
290        auto m = py::module::import("pybind11_tests.issues");
291        m.def("should_fail", [](int, NotRegistered) {}, py::arg(), py::arg("a") = NotRegistered());
292    });
293    m.def("bad_arg_def_unnamed", []{
294        auto m = py::module::import("pybind11_tests.issues");
295        m.def("should_fail", [](int, NotRegistered) {}, py::arg(), py::arg() = NotRegistered());
296    });
297});
298