Debian Codegraph @

Doc/c-api/import.rst

raw
1 .. highlight:: c
2
3 .. _importing:
4
5 Importing Modules
6 =================
7
8
9 .. c:function:: PyObject* PyImport_ImportModule(const char *name)
10
11 .. index::
12 single: package variable; __all__
13 single: __all__ (package variable)
14 single: modules (in module sys)
15
16 This is a wrapper around :c:func:`PyImport_Import()` which takes a
17 :c:expr:`const char *` as an argument instead of a :c:expr:`PyObject *`.
18
19 .. c:function:: PyObject* PyImport_ImportModuleNoBlock(const char *name)
20
21 This function is a deprecated alias of :c:func:`PyImport_ImportModule`.
22
23 .. versionchanged:: 3.3
24 This function used to fail immediately when the import lock was held
25 by another thread. In Python 3.3 though, the locking scheme switched
26 to per-module locks for most purposes, so this function's special
27 behaviour isn't needed anymore.
28
29 .. deprecated-removed:: 3.13 3.15
30 Use :c:func:`PyImport_ImportModule` instead.
31
32
33 .. c:function:: PyObject* PyImport_ImportModuleEx(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)
34
35 .. index:: pair: built-in function; __import__
36
37 Import a module. This is best described by referring to the built-in Python
38 function :func:`__import__`.
39
40 The return value is a new reference to the imported module or top-level
41 package, or ``NULL`` with an exception set on failure. Like for
42 :func:`__import__`, the return value when a submodule of a package was
43 requested is normally the top-level package, unless a non-empty *fromlist*
44 was given.
45
46 Failing imports remove incomplete module objects, like with
47 :c:func:`PyImport_ImportModule`.
48
49
50 .. c:function:: PyObject* PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
51
52 Import a module. This is best described by referring to the built-in Python
53 function :func:`__import__`, as the standard :func:`__import__` function calls
54 this function directly.
55
56 The return value is a new reference to the imported module or top-level package,
57 or ``NULL`` with an exception set on failure. Like for :func:`__import__`,
58 the return value when a submodule of a package was requested is normally the
59 top-level package, unless a non-empty *fromlist* was given.
60
61 .. versionadded:: 3.3
62
63
64 .. c:function:: PyObject* PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)
65
66 Similar to :c:func:`PyImport_ImportModuleLevelObject`, but the name is a
67 UTF-8 encoded string instead of a Unicode object.
68
69 .. versionchanged:: 3.3
70 Negative values for *level* are no longer accepted.
71
72 .. c:function:: PyObject* PyImport_Import(PyObject *name)
73
74 This is a higher-level interface that calls the current "import hook
75 function" (with an explicit *level* of 0, meaning absolute import). It
76 invokes the :func:`__import__` function from the ``__builtins__`` of the
77 current globals. This means that the import is done using whatever import
78 hooks are installed in the current environment.
79
80 This function always uses absolute imports.
81
82
83 .. c:function:: PyObject* PyImport_ReloadModule(PyObject *m)
84
85 Reload a module. Return a new reference to the reloaded module, or ``NULL`` with
86 an exception set on failure (the module still exists in this case).
87
88
89 .. c:function:: PyObject* PyImport_AddModuleRef(const char *name)
90
91 Return the module object corresponding to a module name.
92
93 The *name* argument may be of the form ``package.module``. First check the
94 modules dictionary if there's one there, and if not, create a new one and
95 insert it in the modules dictionary.
96
97 Return a :term:`strong reference` to the module on success. Return ``NULL``
98 with an exception set on failure.
99
100 The module name *name* is decoded from UTF-8.
101
102 This function does not load or import the module; if the module wasn't
103 already loaded, you will get an empty module object. Use
104 :c:func:`PyImport_ImportModule` or one of its variants to import a module.
105 Package structures implied by a dotted name for *name* are not created if
106 not already present.
107
108 .. versionadded:: 3.13
109
110
111 .. c:function:: PyObject* PyImport_AddModuleObject(PyObject *name)
112
113 Similar to :c:func:`PyImport_AddModuleRef`, but return a :term:`borrowed
114 reference` and *name* is a Python :class:`str` object.
115
116 .. versionadded:: 3.3
117
118
119 .. c:function:: PyObject* PyImport_AddModule(const char *name)
120
121 Similar to :c:func:`PyImport_AddModuleRef`, but return a :term:`borrowed
122 reference`.
123
124
125 .. c:function:: PyObject* PyImport_ExecCodeModule(const char *name, PyObject *co)
126
127 .. index:: pair: built-in function; compile
128
129 Given a module name (possibly of the form ``package.module``) and a code object
130 read from a Python bytecode file or obtained from the built-in function
131 :func:`compile`, load the module. Return a new reference to the module object,
132 or ``NULL`` with an exception set if an error occurred. *name*
133 is removed from :data:`sys.modules` in error cases, even if *name* was already
134 in :data:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`. Leaving
135 incompletely initialized modules in :data:`sys.modules` is dangerous, as imports of
136 such modules have no way to know that the module object is an unknown (and
137 probably damaged with respect to the module author's intents) state.
138
139 The module's :attr:`~module.__spec__` and :attr:`~module.__loader__` will be
140 set, if not set already, with the appropriate values. The spec's loader
141 will be set to the module's :attr:`!__loader__` (if set) and to an instance
142 of :class:`~importlib.machinery.SourceFileLoader` otherwise.
143
144 The module's :attr:`~module.__file__` attribute will be set to the code
145 object's :attr:`~codeobject.co_filename`. If applicable,
146 :attr:`~module.__cached__` will also be set.
147
148 This function will reload the module if it was already imported. See
149 :c:func:`PyImport_ReloadModule` for the intended way to reload a module.
150
151 If *name* points to a dotted name of the form ``package.module``, any package
152 structures not already created will still not be created.
153
154 See also :c:func:`PyImport_ExecCodeModuleEx` and
155 :c:func:`PyImport_ExecCodeModuleWithPathnames`.
156
157 .. versionchanged:: 3.12
158 The setting of :attr:`~module.__cached__` and :attr:`~module.__loader__`
159 is deprecated. See :class:`~importlib.machinery.ModuleSpec` for
160 alternatives.
161
162
163 .. c:function:: PyObject* PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
164
165 Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`~module.__file__`
166 attribute of the module object is set to *pathname* if it is non-``NULL``.
167
168 See also :c:func:`PyImport_ExecCodeModuleWithPathnames`.
169
170
171 .. c:function:: PyObject* PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname, PyObject *cpathname)
172
173 Like :c:func:`PyImport_ExecCodeModuleEx`, but the :attr:`~module.__cached__`
174 attribute of the module object is set to *cpathname* if it is
175 non-``NULL``. Of the three functions, this is the preferred one to use.
176
177 .. versionadded:: 3.3
178
179 .. versionchanged:: 3.12
180 Setting :attr:`~module.__cached__` is deprecated. See
181 :class:`~importlib.machinery.ModuleSpec` for alternatives.
182
183
184 .. c:function:: PyObject* PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co, const char *pathname, const char *cpathname)
185
186 Like :c:func:`PyImport_ExecCodeModuleObject`, but *name*, *pathname* and
187 *cpathname* are UTF-8 encoded strings. Attempts are also made to figure out
188 what the value for *pathname* should be from *cpathname* if the former is
189 set to ``NULL``.
190
191 .. versionadded:: 3.2
192 .. versionchanged:: 3.3
193 Uses :func:`!imp.source_from_cache` in calculating the source path if
194 only the bytecode path is provided.
195 .. versionchanged:: 3.12
196 No longer uses the removed :mod:`!imp` module.
197
198
199 .. c:function:: long PyImport_GetMagicNumber()
200
201 Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` file).
202 The magic number should be present in the first four bytes of the bytecode
203 file, in little-endian byte order. Returns ``-1`` on error.
204
205 .. versionchanged:: 3.3
206 Return value of ``-1`` upon failure.
207
208
209 .. c:function:: const char * PyImport_GetMagicTag()
210
211 Return the magic tag string for :pep:`3147` format Python bytecode file
212 names. Keep in mind that the value at ``sys.implementation.cache_tag`` is
213 authoritative and should be used instead of this function.
214
215 .. versionadded:: 3.2
216
217 .. c:function:: PyObject* PyImport_GetModuleDict()
218
219 Return the dictionary used for the module administration (a.k.a.
220 ``sys.modules``). Note that this is a per-interpreter variable.
221
222 .. c:function:: PyObject* PyImport_GetModule(PyObject *name)
223
224 Return the already imported module with the given name. If the
225 module has not been imported yet then returns ``NULL`` but does not set
226 an error. Returns ``NULL`` and sets an error if the lookup failed.
227
228 .. versionadded:: 3.7
229
230 .. c:function:: PyObject* PyImport_GetImporter(PyObject *path)
231
232 Return a finder object for a :data:`sys.path`/:attr:`!pkg.__path__` item
233 *path*, possibly by fetching it from the :data:`sys.path_importer_cache`
234 dict. If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook
235 is found that can handle the path item. Return ``None`` if no hook could;
236 this tells our caller that the :term:`path based finder` could not find a
237 finder for this path item. Cache the result in :data:`sys.path_importer_cache`.
238 Return a new reference to the finder object.
239
240
241 .. c:function:: int PyImport_ImportFrozenModuleObject(PyObject *name)
242
243 Load a frozen module named *name*. Return ``1`` for success, ``0`` if the
244 module is not found, and ``-1`` with an exception set if the initialization
245 failed. To access the imported module on a successful load, use
246 :c:func:`PyImport_ImportModule`. (Note the misnomer --- this function would
247 reload the module if it was already imported.)
248
249 .. versionadded:: 3.3
250
251 .. versionchanged:: 3.4
252 The ``__file__`` attribute is no longer set on the module.
253
254
255 .. c:function:: int PyImport_ImportFrozenModule(const char *name)
256
257 Similar to :c:func:`PyImport_ImportFrozenModuleObject`, but the name is a
258 UTF-8 encoded string instead of a Unicode object.
259
260
261 .. c:struct:: _frozen
262
263 .. index:: single: freeze utility
264
265 This is the structure type definition for frozen module descriptors, as
266 generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the
267 Python source distribution). Its definition, found in :file:`Include/import.h`,
268 is::
269
270 struct _frozen {
271 const char *name;
272 const unsigned char *code;
273 int size;
274 bool is_package;
275 };
276
277 .. versionchanged:: 3.11
278 The new ``is_package`` field indicates whether the module is a package or not.
279 This replaces setting the ``size`` field to a negative value.
280
281 .. c:var:: const struct _frozen* PyImport_FrozenModules
282
283 This pointer is initialized to point to an array of :c:struct:`_frozen`
284 records, terminated by one whose members are all ``NULL`` or zero. When a frozen
285 module is imported, it is searched in this table. Third-party code could play
286 tricks with this to provide a dynamically created collection of frozen modules.
287
288
289 .. c:function:: int PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
290
291 Add a single module to the existing table of built-in modules. This is a
292 convenience wrapper around :c:func:`PyImport_ExtendInittab`, returning ``-1`` if
293 the table could not be extended. The new module can be imported by the name
294 *name*, and uses the function *initfunc* as the initialization function called
295 on the first attempted import. This should be called before
296 :c:func:`Py_Initialize`.
297
298
299 .. c:struct:: _inittab
300
301 Structure describing a single entry in the list of built-in modules.
302 Programs which
303 embed Python may use an array of these structures in conjunction with
304 :c:func:`PyImport_ExtendInittab` to provide additional built-in modules.
305 The structure consists of two members:
306
307 .. c:member:: const char *name
308
309 The module name, as an ASCII encoded string.
310
311 .. c:member:: PyObject* (*initfunc)(void)
312
313 Initialization function for a module built into the interpreter.
314
315
316 .. c:function:: int PyImport_ExtendInittab(struct _inittab *newtab)
317
318 Add a collection of modules to the table of built-in modules. The *newtab*
319 array must end with a sentinel entry which contains ``NULL`` for the :c:member:`~_inittab.name`
320 field; failure to provide the sentinel value can result in a memory fault.
321 Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to
322 extend the internal table. In the event of failure, no modules are added to the
323 internal table. This must be called before :c:func:`Py_Initialize`.
324
325 If Python is initialized multiple times, :c:func:`PyImport_AppendInittab` or
326 :c:func:`PyImport_ExtendInittab` must be called before each Python
327 initialization.
328
329
330 .. c:var:: struct _inittab *PyImport_Inittab
331
332 The table of built-in modules used by Python initialization. Do not use this directly;
333 use :c:func:`PyImport_AppendInittab` and :c:func:`PyImport_ExtendInittab`
334 instead.
335
336
337 .. c:function:: PyObject* PyImport_ImportModuleAttr(PyObject *mod_name, PyObject *attr_name)
338
339 Import the module *mod_name* and get its attribute *attr_name*.
340
341 Names must be Python :class:`str` objects.
342
343 Helper function combining :c:func:`PyImport_Import` and
344 :c:func:`PyObject_GetAttr`. For example, it can raise :exc:`ImportError` if
345 the module is not found, and :exc:`AttributeError` if the attribute doesn't
346 exist.
347
348 .. versionadded:: 3.14
349
350 .. c:function:: PyObject* PyImport_ImportModuleAttrString(const char *mod_name, const char *attr_name)
351
352 Similar to :c:func:`PyImport_ImportModuleAttr`, but names are UTF-8 encoded
353 strings instead of Python :class:`str` objects.
354
355 .. versionadded:: 3.14