Debian Codegraph @

Doc/c-api/module.rst

raw
1 .. highlight:: c
2
3 .. _moduleobjects:
4
5 Module Objects
6 --------------
7
8 .. index:: pair: object; module
9
10
11 .. c:var:: PyTypeObject PyModule_Type
12
13 .. index:: single: ModuleType (in module types)
14
15 This instance of :c:type:`PyTypeObject` represents the Python module type. This
16 is exposed to Python programs as :py:class:`types.ModuleType`.
17
18
19 .. c:function:: int PyModule_Check(PyObject *p)
20
21 Return true if *p* is a module object, or a subtype of a module object.
22 This function always succeeds.
23
24
25 .. c:function:: int PyModule_CheckExact(PyObject *p)
26
27 Return true if *p* is a module object, but not a subtype of
28 :c:data:`PyModule_Type`. This function always succeeds.
29
30
31 .. c:function:: PyObject* PyModule_NewObject(PyObject *name)
32
33 .. index::
34 single: __name__ (module attribute)
35 single: __doc__ (module attribute)
36 single: __file__ (module attribute)
37 single: __package__ (module attribute)
38 single: __loader__ (module attribute)
39
40 Return a new module object with :attr:`module.__name__` set to *name*.
41 The module's :attr:`!__name__`, :attr:`~module.__doc__`,
42 :attr:`~module.__package__` and :attr:`~module.__loader__` attributes are
43 filled in (all but :attr:`!__name__` are set to ``None``). The caller is
44 responsible for setting a :attr:`~module.__file__` attribute.
45
46 Return ``NULL`` with an exception set on error.
47
48 .. versionadded:: 3.3
49
50 .. versionchanged:: 3.4
51 :attr:`~module.__package__` and :attr:`~module.__loader__` are now set to
52 ``None``.
53
54
55 .. c:function:: PyObject* PyModule_New(const char *name)
56
57 Similar to :c:func:`PyModule_NewObject`, but the name is a UTF-8 encoded
58 string instead of a Unicode object.
59
60
61 .. c:function:: PyObject* PyModule_GetDict(PyObject *module)
62
63 .. index:: single: __dict__ (module attribute)
64
65 Return the dictionary object that implements *module*'s namespace; this object
66 is the same as the :attr:`~object.__dict__` attribute of the module object.
67 If *module* is not a module object (or a subtype of a module object),
68 :exc:`SystemError` is raised and ``NULL`` is returned.
69
70 It is recommended extensions use other ``PyModule_*`` and
71 ``PyObject_*`` functions rather than directly manipulate a module's
72 :attr:`~object.__dict__`.
73
74 The returned reference is borrowed from the module; it is valid until
75 the module is destroyed.
76
77
78 .. c:function:: PyObject* PyModule_GetNameObject(PyObject *module)
79
80 .. index::
81 single: __name__ (module attribute)
82 single: SystemError (built-in exception)
83
84 Return *module*'s :attr:`~module.__name__` value. If the module does not
85 provide one, or if it is not a string, :exc:`SystemError` is raised and
86 ``NULL`` is returned.
87
88 .. versionadded:: 3.3
89
90
91 .. c:function:: const char* PyModule_GetName(PyObject *module)
92
93 Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to
94 ``'utf-8'``.
95
96 The returned buffer is only valid until the module is renamed or destroyed.
97 Note that Python code may rename a module by setting its :py:attr:`~module.__name__`
98 attribute.
99
100 .. c:function:: void* PyModule_GetState(PyObject *module)
101
102 Return the "state" of the module, that is, a pointer to the block of memory
103 allocated at module creation time, or ``NULL``. See
104 :c:member:`PyModuleDef.m_size`.
105
106
107 .. c:function:: PyModuleDef* PyModule_GetDef(PyObject *module)
108
109 Return a pointer to the :c:type:`PyModuleDef` struct from which the module was
110 created, or ``NULL`` if the module wasn't created from a definition.
111
112 On error, return ``NULL`` with an exception set.
113 Use :c:func:`PyErr_Occurred` to tell this case apart from a missing
114 :c:type:`!PyModuleDef`.
115
116
117 .. c:function:: PyObject* PyModule_GetFilenameObject(PyObject *module)
118
119 .. index::
120 single: __file__ (module attribute)
121 single: SystemError (built-in exception)
122
123 Return the name of the file from which *module* was loaded using *module*'s
124 :attr:`~module.__file__` attribute. If this is not defined, or if it is not a
125 string, raise :exc:`SystemError` and return ``NULL``; otherwise return
126 a reference to a Unicode object.
127
128 .. versionadded:: 3.2
129
130
131 .. c:function:: const char* PyModule_GetFilename(PyObject *module)
132
133 Similar to :c:func:`PyModule_GetFilenameObject` but return the filename
134 encoded to 'utf-8'.
135
136 The returned buffer is only valid until the module's :py:attr:`~module.__file__` attribute
137 is reassigned or the module is destroyed.
138
139 .. deprecated:: 3.2
140 :c:func:`PyModule_GetFilename` raises :exc:`UnicodeEncodeError` on
141 unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead.
142
143
144 .. _pymoduledef:
145
146 Module definitions
147 ------------------
148
149 The functions in the previous section work on any module object, including
150 modules imported from Python code.
151
152 Modules defined using the C API typically use a *module definition*,
153 :c:type:`PyModuleDef` -- a statically allocated, constant “description" of
154 how a module should be created.
155
156 The definition is usually used to define an extension's “main” module object
157 (see :ref:`extension-modules` for details).
158 It is also used to
159 :ref:`create extension modules dynamically <moduledef-dynamic>`.
160
161 Unlike :c:func:`PyModule_New`, the definition allows management of
162 *module state* -- a piece of memory that is allocated and cleared together
163 with the module object.
164 Unlike the module's Python attributes, Python code cannot replace or delete
165 data stored in module state.
166
167 .. c:type:: PyModuleDef
168
169 The module definition struct, which holds all information needed to create
170 a module object.
171 This structure must be statically allocated (or be otherwise guaranteed
172 to be valid while any modules created from it exist).
173 Usually, there is only one variable of this type for each extension module.
174
175 .. c:member:: PyModuleDef_Base m_base
176
177 Always initialize this member to :c:macro:`PyModuleDef_HEAD_INIT`.
178
179 .. c:member:: const char *m_name
180
181 Name for the new module.
182
183 .. c:member:: const char *m_doc
184
185 Docstring for the module; usually a docstring variable created with
186 :c:macro:`PyDoc_STRVAR` is used.
187
188 .. c:member:: Py_ssize_t m_size
189
190 Module state may be kept in a per-module memory area that can be
191 retrieved with :c:func:`PyModule_GetState`, rather than in static globals.
192 This makes modules safe for use in multiple sub-interpreters.
193
194 This memory area is allocated based on *m_size* on module creation,
195 and freed when the module object is deallocated, after the
196 :c:member:`~PyModuleDef.m_free` function has been called, if present.
197
198 Setting it to a non-negative value means that the module can be
199 re-initialized and specifies the additional amount of memory it requires
200 for its state.
201
202 Setting ``m_size`` to ``-1`` means that the module does not support
203 sub-interpreters, because it has global state.
204 Negative ``m_size`` is only allowed when using
205 :ref:`legacy single-phase initialization <single-phase-initialization>`
206 or when :ref:`creating modules dynamically <moduledef-dynamic>`.
207
208 See :PEP:`3121` for more details.
209
210 .. c:member:: PyMethodDef* m_methods
211
212 A pointer to a table of module-level functions, described by
213 :c:type:`PyMethodDef` values. Can be ``NULL`` if no functions are present.
214
215 .. c:member:: PyModuleDef_Slot* m_slots
216
217 An array of slot definitions for multi-phase initialization, terminated by
218 a ``{0, NULL}`` entry.
219 When using legacy single-phase initialization, *m_slots* must be ``NULL``.
220
221 .. versionchanged:: 3.5
222
223 Prior to version 3.5, this member was always set to ``NULL``,
224 and was defined as:
225
226 .. c:member:: inquiry m_reload
227
228 .. c:member:: traverseproc m_traverse
229
230 A traversal function to call during GC traversal of the module object, or
231 ``NULL`` if not needed.
232
233 This function is not called if the module state was requested but is not
234 allocated yet. This is the case immediately after the module is created
235 and before the module is executed (:c:data:`Py_mod_exec` function). More
236 precisely, this function is not called if :c:member:`~PyModuleDef.m_size` is greater
237 than 0 and the module state (as returned by :c:func:`PyModule_GetState`)
238 is ``NULL``.
239
240 .. versionchanged:: 3.9
241 No longer called before the module state is allocated.
242
243 .. c:member:: inquiry m_clear
244
245 A clear function to call during GC clearing of the module object, or
246 ``NULL`` if not needed.
247
248 This function is not called if the module state was requested but is not
249 allocated yet. This is the case immediately after the module is created
250 and before the module is executed (:c:data:`Py_mod_exec` function). More
251 precisely, this function is not called if :c:member:`~PyModuleDef.m_size` is greater
252 than 0 and the module state (as returned by :c:func:`PyModule_GetState`)
253 is ``NULL``.
254
255 Like :c:member:`PyTypeObject.tp_clear`, this function is not *always*
256 called before a module is deallocated. For example, when reference
257 counting is enough to determine that an object is no longer used,
258 the cyclic garbage collector is not involved and
259 :c:member:`~PyModuleDef.m_free` is called directly.
260
261 .. versionchanged:: 3.9
262 No longer called before the module state is allocated.
263
264 .. c:member:: freefunc m_free
265
266 A function to call during deallocation of the module object, or ``NULL``
267 if not needed.
268
269 This function is not called if the module state was requested but is not
270 allocated yet. This is the case immediately after the module is created
271 and before the module is executed (:c:data:`Py_mod_exec` function). More
272 precisely, this function is not called if :c:member:`~PyModuleDef.m_size` is greater
273 than 0 and the module state (as returned by :c:func:`PyModule_GetState`)
274 is ``NULL``.
275
276 .. versionchanged:: 3.9
277 No longer called before the module state is allocated.
278
279
280 .. c:var:: PyTypeObject PyModuleDef_Type
281
282 The type of ``PyModuleDef`` objects.
283
284
285 Module slots
286 ............
287
288 .. c:type:: PyModuleDef_Slot
289
290 .. c:member:: int slot
291
292 A slot ID, chosen from the available values explained below.
293
294 .. c:member:: void* value
295
296 Value of the slot, whose meaning depends on the slot ID.
297
298 .. versionadded:: 3.5
299
300 The available slot types are:
301
302 .. c:macro:: Py_mod_create
303
304 Specifies a function that is called to create the module object itself.
305 The *value* pointer of this slot must point to a function of the signature:
306
307 .. c:function:: PyObject* create_module(PyObject *spec, PyModuleDef *def)
308 :no-index-entry:
309 :no-contents-entry:
310
311 The function receives a :py:class:`~importlib.machinery.ModuleSpec`
312 instance, as defined in :PEP:`451`, and the module definition.
313 It should return a new module object, or set an error
314 and return ``NULL``.
315
316 This function should be kept minimal. In particular, it should not
317 call arbitrary Python code, as trying to import the same module again may
318 result in an infinite loop.
319
320 Multiple ``Py_mod_create`` slots may not be specified in one module
321 definition.
322
323 If ``Py_mod_create`` is not specified, the import machinery will create
324 a normal module object using :c:func:`PyModule_New`. The name is taken from
325 *spec*, not the definition, to allow extension modules to dynamically adjust
326 to their place in the module hierarchy and be imported under different
327 names through symlinks, all while sharing a single module definition.
328
329 There is no requirement for the returned object to be an instance of
330 :c:type:`PyModule_Type`. Any type can be used, as long as it supports
331 setting and getting import-related attributes.
332 However, only ``PyModule_Type`` instances may be returned if the
333 ``PyModuleDef`` has non-``NULL`` ``m_traverse``, ``m_clear``,
334 ``m_free``; non-zero ``m_size``; or slots other than ``Py_mod_create``.
335
336 .. versionadded:: 3.5
337
338 .. c:macro:: Py_mod_exec
339
340 Specifies a function that is called to *execute* the module.
341 This is equivalent to executing the code of a Python module: typically,
342 this function adds classes and constants to the module.
343 The signature of the function is:
344
345 .. c:function:: int exec_module(PyObject* module)
346 :no-index-entry:
347 :no-contents-entry:
348
349 If multiple ``Py_mod_exec`` slots are specified, they are processed in the
350 order they appear in the *m_slots* array.
351
352 .. versionadded:: 3.5
353
354 .. c:macro:: Py_mod_multiple_interpreters
355
356 Specifies one of the following values:
357
358 .. c:namespace:: NULL
359
360 .. c:macro:: Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
361
362 The module does not support being imported in subinterpreters.
363
364 .. c:macro:: Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED
365
366 The module supports being imported in subinterpreters,
367 but only when they share the main interpreter's GIL.
368 (See :ref:`isolating-extensions-howto`.)
369
370 .. c:macro:: Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
371
372 The module supports being imported in subinterpreters,
373 even when they have their own GIL.
374 (See :ref:`isolating-extensions-howto`.)
375
376 This slot determines whether or not importing this module
377 in a subinterpreter will fail.
378
379 Multiple ``Py_mod_multiple_interpreters`` slots may not be specified
380 in one module definition.
381
382 If ``Py_mod_multiple_interpreters`` is not specified, the import
383 machinery defaults to ``Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED``.
384
385 .. versionadded:: 3.12
386
387 .. c:macro:: Py_mod_gil
388
389 Specifies one of the following values:
390
391 .. c:namespace:: NULL
392
393 .. c:macro:: Py_MOD_GIL_USED
394
395 The module depends on the presence of the global interpreter lock (GIL),
396 and may access global state without synchronization.
397
398 .. c:macro:: Py_MOD_GIL_NOT_USED
399
400 The module is safe to run without an active GIL.
401
402 This slot is ignored by Python builds not configured with
403 :option:`--disable-gil`. Otherwise, it determines whether or not importing
404 this module will cause the GIL to be automatically enabled. See
405 :ref:`whatsnew313-free-threaded-cpython` for more detail.
406
407 Multiple ``Py_mod_gil`` slots may not be specified in one module definition.
408
409 If ``Py_mod_gil`` is not specified, the import machinery defaults to
410 ``Py_MOD_GIL_USED``.
411
412 .. versionadded:: 3.13
413
414
415 .. _moduledef-dynamic:
416
417 Creating extension modules dynamically
418 --------------------------------------
419
420 The following functions may be used to create a module outside of an
421 extension's :ref:`initialization function <extension-export-hook>`.
422 They are also used in
423 :ref:`single-phase initialization <single-phase-initialization>`.
424
425 .. c:function:: PyObject* PyModule_Create(PyModuleDef *def)
426
427 Create a new module object, given the definition in *def*.
428 This is a macro that calls :c:func:`PyModule_Create2` with
429 *module_api_version* set to :c:macro:`PYTHON_API_VERSION`, or
430 to :c:macro:`PYTHON_ABI_VERSION` if using the
431 :ref:`limited API <limited-c-api>`.
432
433 .. c:function:: PyObject* PyModule_Create2(PyModuleDef *def, int module_api_version)
434
435 Create a new module object, given the definition in *def*, assuming the
436 API version *module_api_version*. If that version does not match the version
437 of the running interpreter, a :exc:`RuntimeWarning` is emitted.
438
439 Return ``NULL`` with an exception set on error.
440
441 This function does not support slots.
442 The :c:member:`~PyModuleDef.m_slots` member of *def* must be ``NULL``.
443
444
445 .. note::
446
447 Most uses of this function should be using :c:func:`PyModule_Create`
448 instead; only use this if you are sure you need it.
449
450 .. c:function:: PyObject * PyModule_FromDefAndSpec(PyModuleDef *def, PyObject *spec)
451
452 This macro calls :c:func:`PyModule_FromDefAndSpec2` with
453 *module_api_version* set to :c:macro:`PYTHON_API_VERSION`, or
454 to :c:macro:`PYTHON_ABI_VERSION` if using the
455 :ref:`limited API <limited-c-api>`.
456
457 .. versionadded:: 3.5
458
459 .. c:function:: PyObject * PyModule_FromDefAndSpec2(PyModuleDef *def, PyObject *spec, int module_api_version)
460
461 Create a new module object, given the definition in *def* and the
462 ModuleSpec *spec*, assuming the API version *module_api_version*.
463 If that version does not match the version of the running interpreter,
464 a :exc:`RuntimeWarning` is emitted.
465
466 Return ``NULL`` with an exception set on error.
467
468 Note that this does not process execution slots (:c:data:`Py_mod_exec`).
469 Both ``PyModule_FromDefAndSpec`` and ``PyModule_ExecDef`` must be called
470 to fully initialize a module.
471
472 .. note::
473
474 Most uses of this function should be using :c:func:`PyModule_FromDefAndSpec`
475 instead; only use this if you are sure you need it.
476
477 .. versionadded:: 3.5
478
479 .. c:function:: int PyModule_ExecDef(PyObject *module, PyModuleDef *def)
480
481 Process any execution slots (:c:data:`Py_mod_exec`) given in *def*.
482
483 .. versionadded:: 3.5
484
485 .. c:macro:: PYTHON_API_VERSION
486
487 The C API version. Defined for backwards compatibility.
488
489 Currently, this constant is not updated in new Python versions, and is not
490 useful for versioning. This may change in the future.
491
492 .. c:macro:: PYTHON_ABI_VERSION
493
494 Defined as ``3`` for backwards compatibility.
495
496 Currently, this constant is not updated in new Python versions, and is not
497 useful for versioning. This may change in the future.
498
499
500 Support functions
501 -----------------
502
503 The following functions are provided to help initialize a module
504 state.
505 They are intended for a module's execution slots (:c:data:`Py_mod_exec`),
506 the initialization function for legacy :ref:`single-phase initialization <single-phase-initialization>`,
507 or code that creates modules dynamically.
508
509 .. c:function:: int PyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)
510
511 Add an object to *module* as *name*. This is a convenience function which
512 can be used from the module's initialization function.
513
514 On success, return ``0``. On error, raise an exception and return ``-1``.
515
516 Example usage::
517
518 static int
519 add_spam(PyObject *module, int value)
520 {
521 PyObject *obj = PyLong_FromLong(value);
522 if (obj == NULL) {
523 return -1;
524 }
525 int res = PyModule_AddObjectRef(module, "spam", obj);
526 Py_DECREF(obj);
527 return res;
528 }
529
530 To be convenient, the function accepts ``NULL`` *value* with an exception
531 set. In this case, return ``-1`` and just leave the raised exception
532 unchanged.
533
534 The example can also be written without checking explicitly if *obj* is
535 ``NULL``::
536
537 static int
538 add_spam(PyObject *module, int value)
539 {
540 PyObject *obj = PyLong_FromLong(value);
541 int res = PyModule_AddObjectRef(module, "spam", obj);
542 Py_XDECREF(obj);
543 return res;
544 }
545
546 Note that ``Py_XDECREF()`` should be used instead of ``Py_DECREF()`` in
547 this case, since *obj* can be ``NULL``.
548
549 The number of different *name* strings passed to this function
550 should be kept small, usually by only using statically allocated strings
551 as *name*.
552 For names that aren't known at compile time, prefer calling
553 :c:func:`PyUnicode_FromString` and :c:func:`PyObject_SetAttr` directly.
554 For more details, see :c:func:`PyUnicode_InternFromString`, which may be
555 used internally to create a key object.
556
557 .. versionadded:: 3.10
558
559
560 .. c:function:: int PyModule_Add(PyObject *module, const char *name, PyObject *value)
561
562 Similar to :c:func:`PyModule_AddObjectRef`, but "steals" a reference
563 to *value*.
564 It can be called with a result of function that returns a new reference
565 without bothering to check its result or even saving it to a variable.
566
567 Example usage::
568
569 if (PyModule_Add(module, "spam", PyBytes_FromString(value)) < 0) {
570 goto error;
571 }
572
573 .. versionadded:: 3.13
574
575
576 .. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)
577
578 Similar to :c:func:`PyModule_AddObjectRef`, but steals a reference to
579 *value* on success (if it returns ``0``).
580
581 The new :c:func:`PyModule_Add` or :c:func:`PyModule_AddObjectRef`
582 functions are recommended, since it is
583 easy to introduce reference leaks by misusing the
584 :c:func:`PyModule_AddObject` function.
585
586 .. note::
587
588 Unlike other functions that steal references, ``PyModule_AddObject()``
589 only releases the reference to *value* **on success**.
590
591 This means that its return value must be checked, and calling code must
592 :c:func:`Py_XDECREF` *value* manually on error.
593
594 Example usage::
595
596 PyObject *obj = PyBytes_FromString(value);
597 if (PyModule_AddObject(module, "spam", obj) < 0) {
598 // If 'obj' is not NULL and PyModule_AddObject() failed,
599 // 'obj' strong reference must be deleted with Py_XDECREF().
600 // If 'obj' is NULL, Py_XDECREF() does nothing.
601 Py_XDECREF(obj);
602 goto error;
603 }
604 // PyModule_AddObject() stole a reference to obj:
605 // Py_XDECREF(obj) is not needed here.
606
607 .. soft-deprecated:: 3.13
608
609
610 .. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value)
611
612 Add an integer constant to *module* as *name*. This convenience function can be
613 used from the module's initialization function.
614 Return ``-1`` with an exception set on error, ``0`` on success.
615
616 This is a convenience function that calls :c:func:`PyLong_FromLong` and
617 :c:func:`PyModule_AddObjectRef`; see their documentation for details.
618
619
620 .. c:function:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)
621
622 Add a string constant to *module* as *name*. This convenience function can be
623 used from the module's initialization function. The string *value* must be
624 ``NULL``-terminated.
625 Return ``-1`` with an exception set on error, ``0`` on success.
626
627 This is a convenience function that calls
628 :c:func:`PyUnicode_InternFromString` and :c:func:`PyModule_AddObjectRef`;
629 see their documentation for details.
630
631
632 .. c:macro:: PyModule_AddIntMacro(module, macro)
633
634 Add an int constant to *module*. The name and the value are taken from
635 *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int
636 constant *AF_INET* with the value of *AF_INET* to *module*.
637 Return ``-1`` with an exception set on error, ``0`` on success.
638
639
640 .. c:macro:: PyModule_AddStringMacro(module, macro)
641
642 Add a string constant to *module*.
643
644 .. c:function:: int PyModule_AddType(PyObject *module, PyTypeObject *type)
645
646 Add a type object to *module*.
647 The type object is finalized by calling internally :c:func:`PyType_Ready`.
648 The name of the type object is taken from the last component of
649 :c:member:`~PyTypeObject.tp_name` after dot.
650 Return ``-1`` with an exception set on error, ``0`` on success.
651
652 .. versionadded:: 3.9
653
654 .. c:function:: int PyModule_AddFunctions(PyObject *module, PyMethodDef *functions)
655
656 Add the functions from the ``NULL`` terminated *functions* array to *module*.
657 Refer to the :c:type:`PyMethodDef` documentation for details on individual
658 entries (due to the lack of a shared module namespace, module level
659 "functions" implemented in C typically receive the module as their first
660 parameter, making them similar to instance methods on Python classes).
661
662 This function is called automatically when creating a module from
663 ``PyModuleDef`` (such as when using :ref:`multi-phase-initialization`,
664 ``PyModule_Create``, or ``PyModule_FromDefAndSpec``).
665 Some module authors may prefer defining functions in multiple
666 :c:type:`PyMethodDef` arrays; in that case they should call this function
667 directly.
668
669 The *functions* array must be statically allocated (or otherwise guaranteed
670 to outlive the module object).
671
672 .. versionadded:: 3.5
673
674 .. c:function:: int PyModule_SetDocString(PyObject *module, const char *docstring)
675
676 Set the docstring for *module* to *docstring*.
677 This function is called automatically when creating a module from
678 ``PyModuleDef`` (such as when using :ref:`multi-phase-initialization`,
679 ``PyModule_Create``, or ``PyModule_FromDefAndSpec``).
680
681 Return ``0`` on success.
682 Return ``-1`` with an exception set on error.
683
684 .. versionadded:: 3.5
685
686 .. c:function:: int PyUnstable_Module_SetGIL(PyObject *module, void *gil)
687
688 Indicate that *module* does or does not support running without the global
689 interpreter lock (GIL), using one of the values from
690 :c:macro:`Py_mod_gil`. It must be called during *module*'s initialization
691 function when using :ref:`single-phase-initialization`.
692 If this function is not called during module initialization, the
693 import machinery assumes the module does not support running without the
694 GIL. This function is only available in Python builds configured with
695 :option:`--disable-gil`.
696 Return ``-1`` with an exception set on error, ``0`` on success.
697
698 .. versionadded:: 3.13
699
700
701 Module lookup (single-phase initialization)
702 ...........................................
703
704 The legacy :ref:`single-phase initialization <single-phase-initialization>`
705 initialization scheme creates singleton modules that can be looked up
706 in the context of the current interpreter. This allows the module object to be
707 retrieved later with only a reference to the module definition.
708
709 These functions will not work on modules created using multi-phase initialization,
710 since multiple such modules can be created from a single definition.
711
712 .. c:function:: PyObject* PyState_FindModule(PyModuleDef *def)
713
714 Returns the module object that was created from *def* for the current interpreter.
715 This method requires that the module object has been attached to the interpreter state with
716 :c:func:`PyState_AddModule` beforehand. In case the corresponding module object is not
717 found or has not been attached to the interpreter state yet, it returns ``NULL``.
718
719 .. c:function:: int PyState_AddModule(PyObject *module, PyModuleDef *def)
720
721 Attaches the module object passed to the function to the interpreter state. This allows
722 the module object to be accessible via :c:func:`PyState_FindModule`.
723
724 Only effective on modules created using single-phase initialization.
725
726 Python calls ``PyState_AddModule`` automatically after importing a module
727 that uses :ref:`single-phase initialization <single-phase-initialization>`,
728 so it is unnecessary (but harmless) to call it from module initialization
729 code. An explicit call is needed only if the module's own init code
730 subsequently calls ``PyState_FindModule``.
731 The function is mainly intended for implementing alternative import
732 mechanisms (either by calling it directly, or by referring to its
733 implementation for details of the required state updates).
734
735 If a module was attached previously using the same *def*, it is replaced
736 by the new *module*.
737
738 The caller must have an :term:`attached thread state`.
739
740 Return ``-1`` with an exception set on error, ``0`` on success.
741
742 .. versionadded:: 3.3
743
744 .. c:function:: int PyState_RemoveModule(PyModuleDef *def)
745
746 Removes the module object created from *def* from the interpreter state.
747 Return ``-1`` with an exception set on error, ``0`` on success.
748
749 The caller must have an :term:`attached thread state`.
750
751 .. versionadded:: 3.3