libimp.tex 11.9 KB
Newer Older
Fred Drake's avatar
Fred Drake committed
1
\section{\module{imp} ---
Fred Drake's avatar
Fred Drake committed
2
         Access the \keyword{import} internals}
3

Fred Drake's avatar
Fred Drake committed
4
\declaremodule{builtin}{imp}
5 6
\modulesynopsis{Access the implementation of the \keyword{import} statement.}

Guido van Rossum's avatar
Guido van Rossum committed
7

8
This\stindex{import} module provides an interface to the mechanisms
Fred Drake's avatar
Fred Drake committed
9 10
used to implement the \keyword{import} statement.  It defines the
following constants and functions:
Guido van Rossum's avatar
Guido van Rossum committed
11 12 13


\begin{funcdesc}{get_magic}{}
Fred Drake's avatar
Fred Drake committed
14
\indexii{file}{byte-code}
15
Return the magic string value used to recognize byte-compiled code
Fred Drake's avatar
Fred Drake committed
16
files (\file{.pyc} files).  (This value may be different for each
17
Python version.)
Guido van Rossum's avatar
Guido van Rossum committed
18 19 20
\end{funcdesc}

\begin{funcdesc}{get_suffixes}{}
21
Return a list of triples, each describing a particular type of module.
Guido van Rossum's avatar
Guido van Rossum committed
22 23 24
Each triple has the form \code{(\var{suffix}, \var{mode},
\var{type})}, where \var{suffix} is a string to be appended to the
module name to form the filename to search for, \var{mode} is the mode
Fred Drake's avatar
Fred Drake committed
25 26
string to pass to the built-in \function{open()} function to open the
file (this can be \code{'r'} for text files or \code{'rb'} for binary
Guido van Rossum's avatar
Guido van Rossum committed
27
files), and \var{type} is the file type, which has one of the values
Fred Drake's avatar
Fred Drake committed
28 29
\constant{PY_SOURCE}, \constant{PY_COMPILED}, or
\constant{C_EXTENSION}, described below.
Guido van Rossum's avatar
Guido van Rossum committed
30 31
\end{funcdesc}

Fred Drake's avatar
Fred Drake committed
32
\begin{funcdesc}{find_module}{name\optional{, path}}
33 34
Try to find the module \var{name} on the search path \var{path}.  If
\var{path} is a list of directory names, each directory is searched
Fred Drake's avatar
Fred Drake committed
35
for files with any of the suffixes returned by \function{get_suffixes()}
36 37 38 39
above.  Invalid names in the list are silently ignored (but all list
items must be strings).  If \var{path} is omitted or \code{None}, the
list of directory names given by \code{sys.path} is searched, but
first it searches a few special places: it tries to find a built-in
Fred Drake's avatar
Fred Drake committed
40 41 42
module with the given name (\constant{C_BUILTIN}), then a frozen module
(\constant{PY_FROZEN}), and on some systems some other places are looked
in as well (on the Mac, it looks for a resource (\constant{PY_RESOURCE});
43 44 45 46
on Windows, it looks in the registry which may point to a specific
file).

If search is successful, the return value is a triple
Guido van Rossum's avatar
Guido van Rossum committed
47
\code{(\var{file}, \var{pathname}, \var{description})} where
48 49
\var{file} is an open file object positioned at the beginning,
\var{pathname} is the pathname of the
Guido van Rossum's avatar
Guido van Rossum committed
50
file found, and \var{description} is a triple as contained in the list
Fred Drake's avatar
Fred Drake committed
51
returned by \function{get_suffixes()} describing the kind of module found.
52 53 54
If the module does not live in a file, the returned \var{file} is
\code{None}, \var{filename} is the empty string, and the
\var{description} tuple contains empty strings for its suffix and
55
mode; the module type is as indicate in parentheses above.  If the
Fred Drake's avatar
Fred Drake committed
56
search is unsuccessful, \exception{ImportError} is raised.  Other
57 58 59
exceptions indicate problems with the arguments or environment.

