blob: 5428386208e7426b56eddc39a2f1fd8a0f19747f [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`imp` --- Access the :keyword:`import` internals
3=====================================================
4
5.. module:: imp
6 :synopsis: Access the implementation of the import statement.
7
8
9.. index:: statement: import
10
11This module provides an interface to the mechanisms used to implement the
12:keyword:`import` statement. It defines the following constants and functions:
13
14
15.. function:: get_magic()
16
17 .. index:: pair: file; byte-code
18
19 Return the magic string value used to recognize byte-compiled code files
20 (:file:`.pyc` files). (This value may be different for each Python version.)
21
22
23.. function:: get_suffixes()
24
25 Return a list of triples, each describing a particular type of module. Each
26 triple has the form ``(suffix, mode, type)``, where *suffix* is a string to be
27 appended to the module name to form the filename to search for, *mode* is the
28 mode string to pass to the built-in :func:`open` function to open the file (this
29 can be ``'r'`` for text files or ``'rb'`` for binary files), and *type* is the
30 file type, which has one of the values :const:`PY_SOURCE`, :const:`PY_COMPILED`,
31 or :const:`C_EXTENSION`, described below.
32
33
34.. function:: find_module(name[, path])
35
36 Try to find the module *name* on the search path *path*. If *path* is a list of
37 directory names, each directory is searched for files with any of the suffixes
38 returned by :func:`get_suffixes` above. Invalid names in the list are silently
39 ignored (but all list items must be strings). If *path* is omitted or ``None``,
40 the list of directory names given by ``sys.path`` is searched, but first it
41 searches a few special places: it tries to find a built-in module with the given
42 name (:const:`C_BUILTIN`), then a frozen module (:const:`PY_FROZEN`), and on
43 some systems some other places are looked in as well (on the Mac, it looks for a
44 resource (:const:`PY_RESOURCE`); on Windows, it looks in the registry which may
45 point to a specific file).
46
47 If search is successful, the return value is a triple ``(file, pathname,
48 description)`` where *file* is an open file object positioned at the beginning,
49 *pathname* is the pathname of the file found, and *description* is a triple as
50 contained in the list returned by :func:`get_suffixes` describing the kind of
51 module found. If the module does not live in a file, the returned *file* is
52 ``None``, *filename* is the empty string, and the *description* tuple contains
53 empty strings for its suffix and mode; the module type is as indicate in
54 parentheses above. If the search is unsuccessful, :exc:`ImportError` is raised.
55 Other exceptions indicate problems with the arguments or environment.
56
57 This function does not handle hierarchical module names (names containing dots).
58 In order to find *P*.*M*, that is, submodule *M* of package *P*, use
59 :func:`find_module` and :func:`load_module` to find and load package *P*, and
60 then use :func:`find_module` with the *path* argument set to ``P.__path__``.
61 When *P* itself has a dotted name, apply this recipe recursively.
62
63
64.. function:: load_module(name, file, filename, description)
65
66 .. index:: builtin: reload
67
68 Load a module that was previously found by :func:`find_module` (or by an
69 otherwise conducted search yielding compatible results). This function does
70 more than importing the module: if the module was already imported, it is
71 equivalent to a :func:`reload`! The *name* argument indicates the full module
72 name (including the package name, if this is a submodule of a package). The
73 *file* argument is an open file, and *filename* is the corresponding file name;
74 these can be ``None`` and ``''``, respectively, when the module is not being
75 loaded from a file. The *description* argument is a tuple, as would be returned
76 by :func:`get_suffixes`, describing what kind of module must be loaded.
77
78 If the load is successful, the return value is the module object; otherwise, an
79 exception (usually :exc:`ImportError`) is raised.
80
81 **Important:** the caller is responsible for closing the *file* argument, if it
82 was not ``None``, even when an exception is raised. This is best done using a
83 :keyword:`try` ... :keyword:`finally` statement.
84
85
86.. function:: new_module(name)
87
88 Return a new empty module object called *name*. This object is *not* inserted
89 in ``sys.modules``.
90
91
92.. function:: lock_held()
93
94 Return ``True`` if the import lock is currently held, else ``False``. On
95 platforms without threads, always return ``False``.
96
97 On platforms with threads, a thread executing an import holds an internal lock
98 until the import is complete. This lock blocks other threads from doing an
99 import until the original import completes, which in turn prevents other threads
100 from seeing incomplete module objects constructed by the original thread while
101 in the process of completing its import (and the imports, if any, triggered by
102 that).
103
104
105.. function:: acquire_lock()
106
107 Acquires the interpreter's import lock for the current thread. This lock should
108 be used by import hooks to ensure thread-safety when importing modules. On
109 platforms without threads, this function does nothing.
110
111 .. versionadded:: 2.3
112
113
114.. function:: release_lock()
115
116 Release the interpreter's import lock. On platforms without threads, this
117 function does nothing.
118
119 .. versionadded:: 2.3
120
121The following constants with integer values, defined in this module, are used to
122indicate the search result of :func:`find_module`.
123
124
125.. data:: PY_SOURCE
126
127 The module was found as a source file.
128
129
130.. data:: PY_COMPILED
131
132 The module was found as a compiled code object file.
133
134
135.. data:: C_EXTENSION
136
137 The module was found as dynamically loadable shared library.
138
139
140.. data:: PY_RESOURCE
141
142 The module was found as a Mac OS 9 resource. This value can only be returned on
143 a Mac OS 9 or earlier Macintosh.
144
145
146.. data:: PKG_DIRECTORY
147
148 The module was found as a package directory.
149
150
151.. data:: C_BUILTIN
152
153 The module was found as a built-in module.
154
155
156.. data:: PY_FROZEN
157
158 The module was found as a frozen module (see :func:`init_frozen`).
159
160The following constant and functions are obsolete; their functionality is
161available through :func:`find_module` or :func:`load_module`. They are kept
162around for backward compatibility:
163
164
165.. data:: SEARCH_ERROR
166
167 Unused.
168
169
170.. function:: init_builtin(name)
171
172 Initialize the built-in module called *name* and return its module object along
173 with storing it in ``sys.modules``. If the module was already initialized, it
174 will be initialized *again*. Re-initialization involves the copying of the
175 built-in module's ``__dict__`` from the cached module over the module's entry in
176 ``sys.modules``. If there is no built-in module called *name*, ``None`` is
177 returned.
178
179
180.. function:: init_frozen(name)
181
182 Initialize the frozen module called *name* and return its module object. If
183 the module was already initialized, it will be initialized *again*. If there
184 is no frozen module called *name*, ``None`` is returned. (Frozen modules are
185 modules written in Python whose compiled byte-code object is incorporated
186 into a custom-built Python interpreter by Python's :program:`freeze`
187 utility. See :file:`Tools/freeze/` for now.)
188
189
190.. function:: is_builtin(name)
191
192 Return ``1`` if there is a built-in module called *name* which can be
193 initialized again. Return ``-1`` if there is a built-in module called *name*
194 which cannot be initialized again (see :func:`init_builtin`). Return ``0`` if
195 there is no built-in module called *name*.
196
197
198.. function:: is_frozen(name)
199
200 Return ``True`` if there is a frozen module (see :func:`init_frozen`) called
201 *name*, or ``False`` if there is no such module.
202
203
204.. function:: load_compiled(name, pathname, [file])
205
206 .. index:: pair: file; byte-code
207
208 Load and initialize a module implemented as a byte-compiled code file and return
209 its module object. If the module was already initialized, it will be
210 initialized *again*. The *name* argument is used to create or access a module
211 object. The *pathname* argument points to the byte-compiled code file. The
212 *file* argument is the byte-compiled code file, open for reading in binary mode,
213 from the beginning. It must currently be a real file object, not a user-defined
214 class emulating a file.
215
216
217.. function:: load_dynamic(name, pathname[, file])
218
219 Load and initialize a module implemented as a dynamically loadable shared
220 library and return its module object. If the module was already initialized, it
221 will be initialized *again*. Re-initialization involves copying the ``__dict__``
222 attribute of the cached instance of the module over the value used in the module
223 cached in ``sys.modules``. The *pathname* argument must point to the shared
224 library. The *name* argument is used to construct the name of the
225 initialization function: an external C function called ``initname()`` in the
226 shared library is called. The optional *file* argument is ignored. (Note:
227 using shared libraries is highly system dependent, and not all systems support
228 it.)
229
230
231.. function:: load_source(name, pathname[, file])
232
233 Load and initialize a module implemented as a Python source file and return its
234 module object. If the module was already initialized, it will be initialized
235 *again*. The *name* argument is used to create or access a module object. The
236 *pathname* argument points to the source file. The *file* argument is the
237 source file, open for reading as text, from the beginning. It must currently be
238 a real file object, not a user-defined class emulating a file. Note that if a
239 properly matching byte-compiled file (with suffix :file:`.pyc` or :file:`.pyo`)
240 exists, it will be used instead of parsing the given source file.
241
242
243.. class:: NullImporter(path_string)
244
245 The :class:`NullImporter` type is a :pep:`302` import hook that handles
246 non-directory path strings by failing to find any modules. Calling this type
247 with an existing directory or empty string raises :exc:`ImportError`.
248 Otherwise, a :class:`NullImporter` instance is returned.
249
250 Python adds instances of this type to ``sys.path_importer_cache`` for any path
251 entries that are not directories and are not handled by any other path hooks on
252 ``sys.path_hooks``. Instances have only one method:
253
254
255 .. method:: NullImporter.find_module(fullname [, path])
256
257 This method always returns ``None``, indicating that the requested module could
258 not be found.
259
260 .. versionadded:: 2.5
261
262
263.. _examples-imp:
264
265Examples
266--------
267
268The following function emulates what was the standard import statement up to
269Python 1.4 (no hierarchical module names). (This *implementation* wouldn't work
270in that version, since :func:`find_module` has been extended and
271:func:`load_module` has been added in 1.4.) ::
272
273 import imp
274 import sys
275
276 def __import__(name, globals=None, locals=None, fromlist=None):
277 # Fast path: see if the module has already been imported.
278 try:
279 return sys.modules[name]
280 except KeyError:
281 pass
282
283 # If any of the following calls raises an exception,
284 # there's a problem we can't handle -- let the caller handle it.
285
286 fp, pathname, description = imp.find_module(name)
287
288 try:
289 return imp.load_module(name, fp, pathname, description)
290 finally:
291 # Since we may exit via an exception, close fp explicitly.
292 if fp:
293 fp.close()
294
295.. index::
296 builtin: reload
297 module: knee
298
299A more complete example that implements hierarchical module names and includes a
300:func:`reload` function can be found in the module :mod:`knee`. The :mod:`knee`
301module can be found in :file:`Demo/imputil/` in the Python source distribution.
302