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

Function PYBIND11_MODULE

tests/pybind11_cross_module_tests.cpp:28–163  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

26CrossDSOClass::~CrossDSOClass() = default;
27
28PYBIND11_MODULE(pybind11_cross_module_tests, m, py::mod_gil_not_used()) {
29 m.doc() = "pybind11 cross-module test module";
30
31 // test_local_bindings.py tests:
32 //
33 // Definitions here are tested by importing both this module and the
34 // relevant pybind11_tests submodule from a test_whatever.py
35
36 // test_load_external
37 bind_local<ExternalType1>(m, "ExternalType1", py::module_local());
38 bind_local<ExternalType2, 0, std::shared_ptr<ExternalType2>>(
39 m, "ExternalType2", py::module_local());
40 bind_local<ExternalType3, 0, py::smart_holder>(m, "ExternalType3", py::module_local());
41
42 // test_exceptions.py
43 py::register_local_exception<LocalSimpleException>(m, "LocalSimpleException");
44 m.def("raise_runtime_error", []() {
45 py::set_error(PyExc_RuntimeError, "My runtime error");
46 throw py::error_already_set();
47 });
48 m.def("raise_value_error", []() {
49 py::set_error(PyExc_ValueError, "My value error");
50 throw py::error_already_set();
51 });
52 m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); });
53 m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); });
54 m.def("throw_stop_iteration", []() { throw py::stop_iteration(); });
55 m.def("throw_local_error", []() { throw LocalException("just local"); });
56 m.def("throw_local_simple_error", []() { throw LocalSimpleException("external mod"); });
57 py::register_exception_translator([](std::exception_ptr p) {
58 try {
59 if (p) {
60 std::rethrow_exception(p);
61 }
62 } catch (const shared_exception &e) {
63 py::set_error(PyExc_KeyError, e.what());
64 }
65 });
66
67 // translate the local exception into a key error but only in this module
68 py::register_local_exception_translator([](std::exception_ptr p) {
69 try {
70 if (p) {
71 std::rethrow_exception(p);
72 }
73 } catch (const LocalException &e) {
74 py::set_error(PyExc_KeyError, e.what());
75 }
76 });
77
78 // test_local_bindings.py
79 // Local to both:
80 bind_local<LocalType, 1>(m, "LocalType", py::module_local()).def("get2", [](LocalType &t) {
81 return t.i + 2;
82 });
83
84 // Can only be called with our python type:
85 m.def("local_value", [](LocalType &l) { return l.i; });

Callers

nothing calls this directly

Calls 11

module_localClass · 0.85
LocalExceptionClass · 0.85
set_errorFunction · 0.70
docMethod · 0.45
whatMethod · 0.45
beginMethod · 0.45
endMethod · 0.45
nameMethod · 0.45

Tested by

no test coverage detected