The Python C API has the function PyImport_ImportModule
that returns a new reference to the module. As a new reference, it must be disposed of at some point.
Most objects created during module initialization are added to the module with PyModule_AddObject
, which steals the reference (when successful). However, I'd like to store the module reference from PyImport_ImportModule
in a global variable for quick access. Something like this:
#include <Python.h>
static PyObject *imported_module;
static PyModuleDef myextension_module = {
PyModuleDef_HEAD_INIT,
.m_name = "myextension",
.m_doc = "My extension module that uses an imported module",
.m_size = -1,
};
PyMODINIT_FUNC PyInit_myextension(void)
{
// ...
PyObject *m;
m = PyModule_Create(&md4c_module);
if (m == NULL) {
return NULL;
}
// ...
imported_module = PyImport_ImportModule("extratypes");
if (imported_module == NULL) {
Py_DECREF(m);
return NULL;
}
// Presumably, imported_module needs to be Py_DECREF'd at some point
return m;
}
Is creating traverse/clear/free functions the proper way to clean up (similar to how it is described here, but using these instead), or is it better to just go ahead and PyModule_AddObject
the imported module to the current module (in which case, is it still safe to use the reference that was stolen)? Or are both/neither the correct way to handle it?