模块对象

PyTypeObject PyModule_Type

此实例的 PyTypeObject 表示 Python 模块类型。暴露这给 Python 程序作为 types.ModuleType .

int PyModule_Check ( PyObject  *p )

返回 True 若 p 是模块对象,或模块对象的子类型。

int PyModule_CheckExact ( PyObject  *p )

返回 True 若 p 是模块对象,但不是子类型的 PyModule_Type .

PyObject * PyModule_NewObject ( PyObject  *name )

返回新的模块对象采用 __name__ 属性设置为 name 。模块的 __name__ , __doc__ , __package__ ,和 __loader__ 属性被填充(除了 __name__ 被设为 None );调用者负责提供 __file__ 属性。

3.3 版新增。

3.4 版改变: __package__ and __loader__ 被设为 None .

PyObject * PyModule_New ( const char  *name )
返回值:新引用。

类似 PyModule_NewObject() ,但名称是 UTF-8 编码字符串,而不是 Unicode 对象。

PyObject * PyModule_GetDict ( PyObject  *module )
返回值:借位引用。

Return the dictionary object that implements 模块 ’s namespace; this object is the same as the __dict__ attribute of the module object. If 模块 is not a module object (or a subtype of a module object), SystemError is raised and NULL 被返回。

It is recommended extensions use other PyModule_*() and PyObject_*() functions rather than directly manipulate a module’s __dict__ .

PyObject * PyModule_GetNameObject ( PyObject  *module )

返回 模块 ’s __name__ value. If the module does not provide one, or if it is not a string, SystemError is raised and NULL 被返回。

3.3 版新增。

char* PyModule_GetName ( PyObject  *module )

类似 PyModule_GetNameObject() but return the name encoded to 'utf-8' .

void* PyModule_GetState ( PyObject  *module )

Return the “state” of the module, that is, a pointer to the block of memory allocated at module creation time, or NULL 。见 PyModuleDef.m_size .

PyModuleDef * PyModule_GetDef ( PyObject  *module )

返回指针指向 PyModuleDef struct from which the module was created, or NULL if the module wasn’t created from a definition.

PyObject * PyModule_GetFilenameObject ( PyObject  *module )

Return the name of the file from which 模块 was loaded using 模块 ’s __file__ attribute. If this is not defined, or if it is not a unicode string, raise SystemError 并返回 NULL ; otherwise return a reference to a Unicode object.

3.2 版新增。

char* PyModule_GetFilename ( PyObject  *module )

类似 PyModule_GetFilenameObject() 但返回编码为 utf-8 的文件名。

从 3.2 版起弃用: PyModule_GetFilename() 引发 UnicodeEncodeError 当文件名不可编码时,使用 PyModule_GetFilenameObject() 代替。

初始化 C 模块

Modules objects are usually created from extension modules (shared libraries which export an initialization function), or compiled-in modules (where the initialization function is added using PyImport_AppendInittab() )。见 构建 C/C++ 扩展 or 扩展嵌入式 Python 了解细节。

The initialization function can either pass a module definition instance to PyModule_Create() , and return the resulting module object, or request “multi-phase initialization” by returning the definition struct itself.

PyModuleDef

The module definition struct, which holds all information needed to create a module object. There is usually only one statically initialized variable of this type for each module.

PyModuleDef_Base m_base

始终将此成员初始化为 PyModuleDef_HEAD_INIT .

char* m_name

新模块的名称。

char* m_doc

Docstring for the module; usually a docstring variable created with PyDoc_STRVAR() 被使用。

Py_ssize_t m_size

Module state may be kept in a per-module memory area that can be retrieved with PyModule_GetState() , rather than in static globals. This makes modules safe for use in multiple sub-interpreters.

This memory area is allocated based on m_size on module creation, and freed when the module object is deallocated, after the m_free function has been called, if present.

设置 m_size to -1 means that the module does not support sub-interpreters, because it has global state.

Setting it to a non-negative value means that the module can be re-initialized and specifies the additional amount of memory it requires for its state. Non-negative m_size is required for multi-phase initialization.

PEP 3121 了解更多细节。

PyMethodDef * m_methods

A pointer to a table of module-level functions, described by PyMethodDef values. Can be NULL if no functions are present.

PyModuleDef_Slot * m_slots

An array of slot definitions for multi-phase initialization, terminated by a {0, NULL} entry. When using single-phase initialization, m_slots 必须是 NULL .

