模块对象

PyTypeObject PyModule_Type
属于 稳定 ABI.

这个 PyTypeObject 的实例代表 Python 模块类型。它作为 types.ModuleType 被暴露给 Python 程序。

int PyModule_Check(PyObject *p)

p 为模块类型的对象,或是模块子类型的对象时返回真值。该函数永远有返回值。

int PyModule_CheckExact(PyObject *p)

p 为模块类型的对象且不是 PyModule_Type 的子类型的对象时返回真值。该函数永远有返回值。

PyObject *PyModule_NewObject(PyObject *name)
返回值:新的引用。 属于 稳定 ABI 自 3.7 版起.

返回一个新的模块对象,该对象的 module.__name__ 将设为 name。模块的 __name__, __doc__, __package____loader__ 属性将被填充 (除 __name__ 外全都设为 None)。 调用方要负责设置 __file__ 属性。

当发生错误时将返回 NULL 并设置一个异常。

Added in version 3.3.

在 3.4 版本发生变更: 现在 __package____loader__ 将被设为 None

PyObject *PyModule_New(const char *name)
返回值:新的引用。 属于 稳定 ABI.

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

PyObject *PyModule_GetDict(PyObject *module)
返回值:借入的引用。 属于 稳定 ABI.

返回实现 module 的命名空间的字典对象;此对象与模块对象的 __dict__ 属性相同。如果 module 不是一个模块对象(或模块对象的子类型),则会引发 SystemError 并返回 NULL

建议扩展使用其他 PyModule_*PyObject_* 函数而不是直接操纵模块的 __dict__ 属性。

返回的引用是从模块借入的;它将保持可用直到模块被销毁。

PyObject *PyModule_GetNameObject(PyObject *module)
返回值:新的引用。 属于 稳定 ABI 自 3.7 版起.

返回 module__name__ 值。如果模块未提供该值,或者如果它不是一个字符串,则会引发 SystemError 并返回 NULL

Added in version 3.3.

const char *PyModule_GetName(PyObject *module)
属于 稳定 ABI.

类似于 PyModule_GetNameObject() 但返回 'utf-8' 编码的名称。

返回的缓冲区将保持可用直到模块被重命名或销毁。请注意 Python 代码可能会通过设置其 __name__ 属性来重命名一个模块。

void *PyModule_GetState(PyObject *module)
属于 稳定 ABI.

Return the "state" of the module, that is, a pointer to the block of memory allocated at module creation time, or NULL. See PyModuleDef.m_size.

PyModuleDef *PyModule_GetDef(PyObject *module)
属于 稳定 ABI.

返回指向模块创建所使用的 PyModuleDef 结构体的指针,或者如果模块不是使用结构体定义创建的则返回 NULL

出错时,返回 NULL 并设置一个异常。使用 PyErr_Occurred() 将这种情况与缺少 PyModuleDef 区分开来。

PyObject *PyModule_GetFilenameObject(PyObject *module)
返回值:新的引用。 属于 稳定 ABI.

返回使用 module__file__ 属性所加载的 module 所对应的文件名。 如果未定义该属性,或者如果它不是一个字符串,则会引发 SystemError 并返回 NULL;在其他情况下将返回一个指向 Unicode 对象的引用。

Added in version 3.2.

const char *PyModule_GetFilename(PyObject *module)
属于 稳定 ABI.

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

返回的缓冲区将保持可用直到模块的 __file__ 属性被重新赋值或模块被销毁。

自 3.2 版本弃用: PyModule_GetFilename() 对于不可编码的文件名会引发 UnicodeEncodeError,请改用 PyModule_GetFilenameObject() 函数。

Module definitions

The functions in the previous section work on any module object, including modules imported from Python code.

Modules defined using the C API typically use a module definition, PyModuleDef -- a statically allocated, constant “description" of how a module should be created.

The definition is usually used to define an extension's “main” module object (see 定义扩展模块 for details). It is also used to create extension modules dynamically.

