PyModule_New是模块对象的构造函数。它也公开给纯Python代码,作为types.ModuleType类的__new__方法。在
用户代码可能很少需要使用其中任何一个,因为通常通过导入模块来获取模块。但是,Python解释器使用的机制在请求导入时使用PyModule_New来生成模块对象。在/* 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;
}
至于如何在新的模块对象中设置值,可以使用常规属性访问。在Python代码(而不是C)中,这很简单:
^{pr2}$
请注意,以这种方式创建的模块不能导入到其他任何地方,除非您做了一些额外的工作。例如,您可以将其添加到modules lookup dictionary,sys.modules:import sys
sys.modules["mymodule"] = mymodule
现在其他模块可以按名称导入mymodule。在