In moving my code to use module states I have the need to obtain the module object for the “current” module. All I have in the way of context is the PyModuleSpec structure for the module. The following should work (no error checking)…
PyObject *PyModule_GetModuleByDef(struct PyModuleDef *target_def)
{
PyObject *modules = PySys_GetAttrString(“modules”);
Py_ssize_t pos;
PyObject *name, *module;
while (PyDict_Next(modules, &pos, &name, &module))
{
struct PyModuleDef *module_def;
PyModule_GetToken(module, &module_def);
if (module_def == target_def)
{
Py_DECREF(modules);
return module;
}
}
Py_DECREF(modules);
return NULL;
}
…but is there any chance of this being implemented in the stable ABI (and made more efficient of course)?