test_modules.cpp revision 11986
1754SN/A/*
21762SN/A    tests/test_modules.cpp -- nested modules, importing modules, and
3754SN/A                            internal references
4754SN/A
5754SN/A    Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6754SN/A
7754SN/A    All rights reserved. Use of this source code is governed by a
8754SN/A    BSD-style license that can be found in the LICENSE file.
9754SN/A*/
10754SN/A
11754SN/A#include "pybind11_tests.h"
12754SN/A#include "constructor_stats.h"
13754SN/A
14754SN/Astd::string submodule_func() {
15754SN/A    return "submodule_func()";
16754SN/A}
17754SN/A
18754SN/Aclass A {
19754SN/Apublic:
20754SN/A    A(int v) : v(v) { print_created(this, v); }
21754SN/A    ~A() { print_destroyed(this); }
22754SN/A    A(const A&) { print_copy_created(this); }
23754SN/A    A& operator=(const A &copy) { print_copy_assigned(this); v = copy.v; return *this; }
24754SN/A    std::string toString() { return "A[" + std::to_string(v) + "]"; }
25754SN/Aprivate:
26754SN/A    int v;
272665Ssaidi@eecs.umich.edu};
282665Ssaidi@eecs.umich.edu
292665Ssaidi@eecs.umich.educlass B {
30754SN/Apublic:
31754SN/A    B() { print_default_created(this); }
32754SN/A    ~B() { print_destroyed(this); }
33754SN/A    B(const B&) { print_copy_created(this); }
341070SN/A    B& operator=(const B &copy) { print_copy_assigned(this); a1 = copy.a1; a2 = copy.a2; return *this; }
352680Sktlim@umich.edu    A &get_a1() { return a1; }
363565Sgblack@eecs.umich.edu    A &get_a2() { return a2; }
371108SN/A
382235SN/A    A a1{1};
39754SN/A    A a2{2};
40754SN/A};
41754SN/A
42754SN/Atest_initializer modules([](py::module &m) {
431070SN/A    py::module m_sub = m.def_submodule("submodule");
441070SN/A    m_sub.def("submodule_func", &submodule_func);
452190SN/A
463548SN/A    py::class_<A>(m_sub, "A")
47754SN/A        .def(py::init<int>())
481070SN/A        .def("__repr__", &A::toString);
49754SN/A
50754SN/A    py::class_<B>(m_sub, "B")
511070SN/A        .def(py::init<>())
52754SN/A        .def("get_a1", &B::get_a1, "Return the internal A 1", py::return_value_policy::reference_internal)
531070SN/A        .def("get_a2", &B::get_a2, "Return the internal A 2", py::return_value_policy::reference_internal)
54754SN/A        .def_readwrite("a1", &B::a1)  // def_readonly uses an internal reference return policy by default
55754SN/A        .def_readwrite("a2", &B::a2);
561070SN/A
57754SN/A    m.attr("OD") = py::module::import("collections").attr("OrderedDict");
58754SN/A});
59754SN/A