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