Unlike PyModule_New(), the definition allows management of module state -- a piece of memory that is allocated and cleared together with the module object. Unlike the module's Python attributes, Python code cannot replace or delete data stored in module state.

type PyModuleDef
属于 稳定 ABI (包括所有成员).

The module definition struct, which holds all information needed to create a module object. This structure must be statically allocated (or be otherwise guaranteed to be valid while any modules created from it exist). Usually, there is only one variable of this type for each extension module.

PyModuleDef_Base m_base

Always initialize this member to PyModuleDef_HEAD_INIT.

const char *m_name

Name for the new module.

const char *m_doc

Docstring for the module; usually a docstring variable created with PyDoc_STRVAR is used.

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.

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.

Setting m_size to -1 means that the module does not support sub-interpreters, because it has global state. Negative m_size is only allowed when using legacy single-phase initialization or when creating modules dynamically.

请参阅 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 legacy single-phase initialization, m_slots must be NULL.

在 3.5 版本发生变更: 在 3.5 版之前,此成员总是被设为 NULL,并被定义为:

inquiry m_reload
traverseproc m_traverse

A traversal function to call during GC traversal of the module object, or NULL if not needed.

This function is not called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed (Py_mod_exec function). More precisely, this function is not called if m_size is greater than 0 and the module state (as returned by PyModule_GetState()) is NULL.

在 3.9 版本发生变更: No longer called before the module state is allocated.

inquiry m_clear

A clear function to call during GC clearing of the module object, or NULL if not needed.

This function is not called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed (Py_mod_exec function). More precisely, this function is not called if m_size is greater than 0 and the module state (as returned by PyModule_GetState()) is NULL.

Like PyTypeObject.tp_clear, this function is not always called before a module is deallocated. For example, when reference counting is enough to determine that an object is no longer used, the cyclic garbage collector is not involved and m_free is called directly.

在 3.9 版本发生变更: No longer called before the module state is allocated.

freefunc m_free

A function to call during deallocation of the module object, or NULL if not needed.

This function is not called if the module state was requested but is not allocated yet. This is the case immediately after the module is created and before the module is executed (Py_mod_exec function). More precisely, this function is not called if m_size is greater than 0 and the module state (as returned by PyModule_GetState()) is NULL.

在 3.9 版本发生变更: No longer called before the module state is allocated.

PyTypeObject PyModuleDef_Type
属于 稳定 ABI 自 3.5 版起.

PyModuleDef 对象的类型。

Module slots

type PyModuleDef_Slot
属于 稳定 ABI (包括所有成员) 自 3.5 版起.
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.

Added in version 3.5.

The available slot types are:

Py_mod_create
属于 稳定 ABI 自 3.5 版起.

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

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

The function receives a ModuleSpec instance, as defined in PEP 451, and the module definition. It should return a new module object, or set an error and return NULL.

此函数应当保持最小化。特别地,它不应当调用任意 Python 代码,因为尝试再次导入同一个模块可能会导致无限循环。

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

如果未指定 Py_mod_create,导入机制将使用 PyModule_New() 创建一个普通的模块对象。名称是获取自 spec 而非定义,以允许扩展模块动态地调整它们在模块层级结构中的位置并通过符号链接以不同的名称被导入,同时共享同一个模块定义。

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.

Added in version 3.5.

Py_mod_exec
属于 稳定 ABI 自 3.5 版起.

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)

If multiple Py_mod_exec slots are specified, they are processed in the order they appear in the m_slots array.

Added in version 3.5.

Py_mod_multiple_interpreters
属于 稳定 ABI 自 3.12 版起.

Specifies one of the following values:

Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED

该模块不支持在子解释器中导入。

Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED

该模块支持在子解释器中导入,但是它们必须要共享主解释器的 GIL。 (参见 隔离扩展模块。)

Py_MOD_PER_INTERPRETER_GIL_SUPPORTED

该模块支持在子解释器中导入,即使它们有自己的 GIL。 (参见 隔离扩展模块。)