This function does not handle hierarchical module names (names
60
containing dots).  In order to find \var{P}.\var{M}, that is, submodule
Fred Drake's avatar
Fred Drake committed
61 62 63
\var{M} of package \var{P}, use \function{find_module()} and
\function{load_module()} to find and load package \var{P}, and then use
\function{find_module()} with the \var{path} argument set to
64 65
\code{\var{P}.__path__}.  When \var{P} itself has a dotted name, apply
this recipe recursively.
Guido van Rossum's avatar
Guido van Rossum committed
66 67
\end{funcdesc}

68
\begin{funcdesc}{load_module}{name, file, filename, description}
Fred Drake's avatar
Fred Drake committed
69
Load a module that was previously found by \function{find_module()} (or by
70 71
an otherwise conducted search yielding compatible results).  This
function does more than importing the module: if the module was
Fred Drake's avatar
Fred Drake committed
72
already imported, it is equivalent to a
73 74 75 76 77 78 79 80
\function{reload()}\bifuncindex{reload}!  The \var{name} argument
indicates the full module name (including the package name, if this is
a submodule of a package).  The \var{file} argument is an open file,
and \var{filename} is the corresponding file name; these can be
\code{None} and \code{''}, respectively, when the module is not being
loaded from a file.  The \var{description} argument is a tuple, as
would be returned by \function{get_suffixes()}, describing what kind
of module must be loaded.
81 82

If the load is successful, the return value is the module object;
Fred Drake's avatar
Fred Drake committed
83
otherwise, an exception (usually \exception{ImportError}) is raised.
84 85 86

\strong{Important:} the caller is responsible for closing the
\var{file} argument, if it was not \code{None}, even when an exception
Fred Drake's avatar
Fred Drake committed
87 88
is raised.  This is best done using a \keyword{try}
... \keyword{finally} statement.
89 90 91 92
\end{funcdesc}

\begin{funcdesc}{new_module}{name}
Return a new empty module object called \var{name}.  This object is
Fred Drake's avatar
Fred Drake committed
93
\emph{not} inserted in \code{sys.modules}.
94 95
\end{funcdesc}

96
\begin{funcdesc}{lock_held}{}
97 98
Return \code{True} if the import lock is currently held, else \code{False}.
On platforms without threads, always return \code{False}.
99 100 101 102 103 104 105 106 107 108

On platforms with threads, a thread executing an import holds an internal
lock until the import is complete.
This lock blocks other threads from doing an import until the original
import completes, which in turn prevents other threads from seeing
incomplete module objects constructed by the original thread while in
the process of completing its import (and the imports, if any,
triggered by that).
\end{funcdesc}

109 110 111 112 113 114 115 116 117 118 119 120 121
\begin{funcdesc}{acquire_lock}{}
Acquires the interpreter's import lock for the current thread.  This lock
should be used by import hooks to ensure thread-safety when importing modules.
On platforms without threads, this function does nothing.
\versionadded{2.3}
\end{funcdesc}

\begin{funcdesc}{release_lock}{}
Release the interpreter's import lock.
On platforms without threads, this function does nothing.
\versionadded{2.3}
\end{funcdesc}

122
The following constants with integer values, defined in this module,
Fred Drake's avatar
Fred Drake committed
123
are used to indicate the search result of \function{find_module()}.
124 125 126 127 128 129 130 131 132 133 134 135 136 137

\begin{datadesc}{PY_SOURCE}
The module was found as a source file.
\end{datadesc}

\begin{datadesc}{PY_COMPILED}
The module was found as a compiled code object file.
\end{datadesc}

\begin{datadesc}{C_EXTENSION}
The module was found as dynamically loadable shared library.
\end{datadesc}

\begin{datadesc}{PY_RESOURCE}
138 139
The module was found as a Mac OS 9 resource.  This value can only be
returned on a Mac OS 9 or earlier Macintosh.
140 141 142 143 144 145 146 147 148 149 150
\end{datadesc}

\begin{datadesc}{PKG_DIRECTORY}
The module was found as a package directory.
\end{datadesc}