3.5 版改变: Prior to version 3.5, this member was always set to NULL , and was defined as:

traverseproc m_traverse

A traversal function to call during GC traversal of the module object, or NULL if not needed. This function may be called before module state is allocated ( PyModule_GetState() may return NULL ), and before the Py_mod_exec function is executed.

inquiry m_clear

A clear function to call during GC clearing of the module object, or NULL if not needed. This function may be called before module state is allocated ( PyModule_GetState() may return NULL ), and before the Py_mod_exec function is executed.

freefunc m_free

A function to call during deallocation of the module object, or NULL if not needed. This function may be called before module state is allocated ( PyModule_GetState() may return NULL ), and before the Py_mod_exec function is executed.

单阶段初始化

模块初始化函数可以直接创建并返回模块对象。这被称为单阶段初始化,并使用以下 2 模块创建函数之一:

PyObject * PyModule_Create ( PyModuleDef  *def )

创建新的模块对象,给定定义在 def 。这的行为像 PyModule_Create2() with module_api_version 设为 PYTHON_API_VERSION .

PyObject * PyModule_Create2 ( PyModuleDef  *def , int  module_api_version )

创建新的模块对象,给定定义在 def ,假定 API 版本 module_api_version 。若该版本不匹配正运行解释器版本, RuntimeWarning 被发射。

注意

此函数的大多数用途应该是使用 PyModule_Create() 代替;才使用这若确定需要它。

在从初始化函数中返回之前,通常填充产生的模块对象使用函数像 PyModule_AddObject() .

多阶段初始化

指定扩展的替代方式是请求多阶段初始化。这种方式创建的扩展模块的行为更像 Python 模块:初始化被拆分成 创建阶段 ,当模块对象被创建时,和 执行阶段 ,当它被填充时。区别类似于 __new__() and __init__() 方法对于类。

不像使用单阶段初始化创建的模块,这些模块不是单例:若 sys.modules entry is removed and the module is re-imported, a new module object is created, and the old module is subject to normal garbage collection – as with Python modules. By default, multiple modules created from the same definition should be independent: changes to one should not affect the others. This means that all state should be specific to the module object (using e.g. using PyModule_GetState() ), or its contents (such as the module’s __dict__ or individual classes created with PyType_FromSpec() ).

All modules created using multi-phase initialization are expected to support 子解释器 . Making sure multiple modules are independent is typically enough to achieve this.

To request multi-phase initialization, the initialization function (PyInit_modulename) returns a PyModuleDef 实例采用非空 m_slots 。在返回它之前, PyModuleDef 实例必须采用以下函数被初始化:

PyObject * PyModuleDef_Init ( PyModuleDef  *def )

确保模块定义是被正确初始化的 Python 对象 (可以正确报告其类型和引用计数)。

返回 def 铸造到 PyObject* ,或 NULL 若发生错误。

3.5 版新增。

m_slots member of the module definition must point to an array of PyModuleDef_Slot 结构:

PyModuleDef_Slot
int slot

A slot ID, chosen from the available values explained below.

void* value

Value of the slot, whose meaning depends on the slot ID.

3.5 版新增。

m_slots 数组必须被终止通过槽采用 ID 0。

可用槽类型:

Py_mod_create

Specifies a function that is called to create the module object itself. value pointer of this slot must point to a function of the signature:

PyObject * create_module ( PyObject  *spec , PyModuleDef  *def )

函数接收 ModuleSpec 实例,作为定义在 PEP 451 , and the module definition. It should return a new module object, or set an error and return NULL .

This function should be kept minimal. In particular, it should not call arbitrary Python code, as trying to import the same module again may result in an infinite loop.

Multiple Py_mod_create slots may not be specified in one module definition.

Py_mod_create is not specified, the import machinery will create a normal module object using PyModule_New() . The name is taken from spec , not the definition, to allow extension modules to dynamically adjust to their place in the module hierarchy and be imported under different names through symlinks, all while sharing a single module definition.

There is no requirement for the returned object to be an instance of PyModule_Type . Any type can be used, as long as it supports setting and getting import-related attributes. However, only PyModule_Type instances may be returned if the PyModuleDef has non- NULL m_traverse , m_clear , m_free ; non-zero m_size ; or slots other than Py_mod_create .

Py_mod_exec

Specifies a function that is called to execute the module. This is equivalent to executing the code of a Python module: typically, this function adds classes and constants to the module. The signature of the function is:

int exec_module ( PyObject *  module )