此槽位决定在子解释器中导入此模块是否会失败。

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

如果未指定 Py_mod_multiple_interpreters,则导入机制默认为 Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED 值。

Added in version 3.12.

Py_mod_gil
属于 稳定 ABI 自 3.13 版起.

Specifies one of the following values:

Py_MOD_GIL_USED

这个模块依赖于全局解释器锁 (GIL) 的存在,并可在无需同步的情况下访问全局状态。

Py_MOD_GIL_NOT_USED

这个模块可以在不激活 GIL 的情况下安全运行。

这个槽位会被未配置 --disable-gil 的 Python 构建版所忽略。在其他情况下,它将决定导入此模块是否会导致 GIL 被自动启用。请参阅 自由线程的 CPython 了解详情。

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

如果未指定 Py_mod_gil,则导入机制默认为 Py_MOD_GIL_USED

Added in version 3.13.

动态创建扩展模块

The following functions may be used to create a module outside of an extension's initialization function. They are also used in single-phase initialization.

PyObject *PyModule_Create(PyModuleDef *def)
返回值:新的引用。

根据 def 中的定义创建一个新的模块对象。这是一个调用 PyModule_Create2() 的宏,其中 module_api_version 设置为 PYTHON_API_VERSION,或者如果使用 受限 API,则设置为 PYTHON_ABI_VERSION

PyObject *PyModule_Create2(PyModuleDef *def, int module_api_version)
返回值:新的引用。 属于 稳定 ABI.

创建一个新的模块对象,在参数 def 中给出定义,设定 API 版本为参数 module_api_version。如果该版本与正在运行的解释器版本不匹配,则会触发 RuntimeWarning

当发生错误时将返回 NULL 并设置一个异常。

此函数不支持槽位。 defm_slots 成员必须为 NULL

备注

大多数时候应该使用 PyModule_Create() 代替使用此函数,除非你确定需要使用它。

PyObject *PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
返回值:新的引用。

这个宏调用 PyModule_FromDefAndSpec2()module_api_version 设置为 PYTHON_API_VERSION,或者如果使用 受限 API,则设置为 PYTHON_ABI_VERSION 常量。

Added in version 3.5.

PyObject *PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
返回值:新的引用。 属于 稳定 ABI 自 3.7 版起.

创建一个新的模块对象,在参数 defspec 中给出定义,设置 API 版本为参数 module_api_version。如果该版本与正在运行的解释器版本不匹配,则会触发 RuntimeWarning

当发生错误时将返回 NULL 并设置一个异常。

注意,这不会处理执行槽位 (Py_mod_exec)。 必须调用 PyModule_FromDefAndSpecPyModule_ExecDef 来完全初始化模块。

备注

大多数时候应该使用 PyModule_FromDefAndSpec() 代替使用此函数,除非你确定需要使用它。

Added in version 3.5.

int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
属于 稳定 ABI 自 3.7 版起.

处理在 def 中给出的任何执行槽位 (Py_mod_exec)。

Added in version 3.5.

PYTHON_API_VERSION

The C API version. Defined for backwards compatibility.

目前,该常量在新的 Python 版本中没有更新,并且对于版本控制没有用处。这在未来可能会改变。

PYTHON_ABI_VERSION

Defined as 3 for backwards compatibility.

目前,该常量在新的 Python 版本中没有更新,并且对于版本控制没有用处。这在未来可能会改变。

支持函数

The following functions are provided to help initialize a module state. They are intended for a module's execution slots (Py_mod_exec), the initialization function for legacy single-phase initialization, or code that creates modules dynamically.

int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
属于 稳定 ABI 自 3.10 版起.

将一个对象以 name 为名称添加到 module 中。这是一个便捷函数,可在模块的初始化函数中使用。

如果成功,返回 0。如果发生错误,引发异常并返回 -1

用法示例:

static int
add_spam(PyObject *module, int value)
{
    PyObject *obj = PyLong_FromLong(value);
    if (obj == NULL) {
        return -1;
    }
    int res = PyModule_AddObjectRef(module, "spam", obj);
    Py_DECREF(obj);
    return res;
 }

