Skip to content

Commit c25ca33

Browse files
common: Prevent module re-import duplication in Python3
1 parent b680abc commit c25ca33

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

include/pybind11/detail/common.h

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,18 @@
171171
#define PYBIND11_PLUGIN_IMPL(name) \
172172
extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
173173

174-
#else
174+
#define PYBIND11_CHECK_REIMPORT(m) \
175+
{ \
176+
static py::handle m##_original; \
177+
if (m##_original) { \
178+
m = py::reinterpret_borrow<py::module>(m##_original); \
179+
return m.ptr(); \
180+
} else { \
181+
m##_original = m; \
182+
} \
183+
}
184+
185+
#else // PY_MAJOR_VERSION >= 3
175186
#define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyMethod_New(ptr, nullptr, class_)
176187
#define PYBIND11_INSTANCE_METHOD_CHECK PyMethod_Check
177188
#define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyMethod_GET_FUNCTION
@@ -198,6 +209,7 @@
198209
(void)pybind11_init_wrapper(); \
199210
} \
200211
PyObject *pybind11_init_wrapper()
212+
#define PYBIND11_CHECK_REIMPORT(variable)
201213
#endif
202214

203215
#if PY_VERSION_HEX >= 0x03050000 && PY_VERSION_HEX < 0x03050200
@@ -285,6 +297,7 @@ extern "C" {
285297
PYBIND11_PLUGIN_IMPL(name) { \
286298
PYBIND11_CHECK_PYTHON_VERSION \
287299
auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
300+
PYBIND11_CHECK_REIMPORT(m) \
288301
try { \
289302
PYBIND11_CONCAT(pybind11_init_, name)(m); \
290303
return m.ptr(); \

0 commit comments

Comments
 (0)