blob: ee9045b446d0eedb19604bfeb8ce4643dabc7bc7 [file] [log] [blame]
Brett Cannonafccd632009-01-20 02:21:27 +00001:mod:`importlib` -- An implementation of :keyword:`import`
2==========================================================
3
4.. module:: importlib
5 :synopsis: An implementation of the import machinery.
6
7.. moduleauthor:: Brett Cannon <brett@python.org>
8.. sectionauthor:: Brett Cannon <brett@python.org>
9
10.. versionadded:: 3.1
11
12
13Introduction
14------------
15
16The purpose of the :mod:`importlib` package is two-fold. One is to provide an
17implementation of the :keyword:`import` statement (and thus, by extension, the
18:func:`__import__` function) in Python source code. This provides an
Tarek Ziadé434caaa2009-05-14 12:48:09 +000019implementation of :keyword:`import` which is portable to any Python
Brett Cannonafccd632009-01-20 02:21:27 +000020interpreter. This also provides a reference implementation which is easier to
Brett Cannonf23e3742010-06-27 23:57:46 +000021comprehend than one implemented in a programming language other than Python.
Brett Cannonafccd632009-01-20 02:21:27 +000022
Brett Cannonf23e3742010-06-27 23:57:46 +000023Two, the components to implement :keyword:`import` are exposed in this
Brett Cannonafccd632009-01-20 02:21:27 +000024package, making it easier for users to create their own custom objects (known
Brett Cannondebb98d2009-02-16 04:18:01 +000025generically as an :term:`importer`) to participate in the import process.
Brett Cannonf23e3742010-06-27 23:57:46 +000026Details on custom importers can be found in :pep:`302`.
Brett Cannonafccd632009-01-20 02:21:27 +000027
28.. seealso::
29
30 :ref:`import`
31 The language reference for the :keyword:`import` statement.
32
33 `Packages specification <http://www.python.org/doc/essays/packages.html>`__
34 Original specification of packages. Some semantics have changed since
Georg Brandl375aec22011-01-15 17:03:02 +000035 the writing of this document (e.g. redirecting based on ``None``
Brett Cannonafccd632009-01-20 02:21:27 +000036 in :data:`sys.modules`).
37
38 The :func:`.__import__` function
Brett Cannon0e13c942010-06-29 18:26:11 +000039 The :keyword:`import` statement is syntactic sugar for this function.
Brett Cannonafccd632009-01-20 02:21:27 +000040
41 :pep:`235`
42 Import on Case-Insensitive Platforms
43
44 :pep:`263`
45 Defining Python Source Code Encodings
46
47 :pep:`302`
Brett Cannonf23e3742010-06-27 23:57:46 +000048 New Import Hooks
Brett Cannonafccd632009-01-20 02:21:27 +000049
50 :pep:`328`
51 Imports: Multi-Line and Absolute/Relative
52
53 :pep:`366`
54 Main module explicit relative imports
55
Brett Cannon8917d5e2010-01-13 19:21:00 +000056 :pep:`3120`
Brett Cannonafccd632009-01-20 02:21:27 +000057 Using UTF-8 as the Default Source Encoding
58
Brett Cannon30b7a902010-06-27 21:49:22 +000059 :pep:`3147`
60 PYC Repository Directories
61
Brett Cannonafccd632009-01-20 02:21:27 +000062
63Functions
64---------
65
Brett Cannoncb4996a2012-08-06 16:34:44 -040066.. function:: __import__(name, globals=None, locals=None, fromlist=(), level=0)
Brett Cannonafccd632009-01-20 02:21:27 +000067
Brett Cannonf23e3742010-06-27 23:57:46 +000068 An implementation of the built-in :func:`__import__` function.
Brett Cannonafccd632009-01-20 02:21:27 +000069
70.. function:: import_module(name, package=None)
71
Brett Cannon33418c82009-01-22 18:37:20 +000072 Import a module. The *name* argument specifies what module to
Brett Cannonafccd632009-01-20 02:21:27 +000073 import in absolute or relative terms
74 (e.g. either ``pkg.mod`` or ``..mod``). If the name is
Guido van Rossum09613542009-03-30 20:34:57 +000075 specified in relative terms, then the *package* argument must be set to
76 the name of the package which is to act as the anchor for resolving the
Brett Cannonafccd632009-01-20 02:21:27 +000077 package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
Brett Cannon2c318a12009-02-07 01:15:27 +000078 ``pkg.mod``).
Brett Cannon78246b62009-01-25 04:56:30 +000079
Brett Cannon2c318a12009-02-07 01:15:27 +000080 The :func:`import_module` function acts as a simplifying wrapper around
Brett Cannon9f4cb1c2009-04-01 23:26:47 +000081 :func:`importlib.__import__`. This means all semantics of the function are
82 derived from :func:`importlib.__import__`, including requiring the package
83 from which an import is occurring to have been previously imported
84 (i.e., *package* must already be imported). The most important difference
85 is that :func:`import_module` returns the most nested package or module
86 that was imported (e.g. ``pkg.mod``), while :func:`__import__` returns the
Guido van Rossum09613542009-03-30 20:34:57 +000087 top-level package or module (e.g. ``pkg``).
88
Brett Cannonee78a2b2012-05-12 17:43:17 -040089.. function:: find_loader(name, path=None)
90
91 Find the loader for a module, optionally within the specified *path*. If the
92 module is in :attr:`sys.modules`, then ``sys.modules[name].__loader__`` is
93 returned (unless the loader would be ``None``, in which case
94 :exc:`ValueError` is raised). Otherwise a search using :attr:`sys.meta_path`
95 is done. ``None`` is returned if no loader is found.
96
Brett Cannon56b4ca72012-11-17 09:30:55 -050097 A dotted name does not have its parent's implicitly imported as that requires
98 loading them and that may not be desired. To properly import a submodule you
99 will need to import all parent packages of the submodule and use the correct
100 argument to *path*.
Brett Cannonee78a2b2012-05-12 17:43:17 -0400101
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100102.. function:: invalidate_caches()
103
Brett Cannonf4dc9202012-08-10 12:21:12 -0400104 Invalidate the internal caches of finders stored at
105 :data:`sys.meta_path`. If a finder implements ``invalidate_caches()`` then it
106 will be called to perform the invalidation. This function may be needed if
107 some modules are installed while your program is running and you expect the
108 program to notice the changes.
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100109
110 .. versionadded:: 3.3
111
Brett Cannon78246b62009-01-25 04:56:30 +0000112
Brett Cannon2a922ed2009-03-09 03:35:50 +0000113:mod:`importlib.abc` -- Abstract base classes related to import
114---------------------------------------------------------------
115
116.. module:: importlib.abc
117 :synopsis: Abstract base classes related to import
118
119The :mod:`importlib.abc` module contains all of the core abstract base classes
120used by :keyword:`import`. Some subclasses of the core abstract base classes
121are also provided to help in implementing the core ABCs.
122
Andrew Svetlova8656542012-08-13 22:19:01 +0300123ABC hierarchy::
124
125 object
Brett Cannon1b799182012-08-17 14:08:24 -0400126 +-- Finder (deprecated)
Andrew Svetlova8656542012-08-13 22:19:01 +0300127 | +-- MetaPathFinder
128 | +-- PathEntryFinder
129 +-- Loader
130 +-- ResourceLoader --------+
131 +-- InspectLoader |
132 +-- ExecutionLoader --+
133 +-- FileLoader
134 +-- SourceLoader
Andrew Svetlova8656542012-08-13 22:19:01 +0300135
Brett Cannon2a922ed2009-03-09 03:35:50 +0000136
137.. class:: Finder
138
Brett Cannon1b799182012-08-17 14:08:24 -0400139 An abstract base class representing a :term:`finder`.
140
141 .. deprecated:: 3.3
142 Use :class:`MetaPathFinder` or :class:`PathEntryFinder` instead.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000143
Brett Cannonf4dc9202012-08-10 12:21:12 -0400144 .. method:: find_module(fullname, path=None)
Brett Cannonb46a1792012-02-27 18:15:42 -0500145
Brett Cannonf4dc9202012-08-10 12:21:12 -0400146 An abstact method for finding a :term:`loader` for the specified
147 module. Originally specified in :pep:`302`, this method was meant
148 for use in :data:`sys.meta_path` and in the path-based import subsystem.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000149
150
Brett Cannon077ef452012-08-02 17:50:06 -0400151.. class:: MetaPathFinder
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000152
Brett Cannonf4dc9202012-08-10 12:21:12 -0400153 An abstract base class representing a :term:`meta path finder`. For
154 compatibility, this is a subclass of :class:`Finder`.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000155
156 .. versionadded:: 3.3
157
158 .. method:: find_module(fullname, path)
159
160 An abstract method for finding a :term:`loader` for the specified
161 module. If this is a top-level import, *path* will be ``None``.
Ezio Melotti1f67e802012-10-21 07:24:13 +0300162 Otherwise, this is a search for a subpackage or module and *path*
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000163 will be the value of :attr:`__path__` from the parent
164 package. If a loader cannot be found, ``None`` is returned.
165
Brett Cannonf4dc9202012-08-10 12:21:12 -0400166 .. method:: invalidate_caches()
167
168 An optional method which, when called, should invalidate any internal
Brett Cannona6e85812012-08-11 19:41:27 -0400169 cache used by the finder. Used by :func:`importlib.invalidate_caches`
170 when invalidating the caches of all finders on :data:`sys.meta_path`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400171
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000172
Brett Cannon077ef452012-08-02 17:50:06 -0400173.. class:: PathEntryFinder
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000174
Brett Cannonf4dc9202012-08-10 12:21:12 -0400175 An abstract base class representing a :term:`path entry finder`. Though
176 it bears some similarities to :class:`MetaPathFinder`, ``PathEntryFinder``
177 is meant for use only within the path-based import subsystem provided
178 by :class:`PathFinder`. This ABC is a subclass of :class:`Finder` for
179 compatibility.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000180
181 .. versionadded:: 3.3
182
Brett Cannon773468f2012-08-02 17:35:34 -0400183 .. method:: find_loader(fullname):
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000184
185 An abstract method for finding a :term:`loader` for the specified
Brett Cannonf4dc9202012-08-10 12:21:12 -0400186 module. Returns a 2-tuple of ``(loader, portion)`` where ``portion``
187 is a sequence of file system locations contributing to part of a namespace
188 package. The loader may be ``None`` while specifying ``portion`` to
189 signify the contribution of the file system locations to a namespace
190 package. An empty list can be used for ``portion`` to signify the loader
191 is not part of a package. If ``loader`` is ``None`` and ``portion`` is
192 the empty list then no loader or location for a namespace package were
193 found (i.e. failure to find anything for the module).
194
195 .. method:: find_module(fullname):
196
197 A concrete implementation of :meth:`Finder.find_module` which is
198 equivalent to ``self.find_loader(fullname)[0]``.
199
200 .. method:: invalidate_caches()
201
202 An optional method which, when called, should invalidate any internal
Brett Cannona6e85812012-08-11 19:41:27 -0400203 cache used by the finder. Used by :meth:`PathFinder.invalidate_caches`
Brett Cannonf4dc9202012-08-10 12:21:12 -0400204 when invalidating the caches of all cached finders.
Brett Cannonb46a1792012-02-27 18:15:42 -0500205
Brett Cannon2a922ed2009-03-09 03:35:50 +0000206
207.. class:: Loader
208
209 An abstract base class for a :term:`loader`.
Guido van Rossum09613542009-03-30 20:34:57 +0000210 See :pep:`302` for the exact definition for a loader.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000211
Brett Cannon9c751b72009-03-09 16:28:16 +0000212 .. method:: load_module(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000213
214 An abstract method for loading a module. If the module cannot be
215 loaded, :exc:`ImportError` is raised, otherwise the loaded module is
216 returned.
217
Guido van Rossum09613542009-03-30 20:34:57 +0000218 If the requested module already exists in :data:`sys.modules`, that
Brett Cannon2a922ed2009-03-09 03:35:50 +0000219 module should be used and reloaded.
Guido van Rossum09613542009-03-30 20:34:57 +0000220 Otherwise the loader should create a new module and insert it into
221 :data:`sys.modules` before any loading begins, to prevent recursion
222 from the import. If the loader inserted a module and the load fails, it
Brett Cannon2a922ed2009-03-09 03:35:50 +0000223 must be removed by the loader from :data:`sys.modules`; modules already
224 in :data:`sys.modules` before the loader began execution should be left
225 alone. The :func:`importlib.util.module_for_loader` decorator handles
226 all of these details.
227
Guido van Rossum09613542009-03-30 20:34:57 +0000228 The loader should set several attributes on the module.
229 (Note that some of these attributes can change when a module is
230 reloaded.)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000231
232 - :attr:`__name__`
233 The name of the module.
234
235 - :attr:`__file__`
236 The path to where the module data is stored (not set for built-in
237 modules).
238
239 - :attr:`__path__`
Guido van Rossum09613542009-03-30 20:34:57 +0000240 A list of strings specifying the search path within a
Brett Cannon2a922ed2009-03-09 03:35:50 +0000241 package. This attribute is not set on modules.
242
243 - :attr:`__package__`
244 The parent package for the module/package. If the module is
245 top-level then it has a value of the empty string. The
246 :func:`importlib.util.set_package` decorator can handle the details
247 for :attr:`__package__`.
248
249 - :attr:`__loader__`
Guido van Rossum09613542009-03-30 20:34:57 +0000250 The loader used to load the module.
251 (This is not set by the built-in import machinery,
252 but it should be set whenever a :term:`loader` is used.)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000253
Barry Warsawd7d21942012-07-29 16:36:17 -0400254 .. method:: module_repr(module)
255
256 An abstract method which when implemented calculates and returns the
257 given module's repr, as a string.
258
259 .. versionadded: 3.3
260
Brett Cannon2a922ed2009-03-09 03:35:50 +0000261
262.. class:: ResourceLoader
263
264 An abstract base class for a :term:`loader` which implements the optional
265 :pep:`302` protocol for loading arbitrary resources from the storage
266 back-end.
267
Brett Cannon9c751b72009-03-09 16:28:16 +0000268 .. method:: get_data(path)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000269
270 An abstract method to return the bytes for the data located at *path*.
Guido van Rossum09613542009-03-30 20:34:57 +0000271 Loaders that have a file-like storage back-end
Brett Cannon16248a42009-04-01 20:47:14 +0000272 that allows storing arbitrary data
Guido van Rossum09613542009-03-30 20:34:57 +0000273 can implement this abstract method to give direct access
Brett Cannon2a922ed2009-03-09 03:35:50 +0000274 to the data stored. :exc:`IOError` is to be raised if the *path* cannot
275 be found. The *path* is expected to be constructed using a module's
Brett Cannon16248a42009-04-01 20:47:14 +0000276 :attr:`__file__` attribute or an item from a package's :attr:`__path__`.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000277
278
279.. class:: InspectLoader
280
281 An abstract base class for a :term:`loader` which implements the optional
Guido van Rossum09613542009-03-30 20:34:57 +0000282 :pep:`302` protocol for loaders that inspect modules.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000283
Brett Cannona113ac52009-03-15 01:41:33 +0000284 .. method:: get_code(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000285
Brett Cannona113ac52009-03-15 01:41:33 +0000286 An abstract method to return the :class:`code` object for a module.
Georg Brandl375aec22011-01-15 17:03:02 +0000287 ``None`` is returned if the module does not have a code object
Brett Cannona113ac52009-03-15 01:41:33 +0000288 (e.g. built-in module). :exc:`ImportError` is raised if loader cannot
289 find the requested module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000290
R David Murray1b00f252012-08-15 10:43:58 -0400291 .. index::
292 single: universal newlines; importlib.abc.InspectLoader.get_source method
293
Brett Cannon9c751b72009-03-09 16:28:16 +0000294 .. method:: get_source(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000295
296 An abstract method to return the source of a module. It is returned as
R David Murray1b00f252012-08-15 10:43:58 -0400297 a text string using :term:`universal newlines`, translating all
R David Murrayee0a9452012-08-15 11:05:36 -0400298 recognized line separators into ``'\n'`` characters. Returns ``None``
299 if no source is available (e.g. a built-in module). Raises
300 :exc:`ImportError` if the loader cannot find the module specified.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000301
Brett Cannona113ac52009-03-15 01:41:33 +0000302 .. method:: is_package(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000303
Brett Cannona113ac52009-03-15 01:41:33 +0000304 An abstract method to return a true value if the module is a package, a
305 false value otherwise. :exc:`ImportError` is raised if the
306 :term:`loader` cannot find the module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000307
308
Brett Cannon69194272009-07-20 04:23:48 +0000309.. class:: ExecutionLoader
310
311 An abstract base class which inherits from :class:`InspectLoader` that,
Brett Cannon23460292009-07-20 22:59:00 +0000312 when implemented, helps a module to be executed as a script. The ABC
Brett Cannon69194272009-07-20 04:23:48 +0000313 represents an optional :pep:`302` protocol.
314
315 .. method:: get_filename(fullname)
316
Brett Cannonf23e3742010-06-27 23:57:46 +0000317 An abstract method that is to return the value of :attr:`__file__` for
Brett Cannon69194272009-07-20 04:23:48 +0000318 the specified module. If no path is available, :exc:`ImportError` is
319 raised.
320
Brett Cannonf23e3742010-06-27 23:57:46 +0000321 If source code is available, then the method should return the path to
322 the source file, regardless of whether a bytecode was used to load the
323 module.
324
325
Brett Cannon938d44d2012-04-22 19:58:33 -0400326.. class:: FileLoader(fullname, path)
327
328 An abstract base class which inherits from :class:`ResourceLoader` and
329 :class:`ExecutionLoader`, providing concreate implementations of
330 :meth:`ResourceLoader.get_data` and :meth:`ExecutionLoader.get_filename`.
331
332 The *fullname* argument is a fully resolved name of the module the loader is
333 to handle. The *path* argument is the path to the file for the module.
334
335 .. versionadded:: 3.3
336
337 .. attribute:: name
338
339 The name of the module the loader can handle.
340
341 .. attribute:: path
342
343 Path to the file of the module.
344
Barry Warsawd7d21942012-07-29 16:36:17 -0400345 .. method:: load_module(fullname)
Brett Cannonc0499522012-05-11 14:48:41 -0400346
Barry Warsawd7d21942012-07-29 16:36:17 -0400347 Calls super's ``load_module()``.
Brett Cannonc0499522012-05-11 14:48:41 -0400348
Brett Cannon938d44d2012-04-22 19:58:33 -0400349 .. method:: get_filename(fullname)
350
Barry Warsawd7d21942012-07-29 16:36:17 -0400351 Returns :attr:`path`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400352
353 .. method:: get_data(path)
354
355 Returns the open, binary file for *path*.
356
357
Brett Cannonf23e3742010-06-27 23:57:46 +0000358.. class:: SourceLoader
359
360 An abstract base class for implementing source (and optionally bytecode)
361 file loading. The class inherits from both :class:`ResourceLoader` and
362 :class:`ExecutionLoader`, requiring the implementation of:
363
364 * :meth:`ResourceLoader.get_data`
365 * :meth:`ExecutionLoader.get_filename`
Brett Cannon6dfbff32010-07-21 09:48:31 +0000366 Should only return the path to the source file; sourceless
Brett Cannon5650e4f2012-11-18 10:03:31 -0500367 loading is not supported (see :class:`SourcelessLoader` if that
368 functionality is required)
Brett Cannonf23e3742010-06-27 23:57:46 +0000369
370 The abstract methods defined by this class are to add optional bytecode
Brett Cannon5650e4f2012-11-18 10:03:31 -0500371 file support. Not implementing these optional methods (or causing them to
372 raise :exc:`NotImplementedError`) causes the loader to
Brett Cannonf23e3742010-06-27 23:57:46 +0000373 only work with source code. Implementing the methods allows the loader to
374 work with source *and* bytecode files; it does not allow for *sourceless*
375 loading where only bytecode is provided. Bytecode files are an
376 optimization to speed up loading by removing the parsing step of Python's
377 compiler, and so no bytecode-specific API is exposed.
378
Brett Cannon773468f2012-08-02 17:35:34 -0400379 .. method:: path_stats(path)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100380
381 Optional abstract method which returns a :class:`dict` containing
382 metadata about the specifed path. Supported dictionary keys are:
383
384 - ``'mtime'`` (mandatory): an integer or floating-point number
385 representing the modification time of the source code;
386 - ``'size'`` (optional): the size in bytes of the source code.
387
388 Any other keys in the dictionary are ignored, to allow for future
389 extensions.
390
391 .. versionadded:: 3.3
392
Brett Cannon773468f2012-08-02 17:35:34 -0400393 .. method:: path_mtime(path)
Brett Cannonf23e3742010-06-27 23:57:46 +0000394
395 Optional abstract method which returns the modification time for the
396 specified path.
397
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100398 .. deprecated:: 3.3
399 This method is deprecated in favour of :meth:`path_stats`. You don't
400 have to implement it, but it is still available for compatibility
401 purposes.
402
Brett Cannon773468f2012-08-02 17:35:34 -0400403 .. method:: set_data(path, data)
Brett Cannonf23e3742010-06-27 23:57:46 +0000404
405 Optional abstract method which writes the specified bytes to a file
Brett Cannon61b14252010-07-03 21:48:25 +0000406 path. Any intermediate directories which do not exist are to be created
407 automatically.
408
409 When writing to the path fails because the path is read-only
410 (:attr:`errno.EACCES`), do not propagate the exception.
Brett Cannonf23e3742010-06-27 23:57:46 +0000411
Eric Snowa6cfb282012-12-04 23:43:43 -0800412 .. method:: source_to_code(data, path)
Brett Cannon5650e4f2012-11-18 10:03:31 -0500413
414 Create a code object from Python source.
415
416 The *data* argument can be whatever the :func:`compile` function
417 supports (i.e. string or bytes). The *path* argument should be
418 the "path" to where the source code originated from, which can be an
419 abstract concept (e.g. location in a zip file).
420
421 .. versionadded:: 3.4
422
Brett Cannon773468f2012-08-02 17:35:34 -0400423 .. method:: get_code(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000424
425 Concrete implementation of :meth:`InspectLoader.get_code`.
426
Brett Cannon773468f2012-08-02 17:35:34 -0400427 .. method:: load_module(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000428
429 Concrete implementation of :meth:`Loader.load_module`.
430
Brett Cannon773468f2012-08-02 17:35:34 -0400431 .. method:: get_source(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000432
433 Concrete implementation of :meth:`InspectLoader.get_source`.
434
Brett Cannon773468f2012-08-02 17:35:34 -0400435 .. method:: is_package(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000436
437 Concrete implementation of :meth:`InspectLoader.is_package`. A module
Brett Cannonea0b8232012-06-15 20:00:53 -0400438 is determined to be a package if its file path (as provided by
439 :meth:`ExecutionLoader.get_filename`) is a file named
440 ``__init__`` when the file extension is removed **and** the module name
441 itself does not end in ``__init__``.
Brett Cannonf23e3742010-06-27 23:57:46 +0000442
Brett Cannon69194272009-07-20 04:23:48 +0000443
Brett Cannon78246b62009-01-25 04:56:30 +0000444:mod:`importlib.machinery` -- Importers and path hooks
445------------------------------------------------------
446
447.. module:: importlib.machinery
448 :synopsis: Importers and path hooks
449
450This module contains the various objects that help :keyword:`import`
451find and load modules.
452
Brett Cannoncb66eb02012-05-11 12:58:42 -0400453.. attribute:: SOURCE_SUFFIXES
454
455 A list of strings representing the recognized file suffixes for source
456 modules.
457
458 .. versionadded:: 3.3
459
460.. attribute:: DEBUG_BYTECODE_SUFFIXES
461
462 A list of strings representing the file suffixes for non-optimized bytecode
463 modules.
464
465 .. versionadded:: 3.3
466
467.. attribute:: OPTIMIZED_BYTECODE_SUFFIXES
468
469 A list of strings representing the file suffixes for optimized bytecode
470 modules.
471
472 .. versionadded:: 3.3
473
474.. attribute:: BYTECODE_SUFFIXES
475
476 A list of strings representing the recognized file suffixes for bytecode
477 modules. Set to either :attr:`DEBUG_BYTECODE_SUFFIXES` or
478 :attr:`OPTIMIZED_BYTECODE_SUFFIXES` based on whether ``__debug__`` is true.
479
480 .. versionadded:: 3.3
481
482.. attribute:: EXTENSION_SUFFIXES
483
Nick Coghlan76e07702012-07-18 23:14:57 +1000484 A list of strings representing the recognized file suffixes for
Brett Cannoncb66eb02012-05-11 12:58:42 -0400485 extension modules.
486
487 .. versionadded:: 3.3
488
Nick Coghlanc5afd422012-07-18 23:59:08 +1000489.. function:: all_suffixes()
Nick Coghlan76e07702012-07-18 23:14:57 +1000490
491 Returns a combined list of strings representing all file suffixes for
Nick Coghlanc5afd422012-07-18 23:59:08 +1000492 modules recognized by the standard import machinery. This is a
Nick Coghlan76e07702012-07-18 23:14:57 +1000493 helper for code which simply needs to know if a filesystem path
Nick Coghlanc5afd422012-07-18 23:59:08 +1000494 potentially refers to a module without needing any details on the kind
495 of module (for example, :func:`inspect.getmodulename`)
Nick Coghlan76e07702012-07-18 23:14:57 +1000496
497 .. versionadded:: 3.3
498
499
Brett Cannon78246b62009-01-25 04:56:30 +0000500.. class:: BuiltinImporter
501
Brett Cannon2a922ed2009-03-09 03:35:50 +0000502 An :term:`importer` for built-in modules. All known built-in modules are
503 listed in :data:`sys.builtin_module_names`. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000504 :class:`importlib.abc.MetaPathFinder` and
505 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000506
507 Only class methods are defined by this class to alleviate the need for
508 instantiation.
509
Brett Cannon78246b62009-01-25 04:56:30 +0000510
511.. class:: FrozenImporter
512
Brett Cannon2a922ed2009-03-09 03:35:50 +0000513 An :term:`importer` for frozen modules. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000514 :class:`importlib.abc.MetaPathFinder` and
515 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000516
517 Only class methods are defined by this class to alleviate the need for
518 instantiation.
519
Brett Cannondebb98d2009-02-16 04:18:01 +0000520
Nick Coghlanff794862012-08-02 21:45:24 +1000521.. class:: WindowsRegistryFinder
522
523 :term:`Finder` for modules declared in the Windows registry. This class
Nick Coghlan49417742012-08-02 23:03:58 +1000524 implements the :class:`importlib.abc.Finder` ABC.
Nick Coghlanff794862012-08-02 21:45:24 +1000525
526 Only class methods are defined by this class to alleviate the need for
527 instantiation.
528
529 .. versionadded:: 3.3
530
531
Brett Cannondebb98d2009-02-16 04:18:01 +0000532.. class:: PathFinder
533
Brett Cannon1b799182012-08-17 14:08:24 -0400534 A :term:`Finder` for :data:`sys.path` and package ``__path__`` attributes.
535 This class implements the :class:`importlib.abc.MetaPathFinder` ABC.
Brett Cannondebb98d2009-02-16 04:18:01 +0000536
Brett Cannon1b799182012-08-17 14:08:24 -0400537 Only class methods are defined by this class to alleviate the need for
538 instantiation.
Brett Cannondebb98d2009-02-16 04:18:01 +0000539
Brett Cannon1b799182012-08-17 14:08:24 -0400540 .. classmethod:: find_module(fullname, path=None)
Brett Cannondebb98d2009-02-16 04:18:01 +0000541
Brett Cannon1b799182012-08-17 14:08:24 -0400542 Class method that attempts to find a :term:`loader` for the module
543 specified by *fullname* on :data:`sys.path` or, if defined, on
544 *path*. For each path entry that is searched,
545 :data:`sys.path_importer_cache` is checked. If a non-false object is
546 found then it is used as the :term:`finder` to look for the module
547 being searched for. If no entry is found in
548 :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
549 searched for a finder for the path entry and, if found, is stored in
550 :data:`sys.path_importer_cache` along with being queried about the
551 module. If no finder is ever found then ``None`` is both stored in
552 the cache and returned.
Brett Cannond2e7b332009-02-17 02:45:03 +0000553
Brett Cannonf4dc9202012-08-10 12:21:12 -0400554 .. classmethod:: invalidate_caches()
555
Brett Cannon1b799182012-08-17 14:08:24 -0400556 Calls :meth:`importlib.abc.PathEntryFinder.invalidate_caches` on all
557 finders stored in :attr:`sys.path_importer_cache`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400558
Brett Cannond2e7b332009-02-17 02:45:03 +0000559
Brett Cannon938d44d2012-04-22 19:58:33 -0400560.. class:: FileFinder(path, \*loader_details)
561
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000562 A concrete implementation of :class:`importlib.abc.PathEntryFinder` which
563 caches results from the file system.
Brett Cannon938d44d2012-04-22 19:58:33 -0400564
565 The *path* argument is the directory for which the finder is in charge of
566 searching.
567
Brett Cannonac9f2f32012-08-10 13:47:54 -0400568 The *loader_details* argument is a variable number of 2-item tuples each
569 containing a loader and a sequence of file suffixes the loader recognizes.
Brett Cannon938d44d2012-04-22 19:58:33 -0400570
571 The finder will cache the directory contents as necessary, making stat calls
572 for each module search to verify the cache is not outdated. Because cache
573 staleness relies upon the granularity of the operating system's state
574 information of the file system, there is a potential race condition of
575 searching for a module, creating a new file, and then searching for the
576 module the new file represents. If the operations happen fast enough to fit
577 within the granularity of stat calls, then the module search will fail. To
578 prevent this from happening, when you create a module dynamically, make sure
579 to call :func:`importlib.invalidate_caches`.
580
581 .. versionadded:: 3.3
582
583 .. attribute:: path
584
585 The path the finder will search in.
586
587 .. method:: find_module(fullname)
588
589 Attempt to find the loader to handle *fullname* within :attr:`path`.
590
591 .. method:: invalidate_caches()
592
593 Clear out the internal cache.
594
595 .. classmethod:: path_hook(\*loader_details)
596
597 A class method which returns a closure for use on :attr:`sys.path_hooks`.
598 An instance of :class:`FileFinder` is returned by the closure using the
599 path argument given to the closure directly and *loader_details*
600 indirectly.
601
602 If the argument to the closure is not an existing directory,
603 :exc:`ImportError` is raised.
604
605
606.. class:: SourceFileLoader(fullname, path)
607
608 A concrete implementation of :class:`importlib.abc.SourceLoader` by
609 subclassing :class:`importlib.abc.FileLoader` and providing some concrete
610 implementations of other methods.
611
612 .. versionadded:: 3.3
613
614 .. attribute:: name
615
616 The name of the module that this loader will handle.
617
618 .. attribute:: path
619
620 The path to the source file.
621
622 .. method:: is_package(fullname)
623
624 Return true if :attr:`path` appears to be for a package.
625
626 .. method:: path_stats(path)
627
628 Concrete implementation of :meth:`importlib.abc.SourceLoader.path_stats`.
629
630 .. method:: set_data(path, data)
631
632 Concrete implementation of :meth:`importlib.abc.SourceLoader.set_data`.
633
Brett Cannon938d44d2012-04-22 19:58:33 -0400634
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200635.. class:: SourcelessFileLoader(fullname, path)
Brett Cannon938d44d2012-04-22 19:58:33 -0400636
637 A concrete implementation of :class:`importlib.abc.FileLoader` which can
638 import bytecode files (i.e. no source code files exist).
639
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200640 Please note that direct use of bytecode files (and thus not source code
641 files) inhibits your modules from being usable by all Python
642 implementations or new versions of Python which change the bytecode
643 format.
Brett Cannon938d44d2012-04-22 19:58:33 -0400644
645 .. versionadded:: 3.3
646
647 .. attribute:: name
648
649 The name of the module the loader will handle.
650
651 .. attribute:: path
652
653 The path to the bytecode file.
654
655 .. method:: is_package(fullname)
656
657 Determines if the module is a package based on :attr:`path`.
658
659 .. method:: get_code(fullname)
660
661 Returns the code object for :attr:`name` created from :attr:`path`.
662
663 .. method:: get_source(fullname)
664
665 Returns ``None`` as bytecode files have no source when this loader is
666 used.
667
Brett Cannon938d44d2012-04-22 19:58:33 -0400668
669.. class:: ExtensionFileLoader(fullname, path)
670
671 A concrete implementation of :class:`importlib.abc.InspectLoader` for
672 extension modules.
673
674 The *fullname* argument specifies the name of the module the loader is to
675 support. The *path* argument is the path to the extension module's file.
676
677 .. versionadded:: 3.3
678
679 .. attribute:: name
680
681 Name of the module the loader supports.
682
683 .. attribute:: path
684
685 Path to the extension module.
686
Barry Warsawd7d21942012-07-29 16:36:17 -0400687 .. method:: load_module(fullname)
Brett Cannon938d44d2012-04-22 19:58:33 -0400688
Brett Cannonc0499522012-05-11 14:48:41 -0400689 Loads the extension module if and only if *fullname* is the same as
690 :attr:`name` or is ``None``.
Brett Cannon938d44d2012-04-22 19:58:33 -0400691
692 .. method:: is_package(fullname)
693
Brett Cannonac9f2f32012-08-10 13:47:54 -0400694 Returns ``True`` if the file path points to a package's ``__init__``
695 module based on :attr:`EXTENSION_SUFFIXES`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400696
697 .. method:: get_code(fullname)
698
699 Returns ``None`` as extension modules lack a code object.
700
701 .. method:: get_source(fullname)
702
703 Returns ``None`` as extension modules do not have source code.
704
705
Brett Cannond2e7b332009-02-17 02:45:03 +0000706:mod:`importlib.util` -- Utility code for importers
707---------------------------------------------------
708
709.. module:: importlib.util
Brett Cannon75321e82012-03-02 11:58:25 -0500710 :synopsis: Utility code for importers
Brett Cannond2e7b332009-02-17 02:45:03 +0000711
712This module contains the various objects that help in the construction of
713an :term:`importer`.
714
Brett Cannond200bf52012-05-13 13:45:09 -0400715.. function:: resolve_name(name, package)
716
717 Resolve a relative module name to an absolute one.
718
719 If **name** has no leading dots, then **name** is simply returned. This
720 allows for usage such as
721 ``importlib.util.resolve_name('sys', __package__)`` without doing a
722 check to see if the **package** argument is needed.
723
724 :exc:`ValueError` is raised if **name** is a relative module name but
725 package is a false value (e.g. ``None`` or the empty string).
726 :exc:`ValueError` is also raised a relative name would escape its containing
727 package (e.g. requesting ``..bacon`` from within the ``spam`` package).
728
729 .. versionadded:: 3.3
730
Georg Brandl8a1caa22010-07-29 16:01:11 +0000731.. decorator:: module_for_loader
Brett Cannond2e7b332009-02-17 02:45:03 +0000732
Guido van Rossum09613542009-03-30 20:34:57 +0000733 A :term:`decorator` for a :term:`loader` method,
734 to handle selecting the proper
Brett Cannond2e7b332009-02-17 02:45:03 +0000735 module object to load with. The decorated method is expected to have a call
Brett Cannon2a922ed2009-03-09 03:35:50 +0000736 signature taking two positional arguments
737 (e.g. ``load_module(self, module)``) for which the second argument
Guido van Rossum09613542009-03-30 20:34:57 +0000738 will be the module **object** to be used by the loader.
Brett Cannonefad00d2012-04-27 17:27:14 -0400739 Note that the decorator will not work on static methods because of the
740 assumption of two arguments.
Brett Cannond2e7b332009-02-17 02:45:03 +0000741
Guido van Rossum09613542009-03-30 20:34:57 +0000742 The decorated method will take in the **name** of the module to be loaded
743 as expected for a :term:`loader`. If the module is not found in
Brett Cannon57b46f52009-03-02 14:38:26 +0000744 :data:`sys.modules` then a new one is constructed with its
Brett Cannonefad00d2012-04-27 17:27:14 -0400745 :attr:`__name__` attribute set to **name**, :attr:`__loader__` set to
746 **self**, and :attr:`__package__` set if
747 :meth:`importlib.abc.InspectLoader.is_package` is defined for **self** and
748 does not raise :exc:`ImportError` for **name**. If a new module is not
749 needed then the module found in :data:`sys.modules` will be passed into the
750 method.
751
752 If an exception is raised by the decorated method and a module was added to
Brett Cannond2e7b332009-02-17 02:45:03 +0000753 :data:`sys.modules` it will be removed to prevent a partially initialized
Brett Cannon57b46f52009-03-02 14:38:26 +0000754 module from being in left in :data:`sys.modules`. If the module was already
755 in :data:`sys.modules` then it is left alone.
Brett Cannond2e7b332009-02-17 02:45:03 +0000756
Guido van Rossum09613542009-03-30 20:34:57 +0000757 Use of this decorator handles all the details of which module object a
Brett Cannonefad00d2012-04-27 17:27:14 -0400758 loader should initialize as specified by :pep:`302` as best as possible.
759
760 .. versionchanged:: 3.3
Georg Brandl61063cc2012-06-24 22:48:30 +0200761 :attr:`__loader__` and :attr:`__package__` are automatically set
762 (when possible).
Brett Cannon57b46f52009-03-02 14:38:26 +0000763
Georg Brandl8a1caa22010-07-29 16:01:11 +0000764.. decorator:: set_loader
Brett Cannon2cf03a82009-03-10 05:17:37 +0000765
Guido van Rossum09613542009-03-30 20:34:57 +0000766 A :term:`decorator` for a :term:`loader` method,
767 to set the :attr:`__loader__`
Brett Cannon2cf03a82009-03-10 05:17:37 +0000768 attribute on loaded modules. If the attribute is already set the decorator
769 does nothing. It is assumed that the first positional argument to the
Brett Cannon75321e82012-03-02 11:58:25 -0500770 wrapped method (i.e. ``self``) is what :attr:`__loader__` should be set to.
Brett Cannon2cf03a82009-03-10 05:17:37 +0000771
Brett Cannonefad00d2012-04-27 17:27:14 -0400772 .. note::
773
774 It is recommended that :func:`module_for_loader` be used over this
775 decorator as it subsumes this functionality.
776
777
Georg Brandl8a1caa22010-07-29 16:01:11 +0000778.. decorator:: set_package
Brett Cannon57b46f52009-03-02 14:38:26 +0000779
780 A :term:`decorator` for a :term:`loader` to set the :attr:`__package__`
781 attribute on the module returned by the loader. If :attr:`__package__` is
Georg Brandl375aec22011-01-15 17:03:02 +0000782 set and has a value other than ``None`` it will not be changed.
Brett Cannon57b46f52009-03-02 14:38:26 +0000783 Note that the module returned by the loader is what has the attribute
784 set on and not the module found in :data:`sys.modules`.
Guido van Rossum09613542009-03-30 20:34:57 +0000785
Brett Cannon16248a42009-04-01 20:47:14 +0000786 Reliance on this decorator is discouraged when it is possible to set
Brett Cannon75321e82012-03-02 11:58:25 -0500787 :attr:`__package__` before importing. By
788 setting it beforehand the code for the module is executed with the
789 attribute set and thus can be used by global level code during
Brett Cannon16248a42009-04-01 20:47:14 +0000790 initialization.
791
Brett Cannonefad00d2012-04-27 17:27:14 -0400792 .. note::
793
794 It is recommended that :func:`module_for_loader` be used over this
795 decorator as it subsumes this functionality.