\begin{datadesc}{C_BUILTIN}
The module was found as a built-in module.
\end{datadesc}

\begin{datadesc}{PY_FROZEN}
Fred Drake's avatar
Fred Drake committed
151
The module was found as a frozen module (see \function{init_frozen()}).
152 153 154
\end{datadesc}

The following constant and functions are obsolete; their functionality
Fred Drake's avatar
Fred Drake committed
155
is available through \function{find_module()} or \function{load_module()}.
156 157 158 159 160 161
They are kept around for backward compatibility:

\begin{datadesc}{SEARCH_ERROR}
Unused.
\end{datadesc}

Guido van Rossum's avatar
Guido van Rossum committed
162 163 164
\begin{funcdesc}{init_builtin}{name}
Initialize the built-in module called \var{name} and return its module
object.  If the module was already initialized, it will be initialized
Fred Drake's avatar
Fred Drake committed
165
\emph{again}.  A few modules cannot be initialized twice --- attempting
Fred Drake's avatar
Fred Drake committed
166 167
to initialize these again will raise an \exception{ImportError}
exception.  If there is no
Guido van Rossum's avatar
Guido van Rossum committed
168 169 170 171 172 173
built-in module called \var{name}, \code{None} is returned.
\end{funcdesc}

\begin{funcdesc}{init_frozen}{name}
Initialize the frozen module called \var{name} and return its module
object.  If the module was already initialized, it will be initialized
Fred Drake's avatar
Fred Drake committed
174
\emph{again}.  If there is no frozen module called \var{name},
Guido van Rossum's avatar
Guido van Rossum committed
175 176
\code{None} is returned.  (Frozen modules are modules written in
Python whose compiled byte-code object is incorporated into a
Fred Drake's avatar
Fred Drake committed
177 178
custom-built Python interpreter by Python's \program{freeze} utility.
See \file{Tools/freeze/} for now.)
Guido van Rossum's avatar
Guido van Rossum committed
179 180 181
\end{funcdesc}

\begin{funcdesc}{is_builtin}{name}
Fred Drake's avatar
Fred Drake committed
182 183 184 185 186
Return \code{1} if there is a built-in module called \var{name} which
can be initialized again.  Return \code{-1} if there is a built-in
module called \var{name} which cannot be initialized again (see
\function{init_builtin()}).  Return \code{0} if there is no built-in
module called \var{name}.
Guido van Rossum's avatar
Guido van Rossum committed
187 188 189
\end{funcdesc}

\begin{funcdesc}{is_frozen}{name}
190 191
Return \code{True} if there is a frozen module (see
\function{init_frozen()}) called \var{name}, or \code{False} if there is
Fred Drake's avatar
Fred Drake committed
192
no such module.
Guido van Rossum's avatar
Guido van Rossum committed
193 194
\end{funcdesc}

195
\begin{funcdesc}{load_compiled}{name, pathname, \optional{file}}
Fred Drake's avatar
Fred Drake committed
196
\indexii{file}{byte-code}
Guido van Rossum's avatar
Guido van Rossum committed
197 198
Load and initialize a module implemented as a byte-compiled code file
and return its module object.  If the module was already initialized,
Fred Drake's avatar
Fred Drake committed
199
it will be initialized \emph{again}.  The \var{name} argument is used
Guido van Rossum's avatar
Guido van Rossum committed
200
to create or access a module object.  The \var{pathname} argument
201
points to the byte-compiled code file.  The \var{file}
Guido van Rossum's avatar
Guido van Rossum committed
202
argument is the byte-compiled code file, open for reading in binary
203 204
mode, from the beginning.
It must currently be a real file object, not a
Guido van Rossum's avatar
Guido van Rossum committed
205 206 207
user-defined class emulating a file.
\end{funcdesc}

