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