blob: 50c7d8412c0e4a4fff93233ed6c072023aac2d11 [file] [log] [blame]
Wenzel Jakob38bd7112015-07-05 20:05:44 +02001/*
Dean Moldovana0c1ccf2016-08-12 13:50:00 +02002 tests/test_modules.cpp -- nested modules, importing modules, and
Wenzel Jakobdb028d62015-10-13 23:44:25 +02003 internal references
Wenzel Jakob38bd7112015-07-05 20:05:44 +02004
Wenzel Jakob8cb6cb32016-04-17 20:21:41 +02005 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
Wenzel Jakob38bd7112015-07-05 20:05:44 +02006
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
Dean Moldovana0c1ccf2016-08-12 13:50:00 +020011#include "pybind11_tests.h"
12#include "constructor_stats.h"
Wenzel Jakob38bd7112015-07-05 20:05:44 +020013
Dean Moldovan665e8802016-08-12 22:28:31 +020014std::string submodule_func() {
15 return "submodule_func()";
Wenzel Jakob38bd7112015-07-05 20:05:44 +020016}
17
18class A {
19public:
Jason Rhinelander3f589372016-08-07 13:05:26 -040020 A(int v) : v(v) { print_created(this, v); }
21 ~A() { print_destroyed(this); }
22 A(const A&) { print_copy_created(this); }
23 A& operator=(const A &copy) { print_copy_assigned(this); v = copy.v; return *this; }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020024 std::string toString() { return "A[" + std::to_string(v) + "]"; }
25private:
26 int v;
27};
28
29class B {
30public:
Jason Rhinelander3f589372016-08-07 13:05:26 -040031 B() { print_default_created(this); }
32 ~B() { print_destroyed(this); }
33 B(const B&) { print_copy_created(this); }
34 B& operator=(const B &copy) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; }
Wenzel Jakob38bd7112015-07-05 20:05:44 +020035 A &get_a1() { return a1; }
36 A &get_a2() { return a2; }
37
38 A a1{1};
39 A a2{2};
40};
41
Jason Rhinelander52f4be82016-09-03 14:54:22 -040042test_initializer modules([](py::module &m) {
Wenzel Jakob38bd7112015-07-05 20:05:44 +020043 py::module m_sub = m.def_submodule("submodule");
44 m_sub.def("submodule_func", &submodule_func);
45
46 py::class_<A>(m_sub, "A")
47 .def(py::init<int>())
48 .def("__repr__", &A::toString);
49
50 py::class_<B>(m_sub, "B")
51 .def(py::init<>())
52 .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
53 .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
54 .def_readwrite("a1", &B::a1) // def_readonly uses an internal reference return policy by default
55 .def_readwrite("a2", &B::a2);
Wenzel Jakobdb028d62015-10-13 23:44:25 +020056
57 m.attr("OD") = py::module::import("collections").attr("OrderedDict");
Jason Rhinelander52f4be82016-09-03 14:54:22 -040058});