为了方便,该函数接受 NULL value 并设置一个异常。在此情况下,将返回 -1 并让所引发的异常保持不变。

这个例子也可以写成不显式地检查 obj 是否为 NULL:

static int
add_spam(PyObject *module, int value)
{
    PyObject *obj = PyLong_FromLong(value);
    int res = PyModule_AddObjectRef(module, "spam", obj);
    Py_XDECREF(obj);
    return res;
 }

注意在此情况下应当使用 Py_XDECREF() 而不是 Py_DECREF(),因为 obj 可能为 NULL

传给该函数的不同 name 字符串应当保持在较少的数量,通常是通过仅使用静态分配的字符串作为 name 来做到这一点。 对于编译时未知的名称,建议直接调用 PyUnicode_FromString()PyObject_SetAttr()。更多相关细节,请参阅 PyUnicode_InternFromString(),它可在内部用于创建键对象。

Added in version 3.10.

int PyModule_Add(PyObject *module, const char *name, PyObject *value)
属于 稳定 ABI 自 3.13 版起.

类似于 PyModule_AddObjectRef(),但会“偷取”一个指向 value 的引用。 它在被调用时可附带一个返回新引用的函数的结果而无需检查其结果或是将其保存到一个变量。

用法示例:

if (PyModule_Add(module, "spam", PyBytes_FromString(value)) < 0) {
    goto error;
}

Added in version 3.13.

int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
属于 稳定 ABI.

类似于 PyModule_AddObjectRef(),但会在成功时偷取一个对 value 的引用(如果它返回 0 值)。

推荐使用新的 PyModule_Add()PyModule_AddObjectRef() 函数,因为误用 PyModule_AddObject() 函数很容易导致引用泄漏。

备注

与其他窃取引用的函数不同,PyModule_AddObject() 只在 成功 时释放对 value 的引用。

这意味着必须检查它的返回值,调用方代码必须在发生错误时手动为 value 执行 Py_XDECREF()

用法示例:

PyObject *obj = PyBytes_FromString(value);
if (PyModule_AddObject(module, "spam", obj) < 0) {
    // 如果 'obj' 不为 NULL 且 PyModule_AddObject() 执行失败,
    // 则 'obj' 强引用必须使用 Py_XDECREF() 来删除。
    // 如果 'obj' 为 NULL,则 Py_XDECREF() 不做任何操作。
    Py_XDECREF(obj);
    goto error;
}
// PyModule_AddObject() 会偷取一个对 obj 的引用:
// 这里不需要 Py_XDECREF(obj)。

自 3.13 版起已处于 Soft deprecated 状态.

int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
属于 稳定 ABI.

将一个整数常量作为 name 添加到 module 中。这个便捷函数可在模块的初始化函数中使用。当发生错误时将返回 -1 并设置一个异常,成功时则返回 0

这是一个调用 PyLong_FromLong()PyModule_AddObjectRef() 的便捷函数;请参阅其文档了解详情。

int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
属于 稳定 ABI.

将一个字符串常量作为 name 添加到 module 中。这个便捷函数可在模块初始化函数中使用。字符串 value 必须以 NULL 结尾。当发生错误时将返回 -1,成功时则返回 0

这是一个调用 PyUnicode_InternFromString()PyModule_AddObjectRef() 的便捷函数;请参阅其文档了解详情。

PyModule_AddIntMacro(module, macro)

将一个整数常量添加到 module 中。名称和值取自 macro。例如 PyModule_AddIntMacro(module, AF_INET) 将值为 AF_INET 的整数常量 AF_INET 添加到 module 中。当发生错误时将返回 -1 并设置一个异常,成功时将返回 0

PyModule_AddStringMacro(module, macro)

将一个字符串常量添加到*module*模块中。

int PyModule_AddType(PyObject *module, PyTypeObject *type)
属于 稳定 ABI 自 3.10 版起.