Fred Drake's avatar
Fred Drake committed
208
\begin{funcdesc}{load_dynamic}{name, pathname\optional{, file}}
Guido van Rossum's avatar
Guido van Rossum committed
209 210
Load and initialize a module implemented as a dynamically loadable
shared library and return its module object.  If the module was
Fred Drake's avatar
Fred Drake committed
211
already initialized, it will be initialized \emph{again}.  Some modules
Guido van Rossum's avatar
Guido van Rossum committed
212 213 214
don't like that and may raise an exception.  The \var{pathname}
argument must point to the shared library.  The \var{name} argument is
used to construct the name of the initialization function: an external
Fred Drake's avatar
Fred Drake committed
215
C function called \samp{init\var{name}()} in the shared library is
216
called.  The optional \var{file} argument is ignored.  (Note: using
Guido van Rossum's avatar
Guido van Rossum committed
217 218 219 220
shared libraries is highly system dependent, and not all systems
support it.)
\end{funcdesc}

221
\begin{funcdesc}{load_source}{name, pathname\optional{, file}}
Guido van Rossum's avatar
Guido van Rossum committed
222 223
Load and initialize a module implemented as a Python source file and
return its module object.  If the module was already initialized, it
Fred Drake's avatar
Fred Drake committed
224
will be initialized \emph{again}.  The \var{name} argument is used to
Guido van Rossum's avatar
Guido van Rossum committed
225
create or access a module object.  The \var{pathname} argument points
226 227 228
to the source file.  The \var{file} argument is the source
file, open for reading as text, from the beginning.
It must currently be a real file
Guido van Rossum's avatar
Guido van Rossum committed
229
object, not a user-defined class emulating a file.  Note that if a
Fred Drake's avatar
Fred Drake committed
230 231 232
properly matching byte-compiled file (with suffix \file{.pyc} or
\file{.pyo}) exists, it will be used instead of parsing the given
source file.
Guido van Rossum's avatar
Guido van Rossum committed
233 234
\end{funcdesc}

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
\begin{classdesc}{NullImporter}{path_string}
The \class{NullImporter} type is a \pep{302} import hook that handles
non-directory path strings by failing to find any modules.  Calling this
type with an existing directory or empty string raises
\exception{ImportError}.  Otherwise, a \class{NullImporter} instance is
returned.

Python adds instances of this type to \code{sys.path_importer_cache} for
any path entries that are not directories and are not handled by any other
path hooks on \code{sys.path_hooks}.  Instances have only one method:

\begin{methoddesc}{find_module}{fullname \optional{, path}}
This method always returns \code{None}, indicating that the requested
module could not be found.
\end{methoddesc}

\versionadded{2.5}
\end{classdesc}
253

Guido van Rossum's avatar
Guido van Rossum committed
254
\subsection{Examples}
255 256
\label{examples-imp}

257
The following function emulates what was the standard import statement
258
up to Python 1.4 (no hierarchical module names).  (This
259
\emph{implementation} wouldn't work in that version, since
Fred Drake's avatar
Fred Drake committed
260 261
\function{find_module()} has been extended and
\function{load_module()} has been added in 1.4.)
Guido van Rossum's avatar
Guido van Rossum committed
262

263
\begin{verbatim}
264 265
import imp
import sys
Guido van Rossum's avatar
Guido van Rossum committed
266

267
def __import__(name, globals=None, locals=None, fromlist=None):
268
    # Fast path: see if the module has already been imported.
269
    try:
270
        return sys.modules[name]
271 272
    except KeyError:
        pass
273 274

    # If any of the following calls raises an exception,
275
    # there's a problem we can't handle -- let the caller handle it.
276

277
    fp, pathname, description = imp.find_module(name)
278

279
    try:
280
        return imp.load_module(name, fp, pathname, description)
281 282
    finally:
        # Since we may exit via an exception, close fp explicitly.
283 284
        if fp:
            fp.close()
285
\end{verbatim}
286 287

A more complete example that implements hierarchical module names and
Fred Drake's avatar
Fred Drake committed
288
includes a \function{reload()}\bifuncindex{reload} function can be
289 290 291
found in the module \module{knee}\refmodindex{knee}.  The
\module{knee} module can be found in \file{Demo/imputil/} in the
Python source distribution.