تعریف ماژولهای توسعهای¶
A C extension for CPython is a shared library (for example, a .so file
on Linux, .pyd DLL on Windows), which is loadable into the Python process
(for example, it is compiled with compatible compiler settings), and which
exports an export hook function (or an
old-style initialization function).
برای اینکه بهصورت پیشفرض ایمپورتپذیر باشد (یعنی توسط importlib.machinery.ExtensionFileLoader)، کتابخانهی اشتراکی باید در sys.path موجود باشد و باید بر اساس نام ماژول بهعلاوهی یکی از پسوندهای فهرستشده در importlib.machinery.EXTENSION_SUFFIXES نامگذاری شود.
توجه
ساخت، بستهبندی و توزیع ماژولهای توسعهای بهتر است با ابزارهای شخص ثالث انجام شود و خارج از محدودهی این سند است. یکی از ابزارهای مناسب، Setuptools است که میتوانید مستندات آن را در https://setuptools.pypa.io/en/latest/setuptools.html بیابید.
Extension export hook¶
اضافه شده در نسخهی 3.15: Support for the PyModExport_<name> export hook was added in Python
3.15. The older way of defining modules is still available: consult either
the PyInit function section or earlier versions of this
documentation if you plan to support earlier Python versions.
The export hook must be an exported function with the following signature:
For modules with ASCII-only names, the export hook
must be named PyModExport_<name>,
with <name> replaced by the module's name.
For non-ASCII module names, the export hook must instead be named
PyModExportU_<name> (note the U), with <name> encoded using
Python's punycode encoding with hyphens replaced by underscores. In Python:
def hook_name(name):
try:
suffix = b'_' + name.encode('ascii')
except UnicodeEncodeError:
suffix = b'U_' + name.encode('punycode').replace(b'-', b'_')
return b'PyModExport' + suffix
The export hook returns an array of PySlot entries,
terminated by an entry with a slot ID of 0.
These slots describe how the module should be created and initialized.
This array must remain valid and constant until interpreter shutdown.
Typically, it should use static storage.
Prefer using the Py_mod_create and Py_mod_exec slots
for any dynamic behavior.
The export hook may return NULL with an exception set to signal failure.
It is recommended to define the export hook function using a helper macro:
-
PyMODEXPORT_FUNC¶
- قسمتی از ABI پایدار از نسخهی 3.15.
Declare an extension module export hook. This macro:
specifies the PySlot* return type,
هرگونه اعلان پیوند خاص مورد نیاز پلتفرم را میافزاید و
برای C++، تابع را بهصورت
extern "C"اعلان میکند.
برای مثال، ماژولی به نام spam به شکل زیر تعریف میشود:
PyABIInfo_VAR(abi_info);
static PySlot spam_slots[] = {
PySlot_STATIC_DATA(Py_mod_abi, &abi_info),
PySlot_STATIC_DATA(Py_mod_name, "spam"),
PySlot_FUNC(Py_mod_init, spam_init_function),
...
PySlot_END
};
PyMODEXPORT_FUNC
PyModExport_spam(void)
{
return spam_slots;
}
The export hook is typically the only non-static
item defined in the module's C source.
The hook should be kept short.
If it does more than return a static array, several caveats apply:
If you need to use any Python C API, it is recommended to call
PyABIInfo_Check()first to raise an exception, rather than crash, in common cases of ABI mismatch.Code in the export hook must never rely on the GIL: free-threaded builds of Python can only check the
Py_mod_gilslot (or the lack of it) after the hook returns,Similarly, the hook may be called in any subinterpreter, since the
Py_mod_multiple_interpretersslot (or lack of it) is only checked after the hook returns.
For example:
PyMODEXPORT_FUNC
PyModExport_modulename(void)
{
if (PyABIInfo_Check(&abi_info, "modulename") < 0) {
/* ABI mismatch. It's not safe to examine the raised exception. */
return NULL;
}
/* use Python API (as little as possible); don't rely on GIL */
return modulename_slots;
}
توجه
It is possible to export multiple modules from a single shared library by defining multiple export hooks. However, importing them requires a custom importer or suitably named copies/links of the extension file, because Python's import machinery only finds the function corresponding to the filename. See the Multiple modules in one library section in PEP 489 for details.
مقداردهی اولیه چندمرحلهای¶
The process of creating an extension module follows several phases:
Python finds and calls the export hook to get information on how to create the module.
Before any substantial code is executed, Python can determine which capabilities the module supports, and it can adjust the environment or refuse loading an incompatible extension. Slots like
Py_mod_abi,Py_mod_gilandPy_mod_multiple_interpretersinfluence this step.By default, Python itself then creates the module object -- that is, it does the equivalent of calling
__new__()when creating an object. This step can be overridden using thePy_mod_createslot.Python sets initial module attributes like
__package__and__loader__, and inserts the module object intosys.modules.Afterwards, the module object is initialized in an extension-specific way -- the equivalent of
__init__()when creating an object, or of executing top-level code in a Python-language module. The behavior is specified using thePy_mod_execslot.
This is called multi-phase initialization to distinguish it from the legacy (but still supported) single-phase initialization, where an initialization function returns a fully constructed module.
تغییر یافته در نسخهی 3.5: پشتیبانی از مقداردهی اولیه چندمرحلهای اضافه شد (PEP 489).
نمونههای متعدد ماژول¶
By default, extension modules are not singletons.
For example, if the sys.modules entry is removed and the module
is re-imported, a new module object is created and, typically, populated with
fresh method and type objects.
The old module is subject to normal garbage collection.
This mirrors the behavior of pure-Python modules.
ممکن است نمونههای اضافی ماژول در زیرمفسرها یا پس از راهاندازی مجدد رانتایم پایتون (Py_Finalize() و Py_Initialize()) ایجاد شوند. در این موارد، اشتراکگذاری اشیاء پایتون بین نمونههای ماژول به احتمال زیاد باعث فروپاشی یا رفتار تعریفنشده میشود.
برای پرهیز از چنین مشکلاتی، هر نمونه از یک ماژول توسعهای باید مجزا باشد: تغییرات در یک نمونه نباید بهطور ضمنی بر نمونههای دیگر تأثیر بگذارد، و تمام وضعیتهای متعلق به ماژول، از جمله ارجاعها به اشیاء پایتون، باید مختص به یک نمونه ماژول خاص باشند. برای جزئیات بیشتر و راهنمای عملی، جداسازی ماژولهای توسعه را ببینید.
راه سادهتر برای اجتناب از این مشکلات، ایجاد خطا هنگام مقداردهی اولیهی مکرر است.
انتظار میرود تمام ماژولها از زیرمفسرها پشتیبانی کنند، یا در غیر این صورت، بهصراحت عدم پشتیبانی خود را اعلام کنند. این کار معمولاً از طریق جداسازی یا مسدود کردن مقداردهی اولیهی مکرر، همانطور که در بالا ذکر شد، انجام میشود. همچنین ممکن است یک ماژول با استفاده از جایگاه Py_mod_multiple_interpreters به مفسر اصلی محدود شود.
PyInit function¶
منسوخسازی نرم <Soft deprecated> از نسخهی 3.15: This functionality will not get new features, but there are no plans to remove it.
Instead of PyModExport_modulename(), an extension module can define
an older-style initialization function with the signature:
Its name should be PyInit_<name>, with <name> replaced by the
name of the module.
For non-ASCII module names, use PyInitU_<name> instead, with
<name> encoded in the same way as for the
export hook (that is, using Punycode
with underscores).
If a module exports both PyInit_<name> and
PyModExport_<name>, the PyInit_<name> function
is ignored.
Like with PyMODEXPORT_FUNC, it is recommended to define the
initialization function using a helper macro:
-
PyMODINIT_FUNC¶
یک تابع مقداردهی اولیهی ماژول توسعهای را اعلان میکند. این ماکرو:
نوع بازگشتی PyObject* را تعیین میکند،
هرگونه اعلان پیوند خاص مورد نیاز پلتفرم را میافزاید و
برای C++، تابع را بهصورت
extern "C"اعلان میکند.
Normally, the initialization function (PyInit_modulename) returns
a PyModuleDef instance with non-NULL
m_slots. This allows Python to use
multi-phase initialization.
Before it is returned, the PyModuleDef instance must be initialized
using the following function:
-
PyObject *PyModuleDef_Init(PyModuleDef *def)¶
- قسمتی از ABI پایدار از نسخهی 3.5.
اطمینان حاصل میکند که تعریف ماژول، یک شیء پایتونِ بهدرستی مقداردهیشده است که نوع و شمارش ارجاع خود را بهدرستی گزارش میکند.
def قالبریزیشده به
PyObject*را برمیگرداند، یاNULLرا در صورت وقوع خطا.Calling this function is required before returning a
PyModuleDeffrom a module initialization function. It should not be used in other contexts.توجه داشته باشید که پایتون فرض میکند ساختارهای
PyModuleDefبهصورت ایستا تخصیص یافتهاند. این تابع ممکن است یک ارجاع جدید یا یک ارجاع امانتی برگرداند؛ این ارجاع نباید آزاد شود.اضافه شده در نسخهی 3.5.
برای مثال، ماژولی به نام spam به شکل زیر تعریف میشود:
static struct PyModuleDef spam_module = {
.m_base = PyModuleDef_HEAD_INIT,
.m_name = "spam",
...
};
PyMODINIT_FUNC
PyInit_spam(void)
{
return PyModuleDef_Init(&spam_module);
}
مقداردهی اولیه تکمرحلهای قدیمی¶
منسوخسازی نرم <Soft deprecated> از نسخهی 3.15: راهاندازی تکفازی (single-phase initialization) سازوکاری قدیمی برای راهاندازی ماژولهای توسعهای است و معایب شناختهشده و نقصهای طراحی دارد. به نویسندگان ماژولهای توسعهای توصیه میشود که بهجای آن از راهاندازی چندفازی (multi-phase initialization) استفاده کنند.
However, there are no plans to remove support for it.
In single-phase initialization, the old-style
initialization function (PyInit_modulename)
should create, populate and return a module object.
This is typically done using PyModule_Create() and functions like
PyModule_AddObjectRef().
مقداردهی اولیه تکفازی در موارد زیر با پیشفرض تفاوت دارد:
ماژولهای تکفاز (single-phase) «تکنمونه» هستند، یا به بیان دقیقتر، حاوی «تکنمونه» هستند.
هنگامی که ماژول برای نخستین بار مقداردهی اولیه میشود، پایتون محتویات
__dict__ماژول را ذخیره میکند (یعنی، بهطور معمول، توابع و نوعهای ماژول).برای ایمپورتهای بعدی، پایتون تابع مقداردهی اولیه را دوباره فراخوانی نمیکند. در عوض، شیء ماژول جدیدی با
__dict__جدید میسازد و محتویات ذخیرهشده را در آن کپی میکند. برای مثال، با فرض یک ماژول تکفاز_testsinglephase[1] که تابعی به نامsumو کلاس استثنایی به نامerrorرا تعریف میکند:>>> import sys >>> import _testsinglephase as one >>> del sys.modules['_testsinglephase'] >>> import _testsinglephase as two >>> one is two False >>> one.__dict__ is two.__dict__ False >>> one.sum is two.sum True >>> one.error is two.error True
رفتار دقیق باید بهعنوان جزئیات پیادهسازی سیپایتون در نظر گرفته شود.
برای دور زدن این واقعیت که
PyInit_modulenameآرگومان مشخصات نمیپذیرد، بخشی از وضعیت سازوکار ایمپورت ذخیره میشود و بر نخستین ماژول مناسب ایجادشده در طول فراخوانیPyInit_modulenameاعمال میشود. بهطور خاص، هنگامی که یک زیرماژول ایمپورت میشود، این سازوکار نام بسته والد را به ابتدای نام ماژول میافزاید.یک تابع تکفازه
PyInit_modulenameباید شیء ماژول «خود» را در اسرع وقت ایجاد کند، پیش از آنکه بتوان هر شیء ماژول دیگری را ایجاد کرد.نامهای ماژول غیراسکی (
PyInitU_modulename) پشتیبانی نمیشوند.ماژولهای تکفازی از توابع جستجوی ماژول مانند
PyState_FindModule()پشتیبانی میکنند.The module's
PyModuleDef.m_slotsmust be NULL.