Skip to content

Commit d7d782c

Browse files
authored
fix(regression): support embedded submodule (#5650)
* tests: add test for embedded submodule Signed-off-by: Henry Schreiner <[email protected]> * tests: adjust Signed-off-by: Henry Schreiner <[email protected]> * Update test_interpreter.cpp * Update test_interpreter.cpp * Update test_interpreter.cpp * Update test_interpreter.cpp * Update pybind11.h * fix: end instead of endif Signed-off-by: Henry Schreiner <[email protected]> * Update include/pybind11/pybind11.h --------- Signed-off-by: Henry Schreiner <[email protected]>
1 parent 9a191c2 commit d7d782c

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

include/pybind11/pybind11.h

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1342,13 +1342,18 @@ class module_ : public object {
13421342
// GraalPy doesn't support PyModule_GetFilenameObject,
13431343
// so getting by attribute (see PR #5584)
13441344
handle this_module = m_ptr;
1345-
result.attr("__file__") = this_module.attr("__file__");
1345+
if (object this_file = getattr(this_module, "__file__", none())) {
1346+
result.attr("__file__") = this_file;
1347+
}
13461348
#else
13471349
handle this_file = PyModule_GetFilenameObject(m_ptr);
1348-
if (!this_file) {
1350+
if (this_file) {
1351+
result.attr("__file__") = this_file;
1352+
} else if (PyErr_ExceptionMatches(PyExc_SystemError) != 0) {
1353+
PyErr_Clear();
1354+
} else {
13491355
throw error_already_set();
13501356
}
1351-
result.attr("__file__") = this_file;
13521357
#endif
13531358
attr(name) = result;
13541359
return result;

tests/test_embed/test_interpreter.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ PYBIND11_EMBEDDED_MODULE(widget_module, m) {
6161
.def_property_readonly("the_message", &Widget::the_message);
6262

6363
m.def("add", [](int i, int j) { return i + j; });
64+
65+
auto sub = m.def_submodule("sub");
66+
sub.def("add", [](int i, int j) { return i + j; });
6467
}
6568

6669
PYBIND11_EMBEDDED_MODULE(trampoline_module, m) {
@@ -316,6 +319,9 @@ TEST_CASE("Restart the interpreter") {
316319
auto cpp_module = py::module_::import("widget_module");
317320
REQUIRE(cpp_module.attr("add")(1, 2).cast<int>() == 3);
318321

322+
// Also verify submodules work
323+
REQUIRE(cpp_module.attr("sub").attr("add")(1, 41).cast<int>() == 42);
324+
319325
// C++ type information is reloaded and can be used in python modules.
320326
auto py_module = py::module_::import("test_interpreter");
321327
auto py_widget = py_module.attr("DerivedWidget")("Hello after restart");

0 commit comments

Comments
 (0)