@@ -8,7 +8,8 @@ Defining extension modules
88A C extension for CPython is a shared library (for example, a ``.so `` file
99on Linux, ``.pyd `` DLL on Windows), which is loadable into the Python process
1010(for example, it is compiled with compatible compiler settings), and which
11- exports an :ref: `initialization function <extension-export-hook >`.
11+ exports an :dfn: `export hook ` function (or an
12+ old-style :ref: `initialization function <extension-pyinit >`).
1213
1314To be importable by default (that is, by
1415:py:class: `importlib.machinery.ExtensionFileLoader `),
@@ -23,25 +24,127 @@ and must be named after the module name plus an extension listed in
2324 One suitable tool is Setuptools, whose documentation can be found at
2425 https://setuptools.pypa.io/en/latest/setuptools.html.
2526
26- Normally, the initialization function returns a module definition initialized
27- using :c:func: `PyModuleDef_Init `.
28- This allows splitting the creation process into several phases:
27+ .. _extension-export-hook :
28+
29+ Extension export hook
30+ .....................
31+
32+ .. versionadded :: next
33+
34+ Support for the :samp: `PyModExport_{ <name> } ` export hook was added in Python
35+ 3.15. The older way of defining modules is still available: consult either
36+ the :ref: `extension-pyinit ` section or earlier versions of this
37+ documentation if you plan to support earlier Python versions.
38+
39+ The export hook must be an exported function with the following signature:
40+
41+ .. c :function :: PyModuleDef_Slot *PyModExport_modulename (void)
42+
43+ For modules with ASCII-only names, the :ref:`export hook <extension-export-hook>`
44+ must be named :samp:`PyModExport_{<name>}`,
45+ with ``<name> `` replaced by the module's name.
46+
47+ For non-ASCII module names, the export hook must instead be named
48+ :samp: `PyModExportU_{ <name> } ` (note the ``U ``), with ``<name> `` encoded using
49+ Python's *punycode * encoding with hyphens replaced by underscores. In Python:
50+
51+ .. code-block :: python
52+
53+ def hook_name (name ):
54+ try :
55+ suffix = b ' _' + name.encode(' ascii' )
56+ except UnicodeEncodeError :
57+ suffix = b ' U_' + name.encode(' punycode' ).replace(b ' -' , b ' _' )
58+ return b ' PyModExport' + suffix
59+
60+ The export hook returns an array of :c:type: `PyModuleDef_Slot ` entries,
61+ terminated by an entry with a slot ID of ``0 ``.
62+ These slots describe how the module should be created and initialized.
63+
64+ This array must remain valid and constant until interpreter shutdown.
65+ Typically, it should use ``static `` storage.
66+ Prefer using the :c:macro: `Py_mod_create ` and :c:macro: `Py_mod_exec ` slots
67+ for any dynamic behavior.
68+
69+ The export hook may return ``NULL `` with an exception set to signal failure.
70+
71+ It is recommended to define the export hook function using a helper macro:
72+
73+ .. c :macro :: PyMODEXPORT_FUNC
74+
75+ Declare an extension module export hook.
76+ This macro:
77+
78+ * specifies the :c:expr: `PyModuleDef_Slot* ` return type,
79+ * adds any special linkage declarations required by the platform, and
80+ * for C++, declares the function as ``extern "C" ``.
2981
82+ For example, a module called ``spam `` would be defined like this::
83+
84+ PyABIInfo_VAR(abi_info);
85+
86+ static PyModuleDef_Slot spam_slots[] = {
87+ {Py_mod_abi, &abi_info},
88+ {Py_mod_name, "spam"},
89+ {Py_mod_init, spam_init_function},
90+ ...
91+ {0, NULL},
92+ };
93+
94+ PyMODEXPORT_FUNC
95+ PyModExport_spam(void)
96+ {
97+ return spam_slots;
98+ }
99+
100+ The export hook is typically the only non-\ ``static ``
101+ item defined in the module's C source.
102+
103+ The hook should be kept short -- ideally, one line as above.
104+ If you do need to use Python C API in this function, it is recommended to call
105+ ``PyABIInfo_Check(&abi_info, "modulename") `` first to raise an exception,
106+ rather than crash, in common cases of ABI mismatch.
107+
108+
109+ .. note ::
110+
111+ It is possible to export multiple modules from a single shared library by
112+ defining multiple export hooks.
113+ However, importing them requires a custom importer or suitably named
114+ copies/links of the extension file, because Python's import machinery only
115+ finds the function corresponding to the filename.
116+ See the `Multiple modules in one library <https://peps.python.org/pep-0489/#multiple-modules-in-one-library >`__
117+ section in :pep: `489 ` for details.
118+
119+
120+ .. _multi-phase-initialization :
121+
122+ Multi-phase initialization
123+ ..........................
124+
125+ The process of creating an extension module follows several phases:
126+
127+ - Python finds and calls the export hook to get information on how to
128+ create the module.
30129- Before any substantial code is executed, Python can determine which
31130 capabilities the module supports, and it can adjust the environment or
32131 refuse loading an incompatible extension.
33- - By default, Python itself creates the module object -- that is, it does
34- the equivalent of :py:meth: `object.__new__ ` for classes.
35- It also sets initial attributes like :attr: `~module.__package__ ` and
36- :attr: `~module.__loader__ `.
37- - Afterwards, the module object is initialized using extension-specific
38- code -- the equivalent of :py:meth: `~object.__init__ ` on classes.
132+ Slots like :c:data: `Py_mod_abi `, :c:data: `Py_mod_gil ` and
133+ :c:data: `Py_mod_multiple_interpreters ` influence this step.
134+ - By default, Python itself then creates the module object -- that is, it does
135+ the equivalent of calling :py:meth: `~object.__new__ ` when creating an object.
136+ This step can be overridden using the :c:data: `Py_mod_create ` slot.
137+ - Python sets initial module attributes like :attr: `~module.__package__ ` and
138+ :attr: `~module.__loader__ `, and inserts the module object into
139+ :py:attr: `sys.modules `.
140+ - Afterwards, the module object is initialized in an extension-specific way
141+ -- the equivalent of :py:meth: `~object.__init__ ` when creating an object,
142+ or of executing top-level code in a Python-language module.
143+ The behavior is specified using the :c:data: `Py_mod_exec ` slot.
39144
40145This is called *multi-phase initialization * to distinguish it from the legacy
41- (but still supported) *single-phase initialization * scheme,
42- where the initialization function returns a fully constructed module.
43- See the :ref: `single-phase-initialization section below <single-phase-initialization >`
44- for details.
146+ (but still supported) :ref: `single-phase initialization <single-phase-initialization >`,
147+ where an initialization function returns a fully constructed module.
45148
46149.. versionchanged :: 3.5
47150
@@ -53,7 +156,7 @@ Multiple module instances
53156
54157By default, extension modules are not singletons.
55158For example, if the :py:attr: `sys.modules ` entry is removed and the module
56- is re-imported, a new module object is created, and typically populated with
159+ is re-imported, a new module object is created and, typically, populated with
57160fresh method and type objects.
58161The old module is subject to normal garbage collection.
59162This mirrors the behavior of pure-Python modules.
@@ -83,36 +186,34 @@ A module may also be limited to the main interpreter using
83186the :c:data: `Py_mod_multiple_interpreters ` slot.
84187
85188
86- .. _extension-export-hook :
189+ .. _extension-pyinit :
87190
88- Initialization function
89- .......................
191+ `` PyInit `` function
192+ ...................
90193
91- The initialization function defined by an extension module has the
92- following signature:
194+ .. deprecated :: next
195+
196+ This functionality is :term: `soft deprecated `.
197+ It will not get new features, but there are no plans to remove it.
198+
199+ Instead of :c:func: `PyModExport_modulename `, an extension module can define
200+ an older-style :dfn: `initialization function ` with the signature:
93201
94202.. c :function :: PyObject* PyInit_modulename (void)
95203
96204Its name should be :samp:`PyInit_{<name>}`, with ``<name>`` replaced by the
97205 name of the module.
206+ For non-ASCII module names, use :samp: `PyInitU_{ <name> } ` instead, with
207+ ``<name> `` encoded in the same way as for the
208+ :ref: `export hook <extension-export-hook >` (that is, using Punycode
209+ with underscores).
98210
99- For modules with ASCII-only names, the function must instead be named
100- :samp: `PyInit_{ <name> } `, with ``<name> `` replaced by the name of the module.
101- When using :ref: `multi-phase-initialization `, non-ASCII module names
102- are allowed. In this case, the initialization function name is
103- :samp: `PyInitU_{ <name> } `, with ``<name> `` encoded using Python's
104- *punycode * encoding with hyphens replaced by underscores. In Python:
211+ If a module exports both :samp: `PyInit_{ <name> } ` and
212+ :samp: `PyModExport_{ <name> } `, the :samp: `PyInit_{ <name> } ` function
213+ is ignored.
105214
106- .. code-block :: python
107-
108- def initfunc_name (name ):
109- try :
110- suffix = b ' _' + name.encode(' ascii' )
111- except UnicodeEncodeError :
112- suffix = b ' U_' + name.encode(' punycode' ).replace(b ' -' , b ' _' )
113- return b ' PyInit' + suffix
114-
115- It is recommended to define the initialization function using a helper macro:
215+ Like with :c:macro: `PyMODEXPORT_FUNC `, it is recommended to define the
216+ initialization function using a helper macro:
116217
117218.. c :macro :: PyMODINIT_FUNC
118219
@@ -123,51 +224,24 @@ It is recommended to define the initialization function using a helper macro:
123224 * adds any special linkage declarations required by the platform, and
124225 * for C++, declares the function as ``extern "C" ``.
125226
126- For example, a module called ``spam `` would be defined like this::
127-
128- static struct PyModuleDef spam_module = {
129- .m_base = PyModuleDef_HEAD_INIT,
130- .m_name = "spam",
131- ...
132- };
133-
134- PyMODINIT_FUNC
135- PyInit_spam(void)
136- {
137- return PyModuleDef_Init(&spam_module);
138- }
139-
140- It is possible to export multiple modules from a single shared library by
141- defining multiple initialization functions. However, importing them requires
142- using symbolic links or a custom importer, because by default only the
143- function corresponding to the filename is found.
144- See the `Multiple modules in one library <https://peps.python.org/pep-0489/#multiple-modules-in-one-library >`__
145- section in :pep: `489 ` for details.
146-
147- The initialization function is typically the only non-\ ``static ``
148- item defined in the module's C source.
149227
228+ Normally, the initialization function (``PyInit_modulename ``) returns
229+ a :c:type: `PyModuleDef ` instance with non-``NULL ``
230+ :c:member: `~PyModuleDef.m_slots `. This allows Python to use
231+ :ref: `multi-phase initialization <multi-phase-initialization >`.
150232
151- .. _multi-phase-initialization :
152-
153- Multi-phase initialization
154- ..........................
155-
156- Normally, the :ref: `initialization function <extension-export-hook >`
157- (``PyInit_modulename ``) returns a :c:type: `PyModuleDef ` instance with
158- non-``NULL `` :c:member: `~PyModuleDef.m_slots `.
159233Before it is returned, the ``PyModuleDef `` instance must be initialized
160234using the following function:
161235
162-
163236.. c :function :: PyObject* PyModuleDef_Init (PyModuleDef *def)
164237
165238 Ensure a module definition is a properly initialized Python object that
166239 correctly reports its type and a reference count.
167240
168241 Return *def * cast to ``PyObject* ``, or ``NULL `` if an error occurred.
169242
170- Calling this function is required for :ref: `multi-phase-initialization `.
243+ Calling this function is required before returning a :c:type: `PyModuleDef `
244+ from a module initialization function.
171245 It should not be used in other contexts.
172246
173247 Note that Python assumes that ``PyModuleDef `` structures are statically
@@ -178,18 +252,37 @@ using the following function:
178252 .. versionadded :: 3.5
179253
180254
255+ For example, a module called ``spam `` would be defined like this::
256+
257+ static struct PyModuleDef spam_module = {
258+ .m_base = PyModuleDef_HEAD_INIT,
259+ .m_name = "spam",
260+ ...
261+ };
262+
263+ PyMODINIT_FUNC
264+ PyInit_spam(void)
265+ {
266+ return PyModuleDef_Init(&spam_module);
267+ }
268+
269+
181270.. _single-phase-initialization :
182271
183272Legacy single-phase initialization
184- ..................................
273+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
185274
186- .. attention ::
187- Single-phase initialization is a legacy mechanism to initialize extension
275+ .. deprecated :: next
276+
277+ Single-phase initialization is :term: `soft deprecated `.
278+ It is a legacy mechanism to initialize extension
188279 modules, with known drawbacks and design flaws. Extension module authors
189280 are encouraged to use multi-phase initialization instead.
190281
191- In single-phase initialization, the
192- :ref: `initialization function <extension-export-hook >` (``PyInit_modulename ``)
282+ However, there are no plans to remove support for it.
283+
284+ In single-phase initialization, the old-style
285+ :ref: `initializaton function <extension-pyinit >` (``PyInit_modulename ``)
193286should create, populate and return a module object.
194287This is typically done using :c:func:`PyModule_Create` and functions like
195288:c:func:`PyModule_AddObjectRef`.
@@ -242,6 +335,8 @@ in the following ways:
242335* Single-phase modules support module lookup functions like
243336 :c:func: `PyState_FindModule `.
244337
338+ * The module's :c:member: `PyModuleDef.m_slots ` must be NULL.
339+
245340.. [#testsinglephase ] ``_testsinglephase `` is an internal module used
246341 in CPython's self-test suite; your installation may or may not
247342 include it.
0 commit comments