The PyModule_New
is the constructor for module objects. It's exposed to pure Python code too, as the __new__
method of the types.ModuleType
class.
It probably is pretty rare for user code to need to use either of those, since you usually get modules by importing them. However, the machinery used by the Python interpreter uses PyModule_New
to make the module objects when an import is requested.
You can see this in import.c
in the Python source:
/* Get the module object corresponding to a module name.
First check the modules dictionary if there's one there,
if not, create a new one and insert it in the modules dictionary.
Because the former action is most common, THIS DOES NOT RETURN A
'NEW' REFERENCE! */
PyImport_AddModule(const char *name)
{
PyObject *modules = PyImport_GetModuleDict();
PyObject *m;
if ((m = PyDict_GetItemString(modules, name)) != NULL &&
PyModule_Check(m))
return m;
m = PyModule_New(name);
if (m == NULL)
return NULL;
if (PyDict_SetItemString(modules, name, m) != 0) {
Py_DECREF(m);
return NULL;
}
Py_DECREF(m); /* Yes, it still exists, in modules! */
return m;
}
As for how to set values in a new module object, you can use regular attribute access. In Python code (rather than C), that's simple:
import types
mymodule = types.ModuleType("mymodule")
mymodule.foo = "foo"
Note that a module created this way can't be imported anywhere else unless you do some additional work. For instance, you can add it to the modules lookup dictionary, sys.modules
:
import sys
sys.modules["mymodule"] = mymodule
Now other modules can import mymodule
by name.