MCPcopy Create free account
hub / github.com/pybind/pybind11 / TEST_SUBMODULE

Function TEST_SUBMODULE

tests/test_modules.cpp:14–124  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12#include "pybind11_tests.h"
13
14TEST_SUBMODULE(modules, m) {
15 // test_nested_modules
16 // This is intentionally "py::module" to verify it still can be used in place of "py::module_"
17 py::module m_sub = m.def_submodule("subsubmodule");
18 m_sub.def("submodule_func", []() { return "submodule_func()"; });
19
20 // test_reference_internal
21 class A {
22 public:
23 explicit A(int v) : v(v) { print_created(this, v); }
24 ~A() { print_destroyed(this); }
25 A(const A &) { print_copy_created(this); }
26 A &operator=(const A &copy) {
27 print_copy_assigned(this);
28 v = copy.v;
29 return *this;
30 }
31 std::string toString() const { return "A[" + std::to_string(v) + "]"; }
32
33 private:
34 int v;
35 };
36 py::class_<A>(m_sub, "A").def(py::init<int>()).def("__repr__", &A::toString);
37
38 class B {
39 public:
40 B() { print_default_created(this); }
41 ~B() { print_destroyed(this); }
42 B(const B &) { print_copy_created(this); }
43 B &operator=(const B &copy) {
44 print_copy_assigned(this);
45 a1 = copy.a1;
46 a2 = copy.a2;
47 return *this;
48 }
49 A &get_a1() { return a1; }
50 A &get_a2() { return a2; }
51
52 A a1{1};
53 A a2{2};
54 };
55 py::class_<B>(m_sub, "B")
56 .def(py::init<>())
57 .def("get_a1",
58 &B::get_a1,
59 "Return the internal A 1",
60 py::return_value_policy::reference_internal)
61 .def("get_a2",
62 &B::get_a2,
63 "Return the internal A 2",
64 py::return_value_policy::reference_internal)
65 .def_readwrite("a1", &B::a1) // def_readonly uses an internal
66 // reference return policy by default
67 .def_readwrite("a2", &B::a2);
68
69 // This is intentionally "py::module" to verify it still can be used in place of "py::module_"
70 m.attr("OD") = py::module::import("collections").attr("OrderedDict");
71

Callers

nothing calls this directly

Calls 6

importFunction · 0.85
create_extension_moduleFunction · 0.85
listClass · 0.85
Dupe1Class · 0.85
attrMethod · 0.80
appendMethod · 0.45

Tested by

no test coverage detected