模块对象¶
-
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并设置一个异常。在 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。在 3.3 版本加入.
-
const char *PyModule_GetName(PyObject *module)¶
- 属于 稳定 ABI.
类似于
PyModule_GetNameObject()但返回'utf-8'编码的名称。返回的缓冲区将保持可用直到模块被重命名或销毁。 请注意 Python 代码可能会通过设置其
__name__属性来重命名一个模块。
-
PyModuleDef *PyModule_GetDef(PyObject *module)¶
- 属于 稳定 ABI.
返回指向模块创建所使用的
PyModuleDef结构体的指针,或者如果模块不是使用结构体定义创建的则返回NULL。出错时,返回
NULL并设置一个异常。 使用PyErr_Occurred()将这种情况与缺少PyModuleDef区分开来。
-
PyObject *PyModule_GetFilenameObject(PyObject *module)¶
- 返回值:新的引用。 属于 稳定 ABI.
返回使用 module 的
__file__属性所加载的 module 所对应的文件名。 如果未定义该属性,或者如果它不是一个字符串,则会引发SystemError并返回NULL;在其他情况下将返回一个指向 Unicode 对象的引用。在 3.2 版本加入.
-
const char *PyModule_GetFilename(PyObject *module)¶
- 属于 稳定 ABI.
类似于
PyModule_GetFilenameObject()但会返回编码为 'utf-8' 的文件名。返回的缓冲区将保持可用直到模块的
__file__属性被重新赋值或模块被销毁。自 3.2 版本弃用:
PyModule_GetFilename()对于不可编码的文件名会引发UnicodeEncodeError,请改用PyModule_GetFilenameObject()。
Module definition¶
Modules created using the C API are typically defined using an array of slots. The slots provide a "description" of how a module should be created.
在 3.15.0a2 (unreleased) 版本发生变更: Previously, a PyModuleDef struct was necessary to define modules.
The older way of defining modules is still available: consult either the
Module definition struct section or earlier versions of this documentation
if you plan to support earlier Python versions.
The slots array is usually used to define an extension module's “main” module object (see 定义扩展模块 for details). It can also be used to create extension modules dynamically.
Unless specified otherwise, the same slot ID may not be repeated in an array of slots.
-
type PyModuleDef_Slot¶
- 属于 稳定 ABI (包括所有成员) 自 3.5 版起.
-
int slot¶
A slot ID, chosen from the available
Py_mod_*values explained below.An ID of 0 marks the end of a
PyModuleDef_Slotarray.
-
void *value¶
槽位值,其含义取决于槽位 ID。
The value may not be NULL. To leave a slot out, omit the
PyModuleDef_Slotentry entirely.
在 3.5 版本加入.
-
int slot¶
Metadata slots¶
-
Py_mod_name¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor the name of the new module, as a NUL-terminated UTF8-encodedconst char *.Note that modules are typically created using a
ModuleSpec, and when they are, the name from the spec will be used instead ofPy_mod_name. However, it is still recommended to include this slot for introspection and debugging purposes.在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_nameinstead to support previous versions.
-
Py_mod_doc¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor the docstring of the new module, as a NUL-terminated UTF8-encodedconst char *.Usually it is set to a variable created with
PyDoc_STRVAR.在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_docinstead to support previous versions.
Feature slots¶
-
Py_mod_abi¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDwhose value points to aPyABIInfostructure describing the ABI that the extension is using.A suitable
PyABIInfovariable can be defined using thePyABIInfo_VARmacro, as in:PyABIInfo_VAR(abi_info); static PyModuleDef_Slot mymodule_slots[] = { {Py_mod_abi, &abi_info}, ... };
When creating a module, Python checks the value of this slot using
PyABIInfo_Check().在 3.15 版本加入.
-
Py_mod_multiple_interpreters¶
- 属于 稳定 ABI 自 3.12 版起.
Slot IDwhose value is one of:-
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED¶
该模块不支持在子解释器中导入。
此槽位决定在子解释器中导入此模块是否会失败。
如果未指定
Py_mod_multiple_interpreters,则导入机制默认为Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED。在 3.12 版本加入.
-
Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED¶
-
Py_mod_gil¶
- 属于 稳定 ABI 自 3.13 版起.
Slot IDwhose value is one of:-
Py_MOD_GIL_USED¶
这个模块依赖于全局解释器锁 (GIL) 的存在,并可访问全局状态而不带同步。
-
Py_MOD_GIL_NOT_USED¶
这个模块可以在不激活 GIL 的情况下安全运行。
这个槽位会被未配置
--disable-gil的 Python 构建版所忽略。 在其他情况下,它将决定导入此模块是否会导致 GIL 被自动启用。 请参阅 自由线程的 CPython 了解详情。如果未指定
Py_mod_gil,则导入机制默认为Py_MOD_GIL_USED。在 3.13 版本加入.
-
Py_MOD_GIL_USED¶
Creation and initialization slots¶
-
Py_mod_create¶
- 属于 稳定 ABI 自 3.5 版起.
Slot IDfor a function that creates the module object itself. The function must have the signature:-
PyObject *create_module(PyObject *spec, PyModuleDef *def)¶
The function will be called with:
spec: a
ModuleSpec-like object, meaning that any attributes defined forimportlib.machinery.ModuleSpechave matching semantics. However, any of the attributes may be missing.def:
NULL, or the module definition if the module is created from one.
The function should return a new module object, or set an error and return
NULL.此函数应当保持最小化。 特别地,它不应当调用任意 Python 代码,因为尝试再次导入同一个模块可能会导致无限循环。
如果未指定
Py_mod_create,导入机制将使用PyModule_New()创建一个普通的模块对象。 名称是获取自 spec 而非定义,以允许扩展模块动态地调整它们在模块层级结构中的位置并通过符号链接以不同的名称被导入,同时共享同一个模块定义。There is no requirement for the returned object to be an instance of
PyModule_Type. However, some slots may only be used withPyModule_Typeinstances; in particular:module state slots (
Py_mod_state_*),
在 3.5 版本加入.
在 3.15.0a2 (unreleased) 版本发生变更: The slots argument may be a
ModuleSpec-like object, rather than a trueModuleSpecinstance. Note that previous versions of CPython did not enforce this.The def argument may now be
NULL, since modules are not necessarily made from definitions. -
PyObject *create_module(PyObject *spec, PyModuleDef *def)¶
-
Py_mod_exec¶
- 属于 稳定 ABI 自 3.5 版起.
Slot IDfor a function that will execute, or initialize, the module. This function does the equivalent to executing the code of a Python module: typically, it adds classes and constants to the module. The signature of the function is:See the 支持函数 section for some useful functions to call.
For backwards compatibility, the
PyModuleDef.m_slotsarray may contain multiplePy_mod_execslots; these are processed in the order they appear in the array. Elsewhere (that is, in arguments toPyModule_FromSlotsAndSpec()and in return values ofPyModExport_<name>), repeating the slot is not allowed.在 3.5 版本加入.
在 3.15.0a2 (unreleased) 版本发生变更: Repeated
Py_mod_execslots are disallowed, except inPyModuleDef.m_slots.
-
Py_mod_methods¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor a table of module-level functions, as an array ofPyMethodDefvalues suitable as the functions argument toPyModule_AddFunctions().Like other slot IDs, a slots array may only contain one
Py_mod_methodsentry. To add functions from multiplePyMethodDefarrays, callPyModule_AddFunctions()in thePy_mod_execfunction.The table must be statically allocated (or otherwise guaranteed to outlive the module object).
在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_methodsinstead to support previous versions.
Module state¶
Extension modules can have module state -- a piece of memory that is allocated on module creation, and freed when the module object is deallocated. The module state is specified using dedicated slots.
A typical use of module state is storing an exception type -- or indeed any type object defined by the module --
Unlike the module's Python attributes, Python code cannot replace or delete data stored in module state.
Keeping per-module information in attributes and module state, rather than in static globals, makes module objects isolated and safer for use in multiple sub-interpreters. It also helps Python do an orderly clean-up when it shuts down.
Extensions that keep references to Python objects as part of module state must
implement Py_mod_state_traverse and Py_mod_state_clear
functions to avoid reference leaks.
To retrieve the state from a given module, use the following functions:
-
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. SeePy_mod_state_size.On error, return
NULLwith an exception set. UsePyErr_Occurred()to tell this case apart from missing module state.
-
int PyModule_GetStateSize(PyObject*, Py_ssize_t *result)¶
- 属于 稳定 ABI 自 3.15 版起.
Set *result to the size of the module's state, as specified using
Py_mod_state_size(orPyModuleDef.m_size), and return 0.On error, set *result to -1, and return -1 with an exception set.
在 3.15.0a2 (unreleased) 版本加入.
Slots for defining module state¶
The following PyModuleDef_Slot.slot IDs are available for
defining the module state.
-
Py_mod_state_size¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor the size of the module state, in bytes.Setting the value 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.
请参阅 PEP 3121 了解详情。
Use
PyModule_GetStateSize()to retrieve the size of a given module.在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_sizeinstead to support previous versions.
-
Py_mod_state_traverse¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor a traversal function to call during GC traversal of the module object.The signature of the function, and meanings of the arguments, is similar as for
PyTypeObject.tp_traverse: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 if the state size (Py_mod_state_size) is greater than 0 and the module state (as returned byPyModule_GetState()) isNULL.在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_sizeinstead to support previous versions.
-
Py_mod_state_clear¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor a clear function to call during GC clearing of the module object.The signature of the function is:
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 if the state size (Py_mod_state_size) is 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 and thePy_mod_state_freefunction is called directly.在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_clearinstead to support previous versions.
-
Py_mod_state_free¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor a function to call during deallocation of the module object.The signature of the function is:
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 if the state size (Py_mod_state_size) is greater than 0 and the module state (as returned byPyModule_GetState()) isNULL.在 3.15.0a2 (unreleased) 版本加入: Use
PyModuleDef.m_freeinstead to support previous versions.
Module token¶
Each module may have an associated token: a pointer-sized value intended to identify of the module state's memory layout. This means that if you have a module object, but you are not sure if it “belongs” to your extension, you can check using code like this:
PyObject *module = <the module in question>
void *module_token;
if (PyModule_GetToken(module, &module_token) < 0) {
return NULL;
}
if (module_token != your_token) {
PyErr_SetString(PyExc_ValueError, "unexpected module")
return NULL;
}
// This module's state has the expected memory layout; it's safe to cast
struct my_state state = (struct my_state*)PyModule_GetState(module)
A module's token -- and the your_token value to use in the above code -- is:
For modules created with
PyModuleDef: the address of thatPyModuleDef;For modules defined with the
Py_mod_tokenslot: the value of that slot;For modules created from an
PyModExport_*export hook: the slots array that the export hook returned (unless overriden withPy_mod_token).
-
Py_mod_token¶
- 属于 稳定 ABI 自 3.15 版起.
Slot IDfor the module token.If you use this slot to set the module token (rather than rely on the default), you must ensure that:
The pointer outlives the class, so it's not reused for something else while the class exists.
It "belongs" to the extension module where the class lives, so it will not clash with other extensions.
If the token points to a
PyModuleDefstruct, the module should behave as if it was created from thatPyModuleDef. In particular, the module state must have matching layout and semantics.
Modules created from
PyModuleDefallways use the address of thePyModuleDefas the token. This means thatPy_mod_tokencannot be used inPyModuleDef.m_slots.在 3.15.0a2 (unreleased) 版本加入.
-
int PyModule_GetToken(PyObject *module, void **result)¶
- 属于 稳定 ABI 自 3.15 版起.
Set *result to the module's token and return 0.
On error, set *result to NULL, and return -1 with an exception set.
在 3.15.0a2 (unreleased) 版本加入.
See also PyType_GetModuleByToken().
动态创建扩展模块¶
The following functions may be used to create an extension module dynamically, rather than from an extension's export hook.
-
PyObject *PyModule_FromSlotsAndSpec(const PyModuleDef_Slot *slots, PyObject *spec)¶
- 返回值:新的引用。 属于 稳定 ABI 自 3.15 版起.
Create a new module object, given an array of slots and the
ModuleSpecspec.The slots argument must point to an array of
PyModuleDef_Slotstructures, terminated by an entry slot with slot ID of 0 (typically written as{0}or{0, NULL}in C). The slots argument may not beNULL.The spec argument may be any
ModuleSpec-like object, as described inPy_mod_createdocumentation. Currently, the spec must have anameattribute.On success, return the new module. On error, return
NULLwith an exception set.Note that this does not process the module's execution slot (
Py_mod_exec). BothPyModule_FromSlotsAndSpec()andPyModule_Exec()must be called to fully initialize a module. (See also 多阶段初始化.)The slots array only needs to be valid for the duration of the
PyModule_FromSlotsAndSpec()call. In particular, it may be heap-allocated.在 3.15.0a2 (unreleased) 版本加入.
-
int PyModule_Exec(PyObject *module)¶
- 属于 稳定 ABI 自 3.15 版起.
Execute the
Py_mod_execslot(s) of the given module.On success, return 0. On error, return -1 with an exception set.
For clarity: If module has no slots, for example if it uses legacy single-phase initialization, this function does nothing and returns 0.
在 3.15.0a2 (unreleased) 版本加入.
Module definition struct¶
Traditionally, extension modules were defined using a module definition as the “description" of how a module should be created. Rather than using an array of slots directly, the definition has dedicated members for most common functionality, and allows additional slots as an extension mechanism.
This way of defining modules is still available and there are no plans to remove it.
-
type PyModuleDef¶
- 属于 稳定 ABI (包括所有成员).
The module definition struct, which holds 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 defined this way.
-
PyModuleDef_Base m_base¶
Always initialize this member to
PyModuleDef_HEAD_INIT:-
PyModuleDef_HEAD_INIT¶
The required initial value for
PyModuleDef.m_base.
-
PyModuleDef_HEAD_INIT¶
-
const char *m_name¶
Corresponds to the
Py_mod_nameslot.
-
const char *m_doc¶
These members correspond to the
Py_mod_docslot. Setting this to NULL is equivalent to omitting the slot.
-
Py_ssize_t m_size¶
Corresponds to the
Py_mod_state_sizeslot. Setting this to zero is equivalent to omitting the slot.When using legacy single-phase initialization or when creating modules dynamically using
PyModule_Create()orPyModule_Create2(),m_sizemay be set to -1. This indicates that the module does not support sub-interpreters, because it has global state.
-
PyMethodDef *m_methods¶
Corresponds to the
Py_mod_methodsslot. Setting this to NULL is equivalent to omitting the slot.
-
PyModuleDef_Slot *m_slots¶
An array of additional slots, terminated by a
{0, NULL}entry.This array may not contain slots corresponding to
PyModuleDefmembers. For example, you cannot usePy_mod_nameinm_slots; the module name must be given asPyModuleDef.m_name.
-
traverseproc m_traverse¶
-
inquiry m_clear¶
-
freefunc m_free¶
These members correspond to the
Py_mod_state_traverse,Py_mod_state_clear, andPy_mod_state_freeslots, respectively.Setting these members to NULL is equivalent to omitting the corresponding slots.
在 3.9 版本发生变更:
m_traverse,m_clearandm_freefunctions are longer called before the module state is allocated.
-
PyModuleDef_Base m_base¶
The following API can be used to create modules from a PyModuleDef
struct:
-
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。在 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()代替使用此函数,除非你确定需要使用它。在 3.5 版本加入.
-
int PyModule_ExecDef(PyObject *module, PyModuleDef *def)¶
- 属于 稳定 ABI 自 3.7 版起.
执行参数*def*中给出的任意执行槽(
Py_mod_exec)。在 3.5 版本加入.
-
PYTHON_API_VERSION¶
C API 版本,为向后兼容性而定义。
目前,该常量在新的Python版本中没有更新,并且对于版本控制没有用处。这在未来可能会改变。
-
PYTHON_ABI_VERSION¶
为向后兼容性定义为``3``。
目前,该常量在新的Python版本中没有更新,并且对于版本控制没有用处。这在未来可能会改变。
支持函数¶
The following functions are provided to help initialize a module object.
They are intended for a module's execution slot (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(),它可在内部用于创建键对象。在 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; }
在 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 版本弃用:
PyModule_AddObject()处于 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。在 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 数组必须被静态地分配(否则要保证比模块对象生存得更久)。
在 3.5 版本加入.
-
int PyModule_SetDocString(PyObject *module, const char *docstring)¶
- 属于 稳定 ABI 自 3.7 版起.
将 module 的文档字符串设置为 docstring 。 此函数在使用
PyModuleDef创建模块时自动调用(例如使用 多阶段初始化、PyModule_Create或PyModule_FromDefAndSpec时)。在 3.5 版本加入.
-
int PyUnstable_Module_SetGIL(PyObject *module, void *gil)¶
- 这是 不稳定 API。它可在次发布版中不经警告地改变。
指明 module 是否支持不带全局解释器锁 (GIL) 运行,使用一个来自
Py_mod_gil的值 。 当使用 旧式的单阶段初始化 时它必须在 module 的初始化函数执行期间被调用。 如果此函数在模块初始化期间未被调用,导入机制将假定该模块不支持不带 GIL 运行。 此函数仅在配置了--disable-gil的 Python 构建版中可用。 当发生错误时将返回-1并设置一个异常,成功时将返回0。在 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。在 3.3 版本加入.
-
int PyState_RemoveModule(PyModuleDef *def)¶
- 属于 稳定 ABI 自 3.3 版起.
从解释器状态中移除由 def 创建的模块对象。 当发生错误时将返回
-1并设置一个异常,成功时将返回0。调用方必须有已附加的线程状态 attached thread state。
在 3.3 版本加入.