blob: 91328af701b1a0cf34ac11f2b189fa8dc38dcec7 [file] [log] [blame]
Brett Cannon07fbd782014-02-06 09:46:08 -05001:mod:`importlib` -- The implementation of :keyword:`import`
2===========================================================
Brett Cannonafccd632009-01-20 02:21:27 +00003
4.. module:: importlib
Brett Cannon07fbd782014-02-06 09:46:08 -05005 :synopsis: The implementation of the import machinery.
Brett Cannonafccd632009-01-20 02:21:27 +00006
7.. moduleauthor:: Brett Cannon <brett@python.org>
8.. sectionauthor:: Brett Cannon <brett@python.org>
9
10.. versionadded:: 3.1
11
12
13Introduction
14------------
15
Brett Cannon07fbd782014-02-06 09:46:08 -050016The purpose of the :mod:`importlib` package is two-fold. One is to provide the
Brett Cannonafccd632009-01-20 02:21:27 +000017implementation 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 Cannon07fbd782014-02-06 09:46:08 -050020interpreter. This also provides an 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 Cannonafccd632009-01-20 02:21:27 +000026
27.. seealso::
28
29 :ref:`import`
30 The language reference for the :keyword:`import` statement.
31
Georg Brandlb7354a62014-10-29 10:57:37 +010032 `Packages specification <http://legacy.python.org/doc/essays/packages.html>`__
Brett Cannonafccd632009-01-20 02:21:27 +000033 Original specification of packages. Some semantics have changed since
Georg Brandl375aec22011-01-15 17:03:02 +000034 the writing of this document (e.g. redirecting based on ``None``
Brett Cannonafccd632009-01-20 02:21:27 +000035 in :data:`sys.modules`).
36
37 The :func:`.__import__` function
Brett Cannon0e13c942010-06-29 18:26:11 +000038 The :keyword:`import` statement is syntactic sugar for this function.
Brett Cannonafccd632009-01-20 02:21:27 +000039
40 :pep:`235`
41 Import on Case-Insensitive Platforms
42
43 :pep:`263`
44 Defining Python Source Code Encodings
45
46 :pep:`302`
Brett Cannonf23e3742010-06-27 23:57:46 +000047 New Import Hooks
Brett Cannonafccd632009-01-20 02:21:27 +000048
49 :pep:`328`
50 Imports: Multi-Line and Absolute/Relative
51
52 :pep:`366`
53 Main module explicit relative imports
54
Brett Cannon07fbd782014-02-06 09:46:08 -050055 :pep:`451`
56 A ModuleSpec Type for the Import System
57
Brett Cannon8917d5e2010-01-13 19:21:00 +000058 :pep:`3120`
Brett Cannonafccd632009-01-20 02:21:27 +000059 Using UTF-8 as the Default Source Encoding
60
Brett Cannon30b7a902010-06-27 21:49:22 +000061 :pep:`3147`
62 PYC Repository Directories
63
Brett Cannonafccd632009-01-20 02:21:27 +000064
65Functions
66---------
67
Brett Cannoncb4996a2012-08-06 16:34:44 -040068.. function:: __import__(name, globals=None, locals=None, fromlist=(), level=0)
Brett Cannonafccd632009-01-20 02:21:27 +000069
Brett Cannonf23e3742010-06-27 23:57:46 +000070 An implementation of the built-in :func:`__import__` function.
Brett Cannonafccd632009-01-20 02:21:27 +000071
72.. function:: import_module(name, package=None)
73
Brett Cannon33418c82009-01-22 18:37:20 +000074 Import a module. The *name* argument specifies what module to
Brett Cannonafccd632009-01-20 02:21:27 +000075 import in absolute or relative terms
76 (e.g. either ``pkg.mod`` or ``..mod``). If the name is
Guido van Rossum09613542009-03-30 20:34:57 +000077 specified in relative terms, then the *package* argument must be set to
78 the name of the package which is to act as the anchor for resolving the
Brett Cannonafccd632009-01-20 02:21:27 +000079 package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
Brett Cannon2c318a12009-02-07 01:15:27 +000080 ``pkg.mod``).
Brett Cannon78246b62009-01-25 04:56:30 +000081
Brett Cannon2c318a12009-02-07 01:15:27 +000082 The :func:`import_module` function acts as a simplifying wrapper around
Brett Cannon9f4cb1c2009-04-01 23:26:47 +000083 :func:`importlib.__import__`. This means all semantics of the function are
84 derived from :func:`importlib.__import__`, including requiring the package
85 from which an import is occurring to have been previously imported
86 (i.e., *package* must already be imported). The most important difference
Brett Cannon98620d82013-12-13 13:57:41 -050087 is that :func:`import_module` returns the specified package or module
88 (e.g. ``pkg.mod``), while :func:`__import__` returns the
Guido van Rossum09613542009-03-30 20:34:57 +000089 top-level package or module (e.g. ``pkg``).
90
Brett Cannon98620d82013-12-13 13:57:41 -050091 .. versionchanged:: 3.3
92 Parent packages are automatically imported.
93
Brett Cannonee78a2b2012-05-12 17:43:17 -040094.. function:: find_loader(name, path=None)
95
96 Find the loader for a module, optionally within the specified *path*. If the
97 module is in :attr:`sys.modules`, then ``sys.modules[name].__loader__`` is
Brett Cannon32799232013-03-13 11:09:08 -070098 returned (unless the loader would be ``None`` or is not set, in which case
Brett Cannonee78a2b2012-05-12 17:43:17 -040099 :exc:`ValueError` is raised). Otherwise a search using :attr:`sys.meta_path`
100 is done. ``None`` is returned if no loader is found.
101
Brett Cannon56b4ca72012-11-17 09:30:55 -0500102 A dotted name does not have its parent's implicitly imported as that requires
103 loading them and that may not be desired. To properly import a submodule you
104 will need to import all parent packages of the submodule and use the correct
105 argument to *path*.
Brett Cannonee78a2b2012-05-12 17:43:17 -0400106
Brett Cannon32799232013-03-13 11:09:08 -0700107 .. versionadded:: 3.3
108
109 .. versionchanged:: 3.4
110 If ``__loader__`` is not set, raise :exc:`ValueError`, just like when the
111 attribute is set to ``None``.
112
Eric Snowca2d8542013-12-16 23:06:52 -0700113 .. deprecated:: 3.4
Eric Snow6029e082014-01-25 15:32:46 -0700114 Use :func:`importlib.util.find_spec` instead.
Eric Snowca2d8542013-12-16 23:06:52 -0700115
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100116.. function:: invalidate_caches()
117
Brett Cannonf4dc9202012-08-10 12:21:12 -0400118 Invalidate the internal caches of finders stored at
119 :data:`sys.meta_path`. If a finder implements ``invalidate_caches()`` then it
Brett Cannon4067aa22013-04-27 23:20:32 -0400120 will be called to perform the invalidation. This function should be called
121 if any modules are created/installed while your program is running to
122 guarantee all finders will notice the new module's existence.
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100123
124 .. versionadded:: 3.3
125
Brett Cannon3fe35e62013-06-14 15:04:26 -0400126.. function:: reload(module)
127
128 Reload a previously imported *module*. The argument must be a module object,
129 so it must have been successfully imported before. This is useful if you
130 have edited the module source file using an external editor and want to try
131 out the new version without leaving the Python interpreter. The return value
Brett Cannon8ad37862013-10-25 13:52:46 -0400132 is the module object (which can be different if re-importing causes a
133 different object to be placed in :data:`sys.modules`).
Brett Cannon3fe35e62013-06-14 15:04:26 -0400134
Brett Cannon8ad37862013-10-25 13:52:46 -0400135 When :func:`reload` is executed:
Brett Cannon3fe35e62013-06-14 15:04:26 -0400136
Larry Hastings3732ed22014-03-15 21:13:56 -0700137 * Python module's code is recompiled and the module-level code re-executed,
Brett Cannon3fe35e62013-06-14 15:04:26 -0400138 defining a new set of objects which are bound to names in the module's
139 dictionary by reusing the :term:`loader` which originally loaded the
140 module. The ``init`` function of extension modules is not called a second
141 time.
142
143 * As with all other objects in Python the old objects are only reclaimed
144 after their reference counts drop to zero.
145
146 * The names in the module namespace are updated to point to any new or
147 changed objects.
148
149 * Other references to the old objects (such as names external to the module) are
150 not rebound to refer to the new objects and must be updated in each namespace
151 where they occur if that is desired.
152
153 There are a number of other caveats:
154
155 If a module is syntactically correct but its initialization fails, the first
156 :keyword:`import` statement for it does not bind its name locally, but does
157 store a (partially initialized) module object in ``sys.modules``. To reload
158 the module you must first :keyword:`import` it again (this will bind the name
159 to the partially initialized module object) before you can :func:`reload` it.
160
161 When a module is reloaded, its dictionary (containing the module's global
162 variables) is retained. Redefinitions of names will override the old
163 definitions, so this is generally not a problem. If the new version of a
164 module does not define a name that was defined by the old version, the old
165 definition remains. This feature can be used to the module's advantage if it
166 maintains a global table or cache of objects --- with a :keyword:`try`
167 statement it can test for the table's presence and skip its initialization if
168 desired::
169
170 try:
171 cache
172 except NameError:
173 cache = {}
174
175 It is legal though generally not very useful to reload built-in or
176 dynamically loaded modules (this is not true for e.g. :mod:`sys`,
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +0300177 :mod:`__main__`, :mod:`builtins` and other key modules where reloading is
Brett Cannon3fe35e62013-06-14 15:04:26 -0400178 frowned upon). In many cases, however, extension modules are not designed to
179 be initialized more than once, and may fail in arbitrary ways when reloaded.
180
181 If a module imports objects from another module using :keyword:`from` ...
182 :keyword:`import` ..., calling :func:`reload` for the other module does not
183 redefine the objects imported from it --- one way around this is to
184 re-execute the :keyword:`from` statement, another is to use :keyword:`import`
185 and qualified names (*module.name*) instead.
186
187 If a module instantiates instances of a class, reloading the module that
188 defines the class does not affect the method definitions of the instances ---
189 they continue to use the old class definition. The same is true for derived
190 classes.
191
192 .. versionadded:: 3.4
193
Brett Cannon78246b62009-01-25 04:56:30 +0000194
Brett Cannon2a922ed2009-03-09 03:35:50 +0000195:mod:`importlib.abc` -- Abstract base classes related to import
196---------------------------------------------------------------
197
198.. module:: importlib.abc
199 :synopsis: Abstract base classes related to import
200
201The :mod:`importlib.abc` module contains all of the core abstract base classes
202used by :keyword:`import`. Some subclasses of the core abstract base classes
203are also provided to help in implementing the core ABCs.
204
Andrew Svetlova8656542012-08-13 22:19:01 +0300205ABC hierarchy::
206
207 object
Brett Cannon1b799182012-08-17 14:08:24 -0400208 +-- Finder (deprecated)
Andrew Svetlova8656542012-08-13 22:19:01 +0300209 | +-- MetaPathFinder
210 | +-- PathEntryFinder
211 +-- Loader
212 +-- ResourceLoader --------+
213 +-- InspectLoader |
214 +-- ExecutionLoader --+
215 +-- FileLoader
216 +-- SourceLoader
Andrew Svetlova8656542012-08-13 22:19:01 +0300217
Brett Cannon2a922ed2009-03-09 03:35:50 +0000218
219.. class:: Finder
220
Brett Cannon1b799182012-08-17 14:08:24 -0400221 An abstract base class representing a :term:`finder`.
222
223 .. deprecated:: 3.3
224 Use :class:`MetaPathFinder` or :class:`PathEntryFinder` instead.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000225
Brett Cannonf4dc9202012-08-10 12:21:12 -0400226 .. method:: find_module(fullname, path=None)
Brett Cannonb46a1792012-02-27 18:15:42 -0500227
Brett Cannonf4dc9202012-08-10 12:21:12 -0400228 An abstact method for finding a :term:`loader` for the specified
229 module. Originally specified in :pep:`302`, this method was meant
230 for use in :data:`sys.meta_path` and in the path-based import subsystem.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000231
Brett Cannon100883f2013-04-09 16:59:39 -0400232 .. versionchanged:: 3.4
233 Returns ``None`` when called instead of raising
234 :exc:`NotImplementedError`.
235
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000236
Brett Cannon077ef452012-08-02 17:50:06 -0400237.. class:: MetaPathFinder
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000238
Brett Cannonf4dc9202012-08-10 12:21:12 -0400239 An abstract base class representing a :term:`meta path finder`. For
240 compatibility, this is a subclass of :class:`Finder`.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000241
242 .. versionadded:: 3.3
243
Eric Snowca2d8542013-12-16 23:06:52 -0700244 .. method:: find_spec(fullname, path, target=None)
245
246 An abstract method for finding a :term:`spec <module spec>` for
247 the specified module. If this is a top-level import, *path* will
248 be ``None``. Otherwise, this is a search for a subpackage or
249 module and *path* will be the value of :attr:`__path__` from the
250 parent package. If a spec cannot be found, ``None`` is returned.
251 When passed in, ``target`` is a module object that the finder may
252 use to make a more educated about what spec to return.
253
254 .. versionadded:: 3.4
255
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000256 .. method:: find_module(fullname, path)
257
Eric Snowca2d8542013-12-16 23:06:52 -0700258 A legacy method for finding a :term:`loader` for the specified
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000259 module. If this is a top-level import, *path* will be ``None``.
Ezio Melotti1f67e802012-10-21 07:24:13 +0300260 Otherwise, this is a search for a subpackage or module and *path*
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000261 will be the value of :attr:`__path__` from the parent
262 package. If a loader cannot be found, ``None`` is returned.
263
Brett Cannon8d942292014-01-07 15:52:42 -0500264 If :meth:`find_spec` is defined, backwards-compatible functionality is
265 provided.
266
Brett Cannon100883f2013-04-09 16:59:39 -0400267 .. versionchanged:: 3.4
268 Returns ``None`` when called instead of raising
Brett Cannon8d942292014-01-07 15:52:42 -0500269 :exc:`NotImplementedError`. Can use :meth:`find_spec` to provide
270 functionality.
Brett Cannon100883f2013-04-09 16:59:39 -0400271
Eric Snowca2d8542013-12-16 23:06:52 -0700272 .. deprecated:: 3.4
273 Use :meth:`find_spec` instead.
274
Brett Cannonf4dc9202012-08-10 12:21:12 -0400275 .. method:: invalidate_caches()
276
277 An optional method which, when called, should invalidate any internal
Brett Cannona6e85812012-08-11 19:41:27 -0400278 cache used by the finder. Used by :func:`importlib.invalidate_caches`
279 when invalidating the caches of all finders on :data:`sys.meta_path`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400280
Brett Cannon100883f2013-04-09 16:59:39 -0400281 .. versionchanged:: 3.4
282 Returns ``None`` when called instead of ``NotImplemented``.
283
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000284
Brett Cannon077ef452012-08-02 17:50:06 -0400285.. class:: PathEntryFinder
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000286
Brett Cannonf4dc9202012-08-10 12:21:12 -0400287 An abstract base class representing a :term:`path entry finder`. Though
288 it bears some similarities to :class:`MetaPathFinder`, ``PathEntryFinder``
289 is meant for use only within the path-based import subsystem provided
290 by :class:`PathFinder`. This ABC is a subclass of :class:`Finder` for
Brett Cannon100883f2013-04-09 16:59:39 -0400291 compatibility reasons only.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000292
293 .. versionadded:: 3.3
294
Eric Snowca2d8542013-12-16 23:06:52 -0700295 .. method:: find_spec(fullname, target=None)
296
297 An abstract method for finding a :term:`spec <module spec>` for
298 the specified module. The finder will search for the module only
299 within the :term:`path entry` to which it is assigned. If a spec
300 cannot be found, ``None`` is returned. When passed in, ``target``
301 is a module object that the finder may use to make a more educated
302 about what spec to return.
303
304 .. versionadded:: 3.4
305
Brett Cannon4067aa22013-04-27 23:20:32 -0400306 .. method:: find_loader(fullname)
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000307
Eric Snowca2d8542013-12-16 23:06:52 -0700308 A legacy method for finding a :term:`loader` for the specified
Brett Cannonf4dc9202012-08-10 12:21:12 -0400309 module. Returns a 2-tuple of ``(loader, portion)`` where ``portion``
310 is a sequence of file system locations contributing to part of a namespace
311 package. The loader may be ``None`` while specifying ``portion`` to
312 signify the contribution of the file system locations to a namespace
313 package. An empty list can be used for ``portion`` to signify the loader
Brett Cannon100883f2013-04-09 16:59:39 -0400314 is not part of a namespace package. If ``loader`` is ``None`` and
315 ``portion`` is the empty list then no loader or location for a namespace
316 package were found (i.e. failure to find anything for the module).
317
Brett Cannon8d942292014-01-07 15:52:42 -0500318 If :meth:`find_spec` is defined then backwards-compatible functionality is
319 provided.
320
Brett Cannon100883f2013-04-09 16:59:39 -0400321 .. versionchanged:: 3.4
322 Returns ``(None, [])`` instead of raising :exc:`NotImplementedError`.
Brett Cannon8d942292014-01-07 15:52:42 -0500323 Uses :meth:`find_spec` when available to provide functionality.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400324
Eric Snowca2d8542013-12-16 23:06:52 -0700325 .. deprecated:: 3.4
326 Use :meth:`find_spec` instead.
327
Brett Cannon4067aa22013-04-27 23:20:32 -0400328 .. method:: find_module(fullname)
Brett Cannonf4dc9202012-08-10 12:21:12 -0400329
330 A concrete implementation of :meth:`Finder.find_module` which is
331 equivalent to ``self.find_loader(fullname)[0]``.
332
Eric Snowca2d8542013-12-16 23:06:52 -0700333 .. deprecated:: 3.4
334 Use :meth:`find_spec` instead.
335
Brett Cannonf4dc9202012-08-10 12:21:12 -0400336 .. method:: invalidate_caches()
337
338 An optional method which, when called, should invalidate any internal
Brett Cannona6e85812012-08-11 19:41:27 -0400339 cache used by the finder. Used by :meth:`PathFinder.invalidate_caches`
Brett Cannonf4dc9202012-08-10 12:21:12 -0400340 when invalidating the caches of all cached finders.
Brett Cannonb46a1792012-02-27 18:15:42 -0500341
Brett Cannon2a922ed2009-03-09 03:35:50 +0000342
343.. class:: Loader
344
345 An abstract base class for a :term:`loader`.
Guido van Rossum09613542009-03-30 20:34:57 +0000346 See :pep:`302` for the exact definition for a loader.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000347
Eric Snowca2d8542013-12-16 23:06:52 -0700348 .. method:: create_module(spec)
349
350 An optional method that returns the module object to use when
351 importing a module. create_module() may also return ``None``,
352 indicating that the default module creation should take place
353 instead.
354
355 .. versionadded:: 3.4
356
357 .. method:: exec_module(module)
358
359 An abstract method that executes the module in its own namespace
360 when a module is imported or reloaded. The module should already
361 be initialized when exec_module() is called.
362
363 .. versionadded:: 3.4
364
Brett Cannon9c751b72009-03-09 16:28:16 +0000365 .. method:: load_module(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000366
Eric Snowca2d8542013-12-16 23:06:52 -0700367 A legacy method for loading a module. If the module cannot be
Brett Cannon2a922ed2009-03-09 03:35:50 +0000368 loaded, :exc:`ImportError` is raised, otherwise the loaded module is
369 returned.
370
Guido van Rossum09613542009-03-30 20:34:57 +0000371 If the requested module already exists in :data:`sys.modules`, that
Brett Cannon2a922ed2009-03-09 03:35:50 +0000372 module should be used and reloaded.
Guido van Rossum09613542009-03-30 20:34:57 +0000373 Otherwise the loader should create a new module and insert it into
374 :data:`sys.modules` before any loading begins, to prevent recursion
375 from the import. If the loader inserted a module and the load fails, it
Brett Cannon2a922ed2009-03-09 03:35:50 +0000376 must be removed by the loader from :data:`sys.modules`; modules already
377 in :data:`sys.modules` before the loader began execution should be left
Eric Snowb523f842013-11-22 09:05:39 -0700378 alone (see :func:`importlib.util.module_for_loader`).
Brett Cannon2a922ed2009-03-09 03:35:50 +0000379
Guido van Rossum09613542009-03-30 20:34:57 +0000380 The loader should set several attributes on the module.
381 (Note that some of these attributes can change when a module is
Eric Snowb523f842013-11-22 09:05:39 -0700382 reloaded):
Brett Cannon2a922ed2009-03-09 03:35:50 +0000383
384 - :attr:`__name__`
385 The name of the module.
386
387 - :attr:`__file__`
388 The path to where the module data is stored (not set for built-in
389 modules).
390
Brett Cannon2cefb3c2013-05-25 11:26:11 -0400391 - :attr:`__cached__`
392 The path to where a compiled version of the module is/should be
393 stored (not set when the attribute would be inappropriate).
394
Brett Cannon2a922ed2009-03-09 03:35:50 +0000395 - :attr:`__path__`
Guido van Rossum09613542009-03-30 20:34:57 +0000396 A list of strings specifying the search path within a
Brett Cannon2a922ed2009-03-09 03:35:50 +0000397 package. This attribute is not set on modules.
398
399 - :attr:`__package__`
400 The parent package for the module/package. If the module is
401 top-level then it has a value of the empty string. The
Brett Cannon100883f2013-04-09 16:59:39 -0400402 :func:`importlib.util.module_for_loader` decorator can handle the
403 details for :attr:`__package__`.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000404
405 - :attr:`__loader__`
Brett Cannon100883f2013-04-09 16:59:39 -0400406 The loader used to load the module. The
407 :func:`importlib.util.module_for_loader` decorator can handle the
408 details for :attr:`__package__`.
409
Brett Cannon8d942292014-01-07 15:52:42 -0500410 When :meth:`exec_module` is available then backwards-compatible
411 functionality is provided.
412
Brett Cannon100883f2013-04-09 16:59:39 -0400413 .. versionchanged:: 3.4
414 Raise :exc:`ImportError` when called instead of
Brett Cannon8d942292014-01-07 15:52:42 -0500415 :exc:`NotImplementedError`. Functionality provided when
416 :meth:`exec_module` is available.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000417
Eric Snowca2d8542013-12-16 23:06:52 -0700418 .. deprecated:: 3.4
419 The recommended API for loading a module is :meth:`exec_module`
420 (and optionally :meth:`create_module`). Loaders should implement
421 it instead of load_module(). The import machinery takes care of
422 all the other responsibilities of load_module() when exec_module()
423 is implemented.
424
Barry Warsawd7d21942012-07-29 16:36:17 -0400425 .. method:: module_repr(module)
426
Eric Snowca2d8542013-12-16 23:06:52 -0700427 A legacy method which when implemented calculates and returns the
Brett Cannon100883f2013-04-09 16:59:39 -0400428 given module's repr, as a string. The module type's default repr() will
429 use the result of this method as appropriate.
Barry Warsawd7d21942012-07-29 16:36:17 -0400430
Georg Brandl526575d2013-04-11 16:10:13 +0200431 .. versionadded:: 3.3
Barry Warsawd7d21942012-07-29 16:36:17 -0400432
Brett Cannon100883f2013-04-09 16:59:39 -0400433 .. versionchanged:: 3.4
Georg Brandl526575d2013-04-11 16:10:13 +0200434 Made optional instead of an abstractmethod.
Brett Cannon100883f2013-04-09 16:59:39 -0400435
Eric Snowca2d8542013-12-16 23:06:52 -0700436 .. deprecated:: 3.4
437 The import machinery now takes care of this automatically.
438
Brett Cannon2a922ed2009-03-09 03:35:50 +0000439
440.. class:: ResourceLoader
441
442 An abstract base class for a :term:`loader` which implements the optional
443 :pep:`302` protocol for loading arbitrary resources from the storage
444 back-end.
445
Brett Cannon9c751b72009-03-09 16:28:16 +0000446 .. method:: get_data(path)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000447
448 An abstract method to return the bytes for the data located at *path*.
Guido van Rossum09613542009-03-30 20:34:57 +0000449 Loaders that have a file-like storage back-end
Brett Cannon16248a42009-04-01 20:47:14 +0000450 that allows storing arbitrary data
Guido van Rossum09613542009-03-30 20:34:57 +0000451 can implement this abstract method to give direct access
Andrew Svetlov08af0002014-04-01 01:13:30 +0300452 to the data stored. :exc:`OSError` is to be raised if the *path* cannot
Brett Cannon2a922ed2009-03-09 03:35:50 +0000453 be found. The *path* is expected to be constructed using a module's
Brett Cannon16248a42009-04-01 20:47:14 +0000454 :attr:`__file__` attribute or an item from a package's :attr:`__path__`.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000455
Brett Cannon100883f2013-04-09 16:59:39 -0400456 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300457 Raises :exc:`OSError` instead of :exc:`NotImplementedError`.
Brett Cannon100883f2013-04-09 16:59:39 -0400458
Brett Cannon2a922ed2009-03-09 03:35:50 +0000459
460.. class:: InspectLoader
461
462 An abstract base class for a :term:`loader` which implements the optional
Guido van Rossum09613542009-03-30 20:34:57 +0000463 :pep:`302` protocol for loaders that inspect modules.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000464
Brett Cannona113ac52009-03-15 01:41:33 +0000465 .. method:: get_code(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000466
R David Murray0ae7ae12014-01-08 18:16:02 -0500467 Return the code object for a module, or ``None`` if the module does not
468 have a code object (as would be the case, for example, for a built-in
469 module). Raise an :exc:`ImportError` if loader cannot find the
470 requested module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000471
Brett Cannon3b62ca82013-05-27 21:11:04 -0400472 .. note::
473 While the method has a default implementation, it is suggested that
474 it be overridden if possible for performance.
475
R David Murray1b00f252012-08-15 10:43:58 -0400476 .. index::
477 single: universal newlines; importlib.abc.InspectLoader.get_source method
478
Brett Cannon100883f2013-04-09 16:59:39 -0400479 .. versionchanged:: 3.4
Brett Cannon3b62ca82013-05-27 21:11:04 -0400480 No longer abstract and a concrete implementation is provided.
Brett Cannon100883f2013-04-09 16:59:39 -0400481
Brett Cannon9c751b72009-03-09 16:28:16 +0000482 .. method:: get_source(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000483
484 An abstract method to return the source of a module. It is returned as
R David Murray1b00f252012-08-15 10:43:58 -0400485 a text string using :term:`universal newlines`, translating all
R David Murrayee0a9452012-08-15 11:05:36 -0400486 recognized line separators into ``'\n'`` characters. Returns ``None``
487 if no source is available (e.g. a built-in module). Raises
488 :exc:`ImportError` if the loader cannot find the module specified.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000489
Brett Cannon100883f2013-04-09 16:59:39 -0400490 .. versionchanged:: 3.4
491 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
492
Brett Cannona113ac52009-03-15 01:41:33 +0000493 .. method:: is_package(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000494
Brett Cannona113ac52009-03-15 01:41:33 +0000495 An abstract method to return a true value if the module is a package, a
496 false value otherwise. :exc:`ImportError` is raised if the
497 :term:`loader` cannot find the module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000498
Brett Cannon100883f2013-04-09 16:59:39 -0400499 .. versionchanged:: 3.4
500 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
501
Brett Cannon9ffe85e2013-05-26 16:45:10 -0400502 .. method:: source_to_code(data, path='<string>')
503
504 Create a code object from Python source.
505
506 The *data* argument can be whatever the :func:`compile` function
507 supports (i.e. string or bytes). The *path* argument should be
508 the "path" to where the source code originated from, which can be an
509 abstract concept (e.g. location in a zip file).
510
511 .. versionadded:: 3.4
512
Eric Snowca2d8542013-12-16 23:06:52 -0700513 .. method:: exec_module(module)
514
515 Implementation of :meth:`Loader.exec_module`.
516
517 .. versionadded:: 3.4
518
Brett Cannon0dbb4c72013-05-31 18:56:47 -0400519 .. method:: load_module(fullname)
520
Eric Snowca2d8542013-12-16 23:06:52 -0700521 Implementation of :meth:`Loader.load_module`.
522
523 .. deprecated:: 3.4
524 use :meth:`exec_module` instead.
Brett Cannon0dbb4c72013-05-31 18:56:47 -0400525
Brett Cannon2a922ed2009-03-09 03:35:50 +0000526
Brett Cannon69194272009-07-20 04:23:48 +0000527.. class:: ExecutionLoader
528
529 An abstract base class which inherits from :class:`InspectLoader` that,
Brett Cannon23460292009-07-20 22:59:00 +0000530 when implemented, helps a module to be executed as a script. The ABC
Brett Cannon69194272009-07-20 04:23:48 +0000531 represents an optional :pep:`302` protocol.
532
533 .. method:: get_filename(fullname)
534
Brett Cannonf23e3742010-06-27 23:57:46 +0000535 An abstract method that is to return the value of :attr:`__file__` for
Brett Cannon69194272009-07-20 04:23:48 +0000536 the specified module. If no path is available, :exc:`ImportError` is
537 raised.
538
Brett Cannonf23e3742010-06-27 23:57:46 +0000539 If source code is available, then the method should return the path to
540 the source file, regardless of whether a bytecode was used to load the
541 module.
542
Brett Cannon100883f2013-04-09 16:59:39 -0400543 .. versionchanged:: 3.4
544 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
545
Brett Cannonf23e3742010-06-27 23:57:46 +0000546
Brett Cannon938d44d2012-04-22 19:58:33 -0400547.. class:: FileLoader(fullname, path)
548
549 An abstract base class which inherits from :class:`ResourceLoader` and
Andrew Svetlova60de4f2013-02-17 16:55:58 +0200550 :class:`ExecutionLoader`, providing concrete implementations of
Brett Cannon938d44d2012-04-22 19:58:33 -0400551 :meth:`ResourceLoader.get_data` and :meth:`ExecutionLoader.get_filename`.
552
553 The *fullname* argument is a fully resolved name of the module the loader is
554 to handle. The *path* argument is the path to the file for the module.
555
556 .. versionadded:: 3.3
557
558 .. attribute:: name
559
560 The name of the module the loader can handle.
561
562 .. attribute:: path
563
564 Path to the file of the module.
565
Barry Warsawd7d21942012-07-29 16:36:17 -0400566 .. method:: load_module(fullname)
Brett Cannonc0499522012-05-11 14:48:41 -0400567
Barry Warsawd7d21942012-07-29 16:36:17 -0400568 Calls super's ``load_module()``.
Brett Cannonc0499522012-05-11 14:48:41 -0400569
Eric Snowca2d8542013-12-16 23:06:52 -0700570 .. deprecated:: 3.4
571 Use :meth:`Loader.exec_module` instead.
572
Brett Cannon938d44d2012-04-22 19:58:33 -0400573 .. method:: get_filename(fullname)
574
Barry Warsawd7d21942012-07-29 16:36:17 -0400575 Returns :attr:`path`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400576
577 .. method:: get_data(path)
578
Brett Cannon3b62ca82013-05-27 21:11:04 -0400579 Reads *path* as a binary file and returns the bytes from it.
Brett Cannon938d44d2012-04-22 19:58:33 -0400580
581
Brett Cannonf23e3742010-06-27 23:57:46 +0000582.. class:: SourceLoader
583
584 An abstract base class for implementing source (and optionally bytecode)
585 file loading. The class inherits from both :class:`ResourceLoader` and
586 :class:`ExecutionLoader`, requiring the implementation of:
587
588 * :meth:`ResourceLoader.get_data`
589 * :meth:`ExecutionLoader.get_filename`
Brett Cannon6dfbff32010-07-21 09:48:31 +0000590 Should only return the path to the source file; sourceless
Brett Cannona81d5272013-06-16 19:17:12 -0400591 loading is not supported.
Brett Cannonf23e3742010-06-27 23:57:46 +0000592
593 The abstract methods defined by this class are to add optional bytecode
Brett Cannon5650e4f2012-11-18 10:03:31 -0500594 file support. Not implementing these optional methods (or causing them to
595 raise :exc:`NotImplementedError`) causes the loader to
Brett Cannonf23e3742010-06-27 23:57:46 +0000596 only work with source code. Implementing the methods allows the loader to
597 work with source *and* bytecode files; it does not allow for *sourceless*
598 loading where only bytecode is provided. Bytecode files are an
599 optimization to speed up loading by removing the parsing step of Python's
600 compiler, and so no bytecode-specific API is exposed.
601
Brett Cannon773468f2012-08-02 17:35:34 -0400602 .. method:: path_stats(path)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100603
604 Optional abstract method which returns a :class:`dict` containing
605 metadata about the specifed path. Supported dictionary keys are:
606
607 - ``'mtime'`` (mandatory): an integer or floating-point number
608 representing the modification time of the source code;
609 - ``'size'`` (optional): the size in bytes of the source code.
610
611 Any other keys in the dictionary are ignored, to allow for future
Andrew Svetlov08af0002014-04-01 01:13:30 +0300612 extensions. If the path cannot be handled, :exc:`OSError` is raised.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100613
614 .. versionadded:: 3.3
615
Brett Cannon100883f2013-04-09 16:59:39 -0400616 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300617 Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
Brett Cannon100883f2013-04-09 16:59:39 -0400618
Brett Cannon773468f2012-08-02 17:35:34 -0400619 .. method:: path_mtime(path)
Brett Cannonf23e3742010-06-27 23:57:46 +0000620
621 Optional abstract method which returns the modification time for the
622 specified path.
623
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100624 .. deprecated:: 3.3
625 This method is deprecated in favour of :meth:`path_stats`. You don't
626 have to implement it, but it is still available for compatibility
Andrew Svetlov08af0002014-04-01 01:13:30 +0300627 purposes. Raise :exc:`OSError` if the path cannot be handled.
Brett Cannon100883f2013-04-09 16:59:39 -0400628
Georg Brandldf48b972014-03-24 09:06:18 +0100629 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300630 Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100631
Brett Cannon773468f2012-08-02 17:35:34 -0400632 .. method:: set_data(path, data)
Brett Cannonf23e3742010-06-27 23:57:46 +0000633
634 Optional abstract method which writes the specified bytes to a file
Brett Cannon61b14252010-07-03 21:48:25 +0000635 path. Any intermediate directories which do not exist are to be created
636 automatically.
637
638 When writing to the path fails because the path is read-only
Brett Cannon2cefb3c2013-05-25 11:26:11 -0400639 (:attr:`errno.EACCES`/:exc:`PermissionError`), do not propagate the
640 exception.
Brett Cannonf23e3742010-06-27 23:57:46 +0000641
Brett Cannon100883f2013-04-09 16:59:39 -0400642 .. versionchanged:: 3.4
643 No longer raises :exc:`NotImplementedError` when called.
644
Brett Cannon773468f2012-08-02 17:35:34 -0400645 .. method:: get_code(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000646
647 Concrete implementation of :meth:`InspectLoader.get_code`.
648
Eric Snowca2d8542013-12-16 23:06:52 -0700649 .. method:: exec_module(module)
650
651 Concrete implementation of :meth:`Loader.exec_module`.
652
653 .. versionadded:: 3.4
654
Brett Cannon773468f2012-08-02 17:35:34 -0400655 .. method:: load_module(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000656
Eric Snowca2d8542013-12-16 23:06:52 -0700657 Concrete implementation of :meth:`Loader.load_module`.
658
659 .. deprecated:: 3.4
660 Use :meth:`exec_module` instead.
Brett Cannonf23e3742010-06-27 23:57:46 +0000661
Brett Cannon773468f2012-08-02 17:35:34 -0400662 .. method:: get_source(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000663
664 Concrete implementation of :meth:`InspectLoader.get_source`.
665
Brett Cannon773468f2012-08-02 17:35:34 -0400666 .. method:: is_package(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000667
668 Concrete implementation of :meth:`InspectLoader.is_package`. A module
Brett Cannonea0b8232012-06-15 20:00:53 -0400669 is determined to be a package if its file path (as provided by
670 :meth:`ExecutionLoader.get_filename`) is a file named
671 ``__init__`` when the file extension is removed **and** the module name
672 itself does not end in ``__init__``.
Brett Cannonf23e3742010-06-27 23:57:46 +0000673
Brett Cannon69194272009-07-20 04:23:48 +0000674
Brett Cannon78246b62009-01-25 04:56:30 +0000675:mod:`importlib.machinery` -- Importers and path hooks
676------------------------------------------------------
677
678.. module:: importlib.machinery
679 :synopsis: Importers and path hooks
680
681This module contains the various objects that help :keyword:`import`
682find and load modules.
683
Brett Cannoncb66eb02012-05-11 12:58:42 -0400684.. attribute:: SOURCE_SUFFIXES
685
686 A list of strings representing the recognized file suffixes for source
687 modules.
688
689 .. versionadded:: 3.3
690
691.. attribute:: DEBUG_BYTECODE_SUFFIXES
692
693 A list of strings representing the file suffixes for non-optimized bytecode
694 modules.
695
696 .. versionadded:: 3.3
697
698.. attribute:: OPTIMIZED_BYTECODE_SUFFIXES
699
700 A list of strings representing the file suffixes for optimized bytecode
701 modules.
702
703 .. versionadded:: 3.3
704
705.. attribute:: BYTECODE_SUFFIXES
706
707 A list of strings representing the recognized file suffixes for bytecode
708 modules. Set to either :attr:`DEBUG_BYTECODE_SUFFIXES` or
709 :attr:`OPTIMIZED_BYTECODE_SUFFIXES` based on whether ``__debug__`` is true.
710
711 .. versionadded:: 3.3
712
713.. attribute:: EXTENSION_SUFFIXES
714
Nick Coghlan76e07702012-07-18 23:14:57 +1000715 A list of strings representing the recognized file suffixes for
Brett Cannoncb66eb02012-05-11 12:58:42 -0400716 extension modules.
717
718 .. versionadded:: 3.3
719
Nick Coghlanc5afd422012-07-18 23:59:08 +1000720.. function:: all_suffixes()
Nick Coghlan76e07702012-07-18 23:14:57 +1000721
722 Returns a combined list of strings representing all file suffixes for
Nick Coghlanc5afd422012-07-18 23:59:08 +1000723 modules recognized by the standard import machinery. This is a
Nick Coghlan76e07702012-07-18 23:14:57 +1000724 helper for code which simply needs to know if a filesystem path
Nick Coghlanc5afd422012-07-18 23:59:08 +1000725 potentially refers to a module without needing any details on the kind
726 of module (for example, :func:`inspect.getmodulename`)
Nick Coghlan76e07702012-07-18 23:14:57 +1000727
728 .. versionadded:: 3.3
729
730
Brett Cannon78246b62009-01-25 04:56:30 +0000731.. class:: BuiltinImporter
732
Brett Cannon2a922ed2009-03-09 03:35:50 +0000733 An :term:`importer` for built-in modules. All known built-in modules are
734 listed in :data:`sys.builtin_module_names`. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000735 :class:`importlib.abc.MetaPathFinder` and
736 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000737
738 Only class methods are defined by this class to alleviate the need for
739 instantiation.
740
Eric Snowca2d8542013-12-16 23:06:52 -0700741 .. note::
742 Due to limitations in the extension module C-API, for now
743 BuiltinImporter does not implement :meth:`Loader.exec_module`.
744
Brett Cannon78246b62009-01-25 04:56:30 +0000745
746.. class:: FrozenImporter
747
Brett Cannon2a922ed2009-03-09 03:35:50 +0000748 An :term:`importer` for frozen modules. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000749 :class:`importlib.abc.MetaPathFinder` and
750 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000751
752 Only class methods are defined by this class to alleviate the need for
753 instantiation.
754
Brett Cannondebb98d2009-02-16 04:18:01 +0000755
Nick Coghlanff794862012-08-02 21:45:24 +1000756.. class:: WindowsRegistryFinder
757
758 :term:`Finder` for modules declared in the Windows registry. This class
Nick Coghlan49417742012-08-02 23:03:58 +1000759 implements the :class:`importlib.abc.Finder` ABC.
Nick Coghlanff794862012-08-02 21:45:24 +1000760
761 Only class methods are defined by this class to alleviate the need for
762 instantiation.
763
764 .. versionadded:: 3.3
765
766
Brett Cannondebb98d2009-02-16 04:18:01 +0000767.. class:: PathFinder
768
Brett Cannon1b799182012-08-17 14:08:24 -0400769 A :term:`Finder` for :data:`sys.path` and package ``__path__`` attributes.
770 This class implements the :class:`importlib.abc.MetaPathFinder` ABC.
Brett Cannondebb98d2009-02-16 04:18:01 +0000771
Brett Cannon1b799182012-08-17 14:08:24 -0400772 Only class methods are defined by this class to alleviate the need for
773 instantiation.
Brett Cannondebb98d2009-02-16 04:18:01 +0000774
Eric Snowca2d8542013-12-16 23:06:52 -0700775 .. classmethod:: find_spec(fullname, path=None, target=None)
776
777 Class method that attempts to find a :term:`spec <module spec>`
778 for the module specified by *fullname* on :data:`sys.path` or, if
779 defined, on *path*. For each path entry that is searched,
780 :data:`sys.path_importer_cache` is checked. If a non-false object
781 is found then it is used as the :term:`path entry finder` to look
782 for the module being searched for. If no entry is found in
783 :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
784 searched for a finder for the path entry and, if found, is stored
785 in :data:`sys.path_importer_cache` along with being queried about
786 the module. If no finder is ever found then ``None`` is both
787 stored in the cache and returned.
788
789 .. versionadded:: 3.4
790
Brett Cannon1b799182012-08-17 14:08:24 -0400791 .. classmethod:: find_module(fullname, path=None)
Brett Cannondebb98d2009-02-16 04:18:01 +0000792
Eric Snowca2d8542013-12-16 23:06:52 -0700793 A legacy wrapper around :meth:`find_spec`.
794
795 .. deprecated:: 3.4
796 Use :meth:`find_spec` instead.
Brett Cannond2e7b332009-02-17 02:45:03 +0000797
Brett Cannonf4dc9202012-08-10 12:21:12 -0400798 .. classmethod:: invalidate_caches()
799
Eric Snowca2d8542013-12-16 23:06:52 -0700800 Calls :meth:`importlib.abc.PathEntryFinder.invalidate_caches` on all
801 finders stored in :attr:`sys.path_importer_cache`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400802
Eric Snowca2d8542013-12-16 23:06:52 -0700803 .. versionchanged:: 3.4
804 Calls objects in :data:`sys.path_hooks` with the current working
805 directory for ``''`` (i.e. the empty string).
Brett Cannon27e27f72013-10-18 11:39:04 -0400806
Brett Cannond2e7b332009-02-17 02:45:03 +0000807
Brett Cannon938d44d2012-04-22 19:58:33 -0400808.. class:: FileFinder(path, \*loader_details)
809
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000810 A concrete implementation of :class:`importlib.abc.PathEntryFinder` which
811 caches results from the file system.
Brett Cannon938d44d2012-04-22 19:58:33 -0400812
813 The *path* argument is the directory for which the finder is in charge of
814 searching.
815
Brett Cannonac9f2f32012-08-10 13:47:54 -0400816 The *loader_details* argument is a variable number of 2-item tuples each
817 containing a loader and a sequence of file suffixes the loader recognizes.
Brett Cannon29b2f172013-06-21 18:31:55 -0400818 The loaders are expected to be callables which accept two arguments of
819 the module's name and the path to the file found.
Brett Cannon938d44d2012-04-22 19:58:33 -0400820
821 The finder will cache the directory contents as necessary, making stat calls
822 for each module search to verify the cache is not outdated. Because cache
823 staleness relies upon the granularity of the operating system's state
824 information of the file system, there is a potential race condition of
825 searching for a module, creating a new file, and then searching for the
826 module the new file represents. If the operations happen fast enough to fit
827 within the granularity of stat calls, then the module search will fail. To
828 prevent this from happening, when you create a module dynamically, make sure
829 to call :func:`importlib.invalidate_caches`.
830
831 .. versionadded:: 3.3
832
833 .. attribute:: path
834
835 The path the finder will search in.
836
Eric Snowca2d8542013-12-16 23:06:52 -0700837 .. method:: find_spec(fullname, target=None)
838
839 Attempt to find the spec to handle *fullname* within :attr:`path`.
840
841 .. versionadded:: 3.4
842
Brett Cannon1d753822013-06-16 19:06:55 -0400843 .. method:: find_loader(fullname)
Brett Cannon938d44d2012-04-22 19:58:33 -0400844
845 Attempt to find the loader to handle *fullname* within :attr:`path`.
846
847 .. method:: invalidate_caches()
848
849 Clear out the internal cache.
850
851 .. classmethod:: path_hook(\*loader_details)
852
853 A class method which returns a closure for use on :attr:`sys.path_hooks`.
854 An instance of :class:`FileFinder` is returned by the closure using the
855 path argument given to the closure directly and *loader_details*
856 indirectly.
857
858 If the argument to the closure is not an existing directory,
859 :exc:`ImportError` is raised.
860
861
862.. class:: SourceFileLoader(fullname, path)
863
864 A concrete implementation of :class:`importlib.abc.SourceLoader` by
865 subclassing :class:`importlib.abc.FileLoader` and providing some concrete
866 implementations of other methods.
867
868 .. versionadded:: 3.3
869
870 .. attribute:: name
871
872 The name of the module that this loader will handle.
873
874 .. attribute:: path
875
876 The path to the source file.
877
878 .. method:: is_package(fullname)
879
880 Return true if :attr:`path` appears to be for a package.
881
882 .. method:: path_stats(path)
883
884 Concrete implementation of :meth:`importlib.abc.SourceLoader.path_stats`.
885
886 .. method:: set_data(path, data)
887
888 Concrete implementation of :meth:`importlib.abc.SourceLoader.set_data`.
889
Brett Cannon062fcac2014-05-09 11:55:49 -0400890 .. method:: load_module(name=None)
891
892 Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
893 specifying the name of the module to load is optional.
894
Brett Cannon938d44d2012-04-22 19:58:33 -0400895
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200896.. class:: SourcelessFileLoader(fullname, path)
Brett Cannon938d44d2012-04-22 19:58:33 -0400897
898 A concrete implementation of :class:`importlib.abc.FileLoader` which can
899 import bytecode files (i.e. no source code files exist).
900
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200901 Please note that direct use of bytecode files (and thus not source code
902 files) inhibits your modules from being usable by all Python
903 implementations or new versions of Python which change the bytecode
904 format.
Brett Cannon938d44d2012-04-22 19:58:33 -0400905
906 .. versionadded:: 3.3
907
908 .. attribute:: name
909
910 The name of the module the loader will handle.
911
912 .. attribute:: path
913
914 The path to the bytecode file.
915
916 .. method:: is_package(fullname)
917
918 Determines if the module is a package based on :attr:`path`.
919
920 .. method:: get_code(fullname)
921
922 Returns the code object for :attr:`name` created from :attr:`path`.
923
924 .. method:: get_source(fullname)
925
926 Returns ``None`` as bytecode files have no source when this loader is
927 used.
928
Brett Cannon062fcac2014-05-09 11:55:49 -0400929 .. method:: load_module(name=None)
930
931 Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
932 specifying the name of the module to load is optional.
933
Brett Cannon938d44d2012-04-22 19:58:33 -0400934
935.. class:: ExtensionFileLoader(fullname, path)
936
Eric Snow51794452013-10-03 12:08:55 -0600937 A concrete implementation of :class:`importlib.abc.ExecutionLoader` for
Brett Cannon938d44d2012-04-22 19:58:33 -0400938 extension modules.
939
940 The *fullname* argument specifies the name of the module the loader is to
941 support. The *path* argument is the path to the extension module's file.
942
943 .. versionadded:: 3.3
944
945 .. attribute:: name
946
947 Name of the module the loader supports.
948
949 .. attribute:: path
950
951 Path to the extension module.
952
Brett Cannon062fcac2014-05-09 11:55:49 -0400953 .. method:: load_module(name=None)
Brett Cannon938d44d2012-04-22 19:58:33 -0400954
Brett Cannonc0499522012-05-11 14:48:41 -0400955 Loads the extension module if and only if *fullname* is the same as
956 :attr:`name` or is ``None``.
Brett Cannon938d44d2012-04-22 19:58:33 -0400957
Eric Snowca2d8542013-12-16 23:06:52 -0700958 .. note::
959 Due to limitations in the extension module C-API, for now
960 ExtensionFileLoader does not implement :meth:`Loader.exec_module`.
961
Brett Cannon938d44d2012-04-22 19:58:33 -0400962 .. method:: is_package(fullname)
963
Brett Cannonac9f2f32012-08-10 13:47:54 -0400964 Returns ``True`` if the file path points to a package's ``__init__``
965 module based on :attr:`EXTENSION_SUFFIXES`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400966
967 .. method:: get_code(fullname)
968
969 Returns ``None`` as extension modules lack a code object.
970
971 .. method:: get_source(fullname)
972
973 Returns ``None`` as extension modules do not have source code.
974
Eric Snow51794452013-10-03 12:08:55 -0600975 .. method:: get_filename(fullname)
976
977 Returns :attr:`path`.
978
Eric Snowdcd01b42013-10-04 20:35:34 -0600979 .. versionadded:: 3.4
980
Brett Cannon938d44d2012-04-22 19:58:33 -0400981
Eric Snowb523f842013-11-22 09:05:39 -0700982.. class:: ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)
983
984 A specification for a module's import-system-related state.
985
986 .. versionadded:: 3.4
987
988 .. attribute:: name
989
990 (``__name__``)
991
992 A string for the fully-qualified name of the module.
993
994 .. attribute:: loader
995
996 (``__loader__``)
997
998 The loader to use for loading. For namespace packages this should be
999 set to None.
1000
1001 .. attribute:: origin
1002
1003 (``__file__``)
1004
1005 Name of the place from which the module is loaded, e.g. "builtin" for
1006 built-in modules and the filename for modules loaded from source.
1007 Normally "origin" should be set, but it may be None (the default)
1008 which indicates it is unspecified.
1009
1010 .. attribute:: submodule_search_locations
1011
1012 (``__path__``)
1013
1014 List of strings for where to find submodules, if a package (None
1015 otherwise).
1016
1017 .. attribute:: loader_state
1018
1019 Container of extra module-specific data for use during loading (or
1020 None).
1021
1022 .. attribute:: cached
1023
1024 (``__cached__``)
1025
1026 String for where the compiled module should be stored (or None).
1027
1028 .. attribute:: parent
1029
1030 (``__package__``)
1031
1032 (Read-only) Fully-qualified name of the package to which the module
1033 belongs as a submodule (or None).
1034
1035 .. attribute:: has_location
1036
Eric Snowb282b3d2013-12-10 22:16:41 -07001037 Boolean indicating whether or not the module's "origin"
Eric Snowb523f842013-11-22 09:05:39 -07001038 attribute refers to a loadable location.
1039
Brett Cannond2e7b332009-02-17 02:45:03 +00001040:mod:`importlib.util` -- Utility code for importers
1041---------------------------------------------------
1042
1043.. module:: importlib.util
Brett Cannon75321e82012-03-02 11:58:25 -05001044 :synopsis: Utility code for importers
Brett Cannond2e7b332009-02-17 02:45:03 +00001045
1046This module contains the various objects that help in the construction of
1047an :term:`importer`.
1048
Brett Cannon05a647d2013-06-14 19:02:34 -04001049.. attribute:: MAGIC_NUMBER
1050
1051 The bytes which represent the bytecode version number. If you need help with
1052 loading/writing bytecode then consider :class:`importlib.abc.SourceLoader`.
1053
1054 .. versionadded:: 3.4
1055
Brett Cannona3c96152013-06-14 22:26:30 -04001056.. function:: cache_from_source(path, debug_override=None)
1057
1058 Return the :pep:`3147` path to the byte-compiled file associated with the
1059 source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return
1060 value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.
1061 The ``cpython-32`` string comes from the current magic tag (see
1062 :func:`get_tag`; if :attr:`sys.implementation.cache_tag` is not defined then
1063 :exc:`NotImplementedError` will be raised). The returned path will end in
Serhiy Storchaka0e90e992013-11-29 12:19:53 +02001064 ``.pyc`` when ``__debug__`` is ``True`` or ``.pyo`` for an optimized Python
1065 (i.e. ``__debug__`` is ``False``). By passing in ``True`` or ``False`` for
Brett Cannona3c96152013-06-14 22:26:30 -04001066 *debug_override* you can override the system's value for ``__debug__`` for
1067 extension selection.
1068
1069 *path* need not exist.
1070
1071 .. versionadded:: 3.4
1072
1073
1074.. function:: source_from_cache(path)
1075
1076 Given the *path* to a :pep:`3147` file name, return the associated source code
1077 file path. For example, if *path* is
1078 ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be
1079 ``/foo/bar/baz.py``. *path* need not exist, however if it does not conform
1080 to :pep:`3147` format, a ``ValueError`` is raised. If
1081 :attr:`sys.implementation.cache_tag` is not defined,
1082 :exc:`NotImplementedError` is raised.
1083
1084 .. versionadded:: 3.4
1085
Brett Cannonf24fecd2013-06-16 18:37:53 -04001086.. function:: decode_source(source_bytes)
1087
1088 Decode the given bytes representing source code and return it as a string
1089 with universal newlines (as required by
1090 :meth:`importlib.abc.InspectLoader.get_source`).
1091
1092 .. versionadded:: 3.4
1093
Brett Cannond200bf52012-05-13 13:45:09 -04001094.. function:: resolve_name(name, package)
1095
1096 Resolve a relative module name to an absolute one.
1097
1098 If **name** has no leading dots, then **name** is simply returned. This
1099 allows for usage such as
1100 ``importlib.util.resolve_name('sys', __package__)`` without doing a
1101 check to see if the **package** argument is needed.
1102
1103 :exc:`ValueError` is raised if **name** is a relative module name but
1104 package is a false value (e.g. ``None`` or the empty string).
1105 :exc:`ValueError` is also raised a relative name would escape its containing
1106 package (e.g. requesting ``..bacon`` from within the ``spam`` package).
1107
1108 .. versionadded:: 3.3
1109
Eric Snow6029e082014-01-25 15:32:46 -07001110.. function:: find_spec(name, package=None)
1111
1112 Find the :term:`spec <module spec>` for a module, optionally relative to
1113 the specified **package** name. If the module is in :attr:`sys.modules`,
1114 then ``sys.modules[name].__spec__`` is returned (unless the spec would be
1115 ``None`` or is not set, in which case :exc:`ValueError` is raised).
1116 Otherwise a search using :attr:`sys.meta_path` is done. ``None`` is
1117 returned if no spec is found.
1118
1119 If **name** is for a submodule (contains a dot), the parent module is
1120 automatically imported.
1121
1122 **name** and **package** work the same as for :func:`import_module`.
1123
1124 .. versionadded:: 3.4
1125
Georg Brandl8a1caa22010-07-29 16:01:11 +00001126.. decorator:: module_for_loader
Brett Cannond2e7b332009-02-17 02:45:03 +00001127
Brett Cannona22faca2013-05-28 17:50:14 -04001128 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
Guido van Rossum09613542009-03-30 20:34:57 +00001129 to handle selecting the proper
Brett Cannond2e7b332009-02-17 02:45:03 +00001130 module object to load with. The decorated method is expected to have a call
Brett Cannon2a922ed2009-03-09 03:35:50 +00001131 signature taking two positional arguments
1132 (e.g. ``load_module(self, module)``) for which the second argument
Guido van Rossum09613542009-03-30 20:34:57 +00001133 will be the module **object** to be used by the loader.
Brett Cannonefad00d2012-04-27 17:27:14 -04001134 Note that the decorator will not work on static methods because of the
1135 assumption of two arguments.
Brett Cannond2e7b332009-02-17 02:45:03 +00001136
Guido van Rossum09613542009-03-30 20:34:57 +00001137 The decorated method will take in the **name** of the module to be loaded
1138 as expected for a :term:`loader`. If the module is not found in
Brett Cannon3dc48d62013-05-28 18:35:54 -04001139 :data:`sys.modules` then a new one is constructed. Regardless of where the
1140 module came from, :attr:`__loader__` set to **self** and :attr:`__package__`
1141 is set based on what :meth:`importlib.abc.InspectLoader.is_package` returns
1142 (if available). These attributes are set unconditionally to support
1143 reloading.
Brett Cannonefad00d2012-04-27 17:27:14 -04001144
1145 If an exception is raised by the decorated method and a module was added to
Brett Cannona87e31c2013-09-13 16:52:19 -04001146 :data:`sys.modules`, then the module will be removed to prevent a partially
1147 initialized module from being in left in :data:`sys.modules`. If the module
1148 was already in :data:`sys.modules` then it is left alone.
Brett Cannond2e7b332009-02-17 02:45:03 +00001149
Brett Cannonefad00d2012-04-27 17:27:14 -04001150 .. versionchanged:: 3.3
Georg Brandl61063cc2012-06-24 22:48:30 +02001151 :attr:`__loader__` and :attr:`__package__` are automatically set
1152 (when possible).
Brett Cannon57b46f52009-03-02 14:38:26 +00001153
Brett Cannon3dc48d62013-05-28 18:35:54 -04001154 .. versionchanged:: 3.4
Brett Cannon0dbb4c72013-05-31 18:56:47 -04001155 Set :attr:`__name__`, :attr:`__loader__` :attr:`__package__`
1156 unconditionally to support reloading.
1157
1158 .. deprecated:: 3.4
Eric Snowb523f842013-11-22 09:05:39 -07001159 The import machinery now directly performs all the functionality
1160 provided by this function.
Brett Cannon3dc48d62013-05-28 18:35:54 -04001161
Georg Brandl8a1caa22010-07-29 16:01:11 +00001162.. decorator:: set_loader
Brett Cannon2cf03a82009-03-10 05:17:37 +00001163
Brett Cannona22faca2013-05-28 17:50:14 -04001164 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
1165 to set the :attr:`__loader__`
1166 attribute on the returned module. If the attribute is already set the
1167 decorator does nothing. It is assumed that the first positional argument to
1168 the wrapped method (i.e. ``self``) is what :attr:`__loader__` should be set
1169 to.
Brett Cannon2cf03a82009-03-10 05:17:37 +00001170
Brett Cannon4802bec2013-03-13 10:41:36 -07001171 .. versionchanged:: 3.4
Brett Cannon4c14b5d2013-05-04 13:56:58 -04001172 Set ``__loader__`` if set to ``None``, as if the attribute does not
Brett Cannon4802bec2013-03-13 10:41:36 -07001173 exist.
1174
Eric Snowca2d8542013-12-16 23:06:52 -07001175 .. deprecated:: 3.4
1176 The import machinery takes care of this automatically.
1177
Georg Brandl8a1caa22010-07-29 16:01:11 +00001178.. decorator:: set_package
Brett Cannon57b46f52009-03-02 14:38:26 +00001179
Brett Cannona22faca2013-05-28 17:50:14 -04001180 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module` to set the :attr:`__package__` attribute on the returned module. If :attr:`__package__`
1181 is set and has a value other than ``None`` it will not be changed.
Brett Cannon16248a42009-04-01 20:47:14 +00001182
Eric Snowca2d8542013-12-16 23:06:52 -07001183 .. deprecated:: 3.4
1184 The import machinery takes care of this automatically.
1185
Eric Snowb523f842013-11-22 09:05:39 -07001186.. function:: spec_from_loader(name, loader, *, origin=None, is_package=None)
1187
1188 A factory function for creating a :class:`ModuleSpec` instance based
1189 on a loader. The parameters have the same meaning as they do for
1190 ModuleSpec. The function uses available :term:`loader` APIs, such as
1191 :meth:`InspectLoader.is_package`, to fill in any missing
1192 information on the spec.
1193
1194 .. versionadded:: 3.4
1195
1196.. function:: spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)
1197
1198 A factory function for creating a :class:`ModuleSpec` instance based
1199 on the path to a file. Missing information will be filled in on the
1200 spec by making use of loader APIs and by the implication that the
1201 module will be file-based.
1202
1203 .. versionadded:: 3.4