若多个 Py_mod_exec slots are specified, they are processed in the order they appear in the m_slots array.

PEP 489 了解多阶段初始化的更多细节。

低级模块创建函数

在幕后调用以下函数,当使用多阶段初始化时。可以直接使用它们 (譬如:当动态创建模块对象时)。注意 PyModule_FromDefAndSpec and PyModule_ExecDef 必须被调用以完全初始化模块。

PyObject * PyModule_FromDefAndSpec ( PyModuleDef  *def , PyObject  *spec )

创建新的模块对象,给定定义在 模块 和 ModuleSpec spec 。这的行为像 PyModule_FromDefAndSpec2() with module_api_version 设为 PYTHON_API_VERSION .

3.5 版新增。

PyObject * PyModule_FromDefAndSpec2 ( PyModuleDef  *def , PyObject  *spec , int  module_api_version )

创建新的模块对象,给定定义在 模块 和 ModuleSpec spec ,假定 API 版本 module_api_version 。若该版本不匹配正运行解释器版本, RuntimeWarning 被发射。

注意

此函数的大多数用途应该是使用 PyModule_FromDefAndSpec() 代替;才使用这若确定需要它。

3.5 版新增。

int PyModule_ExecDef ( PyObject  *module , PyModuleDef  *def )

处理任何执行槽 ( Py_mod_exec ) 给定在 def .

3.5 版新增。

int PyModule_SetDocString ( PyObject  *module , const char  *docstring )

设置 docstring 对于 模块 to docstring 。自动调用此函数当创建模块从 PyModuleDef ,使用 PyModule_Create or PyModule_FromDefAndSpec .

3.5 版新增。

int PyModule_AddFunctions ( PyObject  *module , PyMethodDef  *functions )

添加函数从 NULL terminated 函数 数组到 模块 。参考 PyMethodDef documentation for details on individual entries (due to the lack of a shared module namespace, module level “functions” implemented in C typically receive the module as their first parameter, making them similar to instance methods on Python classes). This function is called automatically when creating a module from PyModuleDef ,使用 PyModule_Create or PyModule_FromDefAndSpec .

3.5 版新增。

支持函数

模块初始化函数 (若使用单阶段初始化) 或从模块执行槽调用的函数 (若使用多阶段初始化),可以使用下列函数以帮助初始化模块状态:

int PyModule_AddObject ( PyObject  *module , const char  *name , PyObject  *value )

将对象添加到 模块 as name 。这是可以从模块初始化函数中使用的方便函数。这窃取引用对于 value 。返回 -1 当出错时, 0 当成功时。

int PyModule_AddIntConstant ( PyObject  *module , const char  *name , long  value )

将整数常量添加到 模块 as name 。这是可以从模块初始化函数中使用的方便函数。返回 -1 当出错时, 0 当成功时。

int PyModule_AddStringConstant ( PyObject  *module , const char  *name , const char  *value )

将字符串常量添加到 模块 as name 。这是可以从模块初始化函数中使用的方便函数。字符串 value 必须是 NULL 结尾。返回 -1 当出错时, 0 当成功时。

int PyModule_AddIntMacro ( PyObject  *module , macro )

将整数常量添加到 模块 。名称和值取自 macro 。例如 PyModule_AddIntMacro(module, AF_INET) 添加 int 常量 AF_INET 采用值的 AF_INET to 模块 。返回 -1 当出错时, 0 当成功时。

int PyModule_AddStringMacro ( PyObject  *module , macro )

将字符串常量添加到 模块 .

模块查找

单阶段初始化创建的单例模块 (可以在当前解释器上下文中查找)。这允许稍后采用仅模块定义的引用来检索模块对象。

这些函数不会工作于使用多阶段初始化创建的模块,因为可以从单个定义创建多个这种模块。

PyObject * PyState_FindModule ( PyModuleDef  *def )

Returns the module object that was created from def for the current interpreter. This method requires that the module object has been attached to the interpreter state with PyState_AddModule() beforehand. In case the corresponding module object is not found or has not been attached to the interpreter state yet, it returns NULL .

int PyState_AddModule ( PyObject  *module , PyModuleDef  *def )

Attaches the module object passed to the function to the interpreter state. This allows the module object to be accessible via PyState_FindModule() .

才有效当使用单阶段初始化创建模块时。

3.3 版新增。

int PyState_RemoveModule ( PyModuleDef  *def )

移除创建的模块对象自 def 从解释器状态。

3.3 版新增。