模块对象¶
-
PyTypeObject PyModule_Type¶
- 属于 稳定 ABI.
这个
PyTypeObject的实例代表 Python 模块类型。它作为types.ModuleType被暴露给 Python 程序。
-
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. SeePyModuleDef.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_STRVARis 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_freefunction 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_sizeto-1means that the module does not support sub-interpreters, because it has global state. Negativem_sizeis 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
PyMethodDefvalues. Can beNULLif 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 beNULL.
-
traverseproc m_traverse¶
A traversal function to call during GC traversal of the module object, or
NULLif 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_execfunction). More precisely, this function is not called ifm_sizeis greater than 0 and the module state (as returned byPyModule_GetState()) isNULL.在 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
NULLif 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_execfunction). More precisely, this function is not called ifm_sizeis greater than 0 and the module state (as returned byPyModule_GetState()) isNULL.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 andm_freeis 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
NULLif 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_execfunction). More precisely, this function is not called ifm_sizeis greater than 0 and the module state (as returned byPyModule_GetState()) isNULL.在 3.9 版本发生变更: No longer called before the module state is allocated.
-
PyModuleDef_Base m_base¶
-
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.
-
int slot¶
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
ModuleSpecinstance, as defined in PEP 451, and the module definition. It should return a new module object, or set an error and returnNULL.此函数应当保持最小化。特别地,它不应当调用任意 Python 代码,因为尝试再次导入同一个模块可能会导致无限循环。
Multiple
Py_mod_createslots 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, onlyPyModule_Typeinstances may be returned if thePyModuleDefhas non-NULLm_traverse,m_clear,m_free; non-zerom_size; or slots other thanPy_mod_create.Added in version 3.5.
-
PyObject *create_module(PyObject *spec, PyModuleDef *def)¶
-
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:
If multiple
Py_mod_execslots 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¶
该模块不支持在子解释器中导入。
此槽位决定在子解释器中导入此模块是否会失败。
Multiple
Py_mod_multiple_interpretersslots may not be specified in one module definition.如果未指定
Py_mod_multiple_interpreters,则导入机制默认为Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED值。Added in version 3.12.
-
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED¶
-
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_gilslots may not be specified in one module definition.如果未指定
Py_mod_gil,则导入机制默认为Py_MOD_GIL_USED。Added in version 3.13.
-
Py_MOD_GIL_USED¶
动态创建扩展模块¶
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并设置一个异常。此函数不支持槽位。 def 的
m_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 版起.
创建一个新的模块对象,在参数 def 和 spec 中给出定义,设置 API 版本为参数 module_api_version。如果该版本与正在运行的解释器版本不匹配,则会触发
RuntimeWarning。当发生错误时将返回
NULL并设置一个异常。注意,这不会处理执行槽位 (
Py_mod_exec)。 必须调用PyModule_FromDefAndSpec和PyModule_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
3for 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; }
为了方便,该函数接受
NULLvalue 并设置一个异常。在此情况下,将返回-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_Create或PyModule_FromDefAndSpec等)。一些模块作者可能更喜欢在多个PyMethodDef数组中定义函数;在这种情况下,他们应该直接调用这个函数。functions 数组必须被静态地分配(或者要保证比模块对象生存得更久)。
Added in version 3.5.
-
int PyModule_SetDocString(PyObject *module, const char *docstring)¶
- 属于 稳定 ABI 自 3.7 版起.
将 module 的文档字符串设置为 docstring。此函数在使用
PyModuleDef创建模块时自动调用(例如使用 多阶段初始化、PyModule_Create或PyModule_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.