将一个类型对象添加到 module 中。类型对象是通过在内部调用 PyType_Ready() 来最终化的。类型对象的名称取自 tp_name 在点号之后的部分。当发生错误时将返回 -1 并设置一个异常,成功时将返回 0

Added in version 3.9.

int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
属于 稳定 ABI 自 3.7 版起.

将以 NULL 结尾的 functions 数组中的函数添加到 module 中。有关单个条目的更多细节,请参阅 PyMethodDef 文档(由于缺少共享的模块命名空间,在 C 中实现的模块级"函数"通常将模块作为其第一个形参,与 Python 类的实例方法类似)。

此函数在从 PyModuleDef 创建模块时自动调用(例如使用 多阶段初始化PyModule_CreatePyModule_FromDefAndSpec 等)。一些模块作者可能更喜欢在多个 PyMethodDef 数组中定义函数;在这种情况下,他们应该直接调用这个函数。

functions 数组必须被静态地分配(或者要保证比模块对象生存得更久)。

Added in version 3.5.

int PyModule_SetDocString(PyObject *module, const char *docstring)
属于 稳定 ABI 自 3.7 版起.

module 的文档字符串设置为 docstring。此函数在使用 PyModuleDef 创建模块时自动调用(例如使用 多阶段初始化PyModule_CreatePyModule_FromDefAndSpec 时)。

成功时返回 0。出错时返回 -1 并设置异常。

Added in version 3.5.

int PyUnstable_Module_SetGIL(PyObject *module, void *gil)
这是 不稳定 API。它可能在次要版本中不经警告地被更改。

指明 module 是否支持不带全局解释器锁 (GIL) 运行,使用一个来自 Py_mod_gil 的值。当使用 旧式的单阶段初始化 时它必须在 module 的初始化函数执行期间被调用。 如果此函数在模块初始化期间未被调用,导入机制将假定该模块不支持不带 GIL 运行。此函数仅在配置了 --disable-gil 的 Python 构建版中可用。当发生错误时将返回 -1 并设置一个异常,成功时将返回 0

Added in version 3.13.

模块查找(单阶段初始化)

遗留的 单阶段初始化 初始化方案创建可以在当前解释器上下文中被查找的单例模块。这使得仅通过模块定义的引用,就可以检索模块对象。

这些函数不适用于通过多阶段初始化创建的模块,因为可以从一个模块定义创建多个模块对象。

PyObject *PyState_FindModule(PyModuleDef *def)
返回值:借入的引用。 属于 稳定 ABI.

返回当前解释器中由 def 创建的模块对象。此方法要求模块对象此前已通过 PyState_AddModule() 函数附加到解释器状态中。如果找不到相应的模块对象,或模块对象还未附加到解释器状态,返回 NULL

int PyState_AddModule(PyObject *module, PyModuleDef *def)
属于 稳定 ABI 自 3.3 版起.

将传给函数的模块对象附加到解释器状态。这将允许通过 PyState_FindModule() 来访问该模块对象。

仅在使用单阶段初始化创建的模块上有效。

Python 会在使用 单阶段初始化 导入一个模块后自动调用 PyState_AddModule,因此从模块初始化代码中调用它是没有必要的(但也没有害处)。显式的调用仅在模块自己的初始化代码后继调用了 PyState_FindModule 的情况下才是必要的。 此函数主要是为了实现替代导入机制(或是通过直接调用它,或是通过引用它的实现来获取所需的状态更新详情)。

如果先前使用相同的 def 附加了一个模块,则将其替换为新的 module

调用方必须有已附加的线程状态 attached thread state

出错时返回 -1 并设置一个异常,成功时返回 0

Added in version 3.3.

int PyState_RemoveModule(PyModuleDef *def)
属于 稳定 ABI 自 3.3 版起.

从解释器状态中移除由 def 创建的模块对象。当发生错误时将返回 -1 并设置一个异常,成功时将返回 0

调用方必须有已附加的线程状态 attached thread state

Added in version 3.3.