blob: beac9d72b7c19f0814aad2dcf21e1f4744d1c83e [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 Cannon6eaac132014-05-09 12:28:22 -0400502 .. staticmethod:: source_to_code(data, path='<string>')
Brett Cannon9ffe85e2013-05-26 16:45:10 -0400503
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
Brett Cannon6eaac132014-05-09 12:28:22 -0400511 With the subsequent code object one can execute it in a module by
512 running ``exec(code, module.__dict__)``.
513
Brett Cannon9ffe85e2013-05-26 16:45:10 -0400514 .. versionadded:: 3.4
515
Brett Cannon6eaac132014-05-09 12:28:22 -0400516 .. versionchanged:: 3.5
517 Made the method static.
518
Eric Snowca2d8542013-12-16 23:06:52 -0700519 .. method:: exec_module(module)
520
521 Implementation of :meth:`Loader.exec_module`.
522
523 .. versionadded:: 3.4
524
Brett Cannon0dbb4c72013-05-31 18:56:47 -0400525 .. method:: load_module(fullname)
526
Eric Snowca2d8542013-12-16 23:06:52 -0700527 Implementation of :meth:`Loader.load_module`.
528
529 .. deprecated:: 3.4
530 use :meth:`exec_module` instead.
Brett Cannon0dbb4c72013-05-31 18:56:47 -0400531
Brett Cannon2a922ed2009-03-09 03:35:50 +0000532
Brett Cannon69194272009-07-20 04:23:48 +0000533.. class:: ExecutionLoader
534
535 An abstract base class which inherits from :class:`InspectLoader` that,
Brett Cannon23460292009-07-20 22:59:00 +0000536 when implemented, helps a module to be executed as a script. The ABC
Brett Cannon69194272009-07-20 04:23:48 +0000537 represents an optional :pep:`302` protocol.
538
539 .. method:: get_filename(fullname)
540
Brett Cannonf23e3742010-06-27 23:57:46 +0000541 An abstract method that is to return the value of :attr:`__file__` for
Brett Cannon69194272009-07-20 04:23:48 +0000542 the specified module. If no path is available, :exc:`ImportError` is
543 raised.
544
Brett Cannonf23e3742010-06-27 23:57:46 +0000545 If source code is available, then the method should return the path to
546 the source file, regardless of whether a bytecode was used to load the
547 module.
548
Brett Cannon100883f2013-04-09 16:59:39 -0400549 .. versionchanged:: 3.4
550 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
551
Brett Cannonf23e3742010-06-27 23:57:46 +0000552
Brett Cannon938d44d2012-04-22 19:58:33 -0400553.. class:: FileLoader(fullname, path)
554
555 An abstract base class which inherits from :class:`ResourceLoader` and
Andrew Svetlova60de4f2013-02-17 16:55:58 +0200556 :class:`ExecutionLoader`, providing concrete implementations of
Brett Cannon938d44d2012-04-22 19:58:33 -0400557 :meth:`ResourceLoader.get_data` and :meth:`ExecutionLoader.get_filename`.
558
559 The *fullname* argument is a fully resolved name of the module the loader is
560 to handle. The *path* argument is the path to the file for the module.
561
562 .. versionadded:: 3.3
563
564 .. attribute:: name
565
566 The name of the module the loader can handle.
567
568 .. attribute:: path
569
570 Path to the file of the module.
571
Barry Warsawd7d21942012-07-29 16:36:17 -0400572 .. method:: load_module(fullname)
Brett Cannonc0499522012-05-11 14:48:41 -0400573
Barry Warsawd7d21942012-07-29 16:36:17 -0400574 Calls super's ``load_module()``.
Brett Cannonc0499522012-05-11 14:48:41 -0400575
Eric Snowca2d8542013-12-16 23:06:52 -0700576 .. deprecated:: 3.4
577 Use :meth:`Loader.exec_module` instead.
578
Brett Cannon938d44d2012-04-22 19:58:33 -0400579 .. method:: get_filename(fullname)
580
Barry Warsawd7d21942012-07-29 16:36:17 -0400581 Returns :attr:`path`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400582
583 .. method:: get_data(path)
584
Brett Cannon3b62ca82013-05-27 21:11:04 -0400585 Reads *path* as a binary file and returns the bytes from it.
Brett Cannon938d44d2012-04-22 19:58:33 -0400586
587
Brett Cannonf23e3742010-06-27 23:57:46 +0000588.. class:: SourceLoader
589
590 An abstract base class for implementing source (and optionally bytecode)
591 file loading. The class inherits from both :class:`ResourceLoader` and
592 :class:`ExecutionLoader`, requiring the implementation of:
593
594 * :meth:`ResourceLoader.get_data`
595 * :meth:`ExecutionLoader.get_filename`
Brett Cannon6dfbff32010-07-21 09:48:31 +0000596 Should only return the path to the source file; sourceless
Brett Cannona81d5272013-06-16 19:17:12 -0400597 loading is not supported.
Brett Cannonf23e3742010-06-27 23:57:46 +0000598
599 The abstract methods defined by this class are to add optional bytecode
Brett Cannon5650e4f2012-11-18 10:03:31 -0500600 file support. Not implementing these optional methods (or causing them to
601 raise :exc:`NotImplementedError`) causes the loader to
Brett Cannonf23e3742010-06-27 23:57:46 +0000602 only work with source code. Implementing the methods allows the loader to
603 work with source *and* bytecode files; it does not allow for *sourceless*
604 loading where only bytecode is provided. Bytecode files are an
605 optimization to speed up loading by removing the parsing step of Python's
606 compiler, and so no bytecode-specific API is exposed.
607
Brett Cannon773468f2012-08-02 17:35:34 -0400608 .. method:: path_stats(path)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100609
610 Optional abstract method which returns a :class:`dict` containing
611 metadata about the specifed path. Supported dictionary keys are:
612
613 - ``'mtime'`` (mandatory): an integer or floating-point number
614 representing the modification time of the source code;
615 - ``'size'`` (optional): the size in bytes of the source code.
616
617 Any other keys in the dictionary are ignored, to allow for future
Andrew Svetlov08af0002014-04-01 01:13:30 +0300618 extensions. If the path cannot be handled, :exc:`OSError` is raised.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100619
620 .. versionadded:: 3.3
621
Brett Cannon100883f2013-04-09 16:59:39 -0400622 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300623 Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
Brett Cannon100883f2013-04-09 16:59:39 -0400624
Brett Cannon773468f2012-08-02 17:35:34 -0400625 .. method:: path_mtime(path)
Brett Cannonf23e3742010-06-27 23:57:46 +0000626
627 Optional abstract method which returns the modification time for the
628 specified path.
629
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100630 .. deprecated:: 3.3
631 This method is deprecated in favour of :meth:`path_stats`. You don't
632 have to implement it, but it is still available for compatibility
Andrew Svetlov08af0002014-04-01 01:13:30 +0300633 purposes. Raise :exc:`OSError` if the path cannot be handled.
Brett Cannon100883f2013-04-09 16:59:39 -0400634
Georg Brandldf48b972014-03-24 09:06:18 +0100635 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300636 Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100637
Brett Cannon773468f2012-08-02 17:35:34 -0400638 .. method:: set_data(path, data)
Brett Cannonf23e3742010-06-27 23:57:46 +0000639
640 Optional abstract method which writes the specified bytes to a file
Brett Cannon61b14252010-07-03 21:48:25 +0000641 path. Any intermediate directories which do not exist are to be created
642 automatically.
643
644 When writing to the path fails because the path is read-only
Brett Cannon2cefb3c2013-05-25 11:26:11 -0400645 (:attr:`errno.EACCES`/:exc:`PermissionError`), do not propagate the
646 exception.
Brett Cannonf23e3742010-06-27 23:57:46 +0000647
Brett Cannon100883f2013-04-09 16:59:39 -0400648 .. versionchanged:: 3.4
649 No longer raises :exc:`NotImplementedError` when called.
650
Brett Cannon773468f2012-08-02 17:35:34 -0400651 .. method:: get_code(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000652
653 Concrete implementation of :meth:`InspectLoader.get_code`.
654
Eric Snowca2d8542013-12-16 23:06:52 -0700655 .. method:: exec_module(module)
656
657 Concrete implementation of :meth:`Loader.exec_module`.
658
659 .. versionadded:: 3.4
660
Brett Cannon773468f2012-08-02 17:35:34 -0400661 .. method:: load_module(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000662
Eric Snowca2d8542013-12-16 23:06:52 -0700663 Concrete implementation of :meth:`Loader.load_module`.
664
665 .. deprecated:: 3.4
666 Use :meth:`exec_module` instead.
Brett Cannonf23e3742010-06-27 23:57:46 +0000667
Brett Cannon773468f2012-08-02 17:35:34 -0400668 .. method:: get_source(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000669
670 Concrete implementation of :meth:`InspectLoader.get_source`.
671
Brett Cannon773468f2012-08-02 17:35:34 -0400672 .. method:: is_package(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000673
674 Concrete implementation of :meth:`InspectLoader.is_package`. A module
Brett Cannonea0b8232012-06-15 20:00:53 -0400675 is determined to be a package if its file path (as provided by
676 :meth:`ExecutionLoader.get_filename`) is a file named
677 ``__init__`` when the file extension is removed **and** the module name
678 itself does not end in ``__init__``.
Brett Cannonf23e3742010-06-27 23:57:46 +0000679
Brett Cannon69194272009-07-20 04:23:48 +0000680
Brett Cannon78246b62009-01-25 04:56:30 +0000681:mod:`importlib.machinery` -- Importers and path hooks
682------------------------------------------------------
683
684.. module:: importlib.machinery
685 :synopsis: Importers and path hooks
686
687This module contains the various objects that help :keyword:`import`
688find and load modules.
689
Brett Cannoncb66eb02012-05-11 12:58:42 -0400690.. attribute:: SOURCE_SUFFIXES
691
692 A list of strings representing the recognized file suffixes for source
693 modules.
694
695 .. versionadded:: 3.3
696
697.. attribute:: DEBUG_BYTECODE_SUFFIXES
698
699 A list of strings representing the file suffixes for non-optimized bytecode
700 modules.
701
702 .. versionadded:: 3.3
703
704.. attribute:: OPTIMIZED_BYTECODE_SUFFIXES
705
706 A list of strings representing the file suffixes for optimized bytecode
707 modules.
708
709 .. versionadded:: 3.3
710
711.. attribute:: BYTECODE_SUFFIXES
712
713 A list of strings representing the recognized file suffixes for bytecode
714 modules. Set to either :attr:`DEBUG_BYTECODE_SUFFIXES` or
715 :attr:`OPTIMIZED_BYTECODE_SUFFIXES` based on whether ``__debug__`` is true.
716
717 .. versionadded:: 3.3
718
719.. attribute:: EXTENSION_SUFFIXES
720
Nick Coghlan76e07702012-07-18 23:14:57 +1000721 A list of strings representing the recognized file suffixes for
Brett Cannoncb66eb02012-05-11 12:58:42 -0400722 extension modules.
723
724 .. versionadded:: 3.3
725
Nick Coghlanc5afd422012-07-18 23:59:08 +1000726.. function:: all_suffixes()
Nick Coghlan76e07702012-07-18 23:14:57 +1000727
728 Returns a combined list of strings representing all file suffixes for
Nick Coghlanc5afd422012-07-18 23:59:08 +1000729 modules recognized by the standard import machinery. This is a
Nick Coghlan76e07702012-07-18 23:14:57 +1000730 helper for code which simply needs to know if a filesystem path
Nick Coghlanc5afd422012-07-18 23:59:08 +1000731 potentially refers to a module without needing any details on the kind
732 of module (for example, :func:`inspect.getmodulename`)
Nick Coghlan76e07702012-07-18 23:14:57 +1000733
734 .. versionadded:: 3.3
735
736
Brett Cannon78246b62009-01-25 04:56:30 +0000737.. class:: BuiltinImporter
738
Brett Cannon2a922ed2009-03-09 03:35:50 +0000739 An :term:`importer` for built-in modules. All known built-in modules are
740 listed in :data:`sys.builtin_module_names`. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000741 :class:`importlib.abc.MetaPathFinder` and
742 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000743
744 Only class methods are defined by this class to alleviate the need for
745 instantiation.
746
Eric Snowca2d8542013-12-16 23:06:52 -0700747 .. note::
748 Due to limitations in the extension module C-API, for now
749 BuiltinImporter does not implement :meth:`Loader.exec_module`.
750
Brett Cannon78246b62009-01-25 04:56:30 +0000751
752.. class:: FrozenImporter
753
Brett Cannon2a922ed2009-03-09 03:35:50 +0000754 An :term:`importer` for frozen modules. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000755 :class:`importlib.abc.MetaPathFinder` and
756 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000757
758 Only class methods are defined by this class to alleviate the need for
759 instantiation.
760
Brett Cannondebb98d2009-02-16 04:18:01 +0000761
Nick Coghlanff794862012-08-02 21:45:24 +1000762.. class:: WindowsRegistryFinder
763
764 :term:`Finder` for modules declared in the Windows registry. This class
Nick Coghlan49417742012-08-02 23:03:58 +1000765 implements the :class:`importlib.abc.Finder` ABC.
Nick Coghlanff794862012-08-02 21:45:24 +1000766
767 Only class methods are defined by this class to alleviate the need for
768 instantiation.
769
770 .. versionadded:: 3.3
771
772
Brett Cannondebb98d2009-02-16 04:18:01 +0000773.. class:: PathFinder
774
Brett Cannon1b799182012-08-17 14:08:24 -0400775 A :term:`Finder` for :data:`sys.path` and package ``__path__`` attributes.
776 This class implements the :class:`importlib.abc.MetaPathFinder` ABC.
Brett Cannondebb98d2009-02-16 04:18:01 +0000777
Brett Cannon1b799182012-08-17 14:08:24 -0400778 Only class methods are defined by this class to alleviate the need for
779 instantiation.
Brett Cannondebb98d2009-02-16 04:18:01 +0000780
Eric Snowca2d8542013-12-16 23:06:52 -0700781 .. classmethod:: find_spec(fullname, path=None, target=None)
782
783 Class method that attempts to find a :term:`spec <module spec>`
784 for the module specified by *fullname* on :data:`sys.path` or, if
785 defined, on *path*. For each path entry that is searched,
786 :data:`sys.path_importer_cache` is checked. If a non-false object
787 is found then it is used as the :term:`path entry finder` to look
788 for the module being searched for. If no entry is found in
789 :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
790 searched for a finder for the path entry and, if found, is stored
791 in :data:`sys.path_importer_cache` along with being queried about
792 the module. If no finder is ever found then ``None`` is both
793 stored in the cache and returned.
794
795 .. versionadded:: 3.4
796
Brett Cannon1b799182012-08-17 14:08:24 -0400797 .. classmethod:: find_module(fullname, path=None)
Brett Cannondebb98d2009-02-16 04:18:01 +0000798
Eric Snowca2d8542013-12-16 23:06:52 -0700799 A legacy wrapper around :meth:`find_spec`.
800
801 .. deprecated:: 3.4
802 Use :meth:`find_spec` instead.
Brett Cannond2e7b332009-02-17 02:45:03 +0000803
Brett Cannonf4dc9202012-08-10 12:21:12 -0400804 .. classmethod:: invalidate_caches()
805
Eric Snowca2d8542013-12-16 23:06:52 -0700806 Calls :meth:`importlib.abc.PathEntryFinder.invalidate_caches` on all
807 finders stored in :attr:`sys.path_importer_cache`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400808
Eric Snowca2d8542013-12-16 23:06:52 -0700809 .. versionchanged:: 3.4
810 Calls objects in :data:`sys.path_hooks` with the current working
811 directory for ``''`` (i.e. the empty string).
Brett Cannon27e27f72013-10-18 11:39:04 -0400812
Brett Cannond2e7b332009-02-17 02:45:03 +0000813
Brett Cannon938d44d2012-04-22 19:58:33 -0400814.. class:: FileFinder(path, \*loader_details)
815
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000816 A concrete implementation of :class:`importlib.abc.PathEntryFinder` which
817 caches results from the file system.
Brett Cannon938d44d2012-04-22 19:58:33 -0400818
819 The *path* argument is the directory for which the finder is in charge of
820 searching.
821
Brett Cannonac9f2f32012-08-10 13:47:54 -0400822 The *loader_details* argument is a variable number of 2-item tuples each
823 containing a loader and a sequence of file suffixes the loader recognizes.
Brett Cannon29b2f172013-06-21 18:31:55 -0400824 The loaders are expected to be callables which accept two arguments of
825 the module's name and the path to the file found.
Brett Cannon938d44d2012-04-22 19:58:33 -0400826
827 The finder will cache the directory contents as necessary, making stat calls
828 for each module search to verify the cache is not outdated. Because cache
829 staleness relies upon the granularity of the operating system's state
830 information of the file system, there is a potential race condition of
831 searching for a module, creating a new file, and then searching for the
832 module the new file represents. If the operations happen fast enough to fit
833 within the granularity of stat calls, then the module search will fail. To
834 prevent this from happening, when you create a module dynamically, make sure
835 to call :func:`importlib.invalidate_caches`.
836
837 .. versionadded:: 3.3
838
839 .. attribute:: path
840
841 The path the finder will search in.
842
Eric Snowca2d8542013-12-16 23:06:52 -0700843 .. method:: find_spec(fullname, target=None)
844
845 Attempt to find the spec to handle *fullname* within :attr:`path`.
846
847 .. versionadded:: 3.4
848
Brett Cannon1d753822013-06-16 19:06:55 -0400849 .. method:: find_loader(fullname)
Brett Cannon938d44d2012-04-22 19:58:33 -0400850
851 Attempt to find the loader to handle *fullname* within :attr:`path`.
852
853 .. method:: invalidate_caches()
854
855 Clear out the internal cache.
856
857 .. classmethod:: path_hook(\*loader_details)
858
859 A class method which returns a closure for use on :attr:`sys.path_hooks`.
860 An instance of :class:`FileFinder` is returned by the closure using the
861 path argument given to the closure directly and *loader_details*
862 indirectly.
863
864 If the argument to the closure is not an existing directory,
865 :exc:`ImportError` is raised.
866
867
868.. class:: SourceFileLoader(fullname, path)
869
870 A concrete implementation of :class:`importlib.abc.SourceLoader` by
871 subclassing :class:`importlib.abc.FileLoader` and providing some concrete
872 implementations of other methods.
873
874 .. versionadded:: 3.3
875
876 .. attribute:: name
877
878 The name of the module that this loader will handle.
879
880 .. attribute:: path
881
882 The path to the source file.
883
884 .. method:: is_package(fullname)
885
886 Return true if :attr:`path` appears to be for a package.
887
888 .. method:: path_stats(path)
889
890 Concrete implementation of :meth:`importlib.abc.SourceLoader.path_stats`.
891
892 .. method:: set_data(path, data)
893
894 Concrete implementation of :meth:`importlib.abc.SourceLoader.set_data`.
895
Brett Cannon062fcac2014-05-09 11:55:49 -0400896 .. method:: load_module(name=None)
897
898 Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
899 specifying the name of the module to load is optional.
900
Brett Cannon938d44d2012-04-22 19:58:33 -0400901
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200902.. class:: SourcelessFileLoader(fullname, path)
Brett Cannon938d44d2012-04-22 19:58:33 -0400903
904 A concrete implementation of :class:`importlib.abc.FileLoader` which can
905 import bytecode files (i.e. no source code files exist).
906
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200907 Please note that direct use of bytecode files (and thus not source code
908 files) inhibits your modules from being usable by all Python
909 implementations or new versions of Python which change the bytecode
910 format.
Brett Cannon938d44d2012-04-22 19:58:33 -0400911
912 .. versionadded:: 3.3
913
914 .. attribute:: name
915
916 The name of the module the loader will handle.
917
918 .. attribute:: path
919
920 The path to the bytecode file.
921
922 .. method:: is_package(fullname)
923
924 Determines if the module is a package based on :attr:`path`.
925
926 .. method:: get_code(fullname)
927
928 Returns the code object for :attr:`name` created from :attr:`path`.
929
930 .. method:: get_source(fullname)
931
932 Returns ``None`` as bytecode files have no source when this loader is
933 used.
934
Brett Cannon062fcac2014-05-09 11:55:49 -0400935 .. method:: load_module(name=None)
936
937 Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
938 specifying the name of the module to load is optional.
939
Brett Cannon938d44d2012-04-22 19:58:33 -0400940
941.. class:: ExtensionFileLoader(fullname, path)
942
Eric Snow51794452013-10-03 12:08:55 -0600943 A concrete implementation of :class:`importlib.abc.ExecutionLoader` for
Brett Cannon938d44d2012-04-22 19:58:33 -0400944 extension modules.
945
946 The *fullname* argument specifies the name of the module the loader is to
947 support. The *path* argument is the path to the extension module's file.
948
949 .. versionadded:: 3.3
950
951 .. attribute:: name
952
953 Name of the module the loader supports.
954
955 .. attribute:: path
956
957 Path to the extension module.
958
Brett Cannon062fcac2014-05-09 11:55:49 -0400959 .. method:: load_module(name=None)
Brett Cannon938d44d2012-04-22 19:58:33 -0400960
Brett Cannonc0499522012-05-11 14:48:41 -0400961 Loads the extension module if and only if *fullname* is the same as
962 :attr:`name` or is ``None``.
Brett Cannon938d44d2012-04-22 19:58:33 -0400963
Eric Snowca2d8542013-12-16 23:06:52 -0700964 .. note::
965 Due to limitations in the extension module C-API, for now
966 ExtensionFileLoader does not implement :meth:`Loader.exec_module`.
967
Brett Cannon938d44d2012-04-22 19:58:33 -0400968 .. method:: is_package(fullname)
969
Brett Cannonac9f2f32012-08-10 13:47:54 -0400970 Returns ``True`` if the file path points to a package's ``__init__``
971 module based on :attr:`EXTENSION_SUFFIXES`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400972
973 .. method:: get_code(fullname)
974
975 Returns ``None`` as extension modules lack a code object.
976
977 .. method:: get_source(fullname)
978
979 Returns ``None`` as extension modules do not have source code.
980
Eric Snow51794452013-10-03 12:08:55 -0600981 .. method:: get_filename(fullname)
982
983 Returns :attr:`path`.
984
Eric Snowdcd01b42013-10-04 20:35:34 -0600985 .. versionadded:: 3.4
986
Brett Cannon938d44d2012-04-22 19:58:33 -0400987
Eric Snowb523f842013-11-22 09:05:39 -0700988.. class:: ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)
989
990 A specification for a module's import-system-related state.
991
992 .. versionadded:: 3.4
993
994 .. attribute:: name
995
996 (``__name__``)
997
998 A string for the fully-qualified name of the module.
999
1000 .. attribute:: loader
1001
1002 (``__loader__``)
1003
1004 The loader to use for loading. For namespace packages this should be
1005 set to None.
1006
1007 .. attribute:: origin
1008
1009 (``__file__``)
1010
1011 Name of the place from which the module is loaded, e.g. "builtin" for
1012 built-in modules and the filename for modules loaded from source.
1013 Normally "origin" should be set, but it may be None (the default)
1014 which indicates it is unspecified.
1015
1016 .. attribute:: submodule_search_locations
1017
1018 (``__path__``)
1019
1020 List of strings for where to find submodules, if a package (None
1021 otherwise).
1022
1023 .. attribute:: loader_state
1024
1025 Container of extra module-specific data for use during loading (or
1026 None).
1027
1028 .. attribute:: cached
1029
1030 (``__cached__``)
1031
1032 String for where the compiled module should be stored (or None).
1033
1034 .. attribute:: parent
1035
1036 (``__package__``)
1037
1038 (Read-only) Fully-qualified name of the package to which the module
1039 belongs as a submodule (or None).
1040
1041 .. attribute:: has_location
1042
Eric Snowb282b3d2013-12-10 22:16:41 -07001043 Boolean indicating whether or not the module's "origin"
Eric Snowb523f842013-11-22 09:05:39 -07001044 attribute refers to a loadable location.
1045
Brett Cannond2e7b332009-02-17 02:45:03 +00001046:mod:`importlib.util` -- Utility code for importers
1047---------------------------------------------------
1048
1049.. module:: importlib.util
Brett Cannon75321e82012-03-02 11:58:25 -05001050 :synopsis: Utility code for importers
Brett Cannond2e7b332009-02-17 02:45:03 +00001051
1052This module contains the various objects that help in the construction of
1053an :term:`importer`.
1054
Brett Cannon05a647d2013-06-14 19:02:34 -04001055.. attribute:: MAGIC_NUMBER
1056
1057 The bytes which represent the bytecode version number. If you need help with
1058 loading/writing bytecode then consider :class:`importlib.abc.SourceLoader`.
1059
1060 .. versionadded:: 3.4
1061
Brett Cannona3c96152013-06-14 22:26:30 -04001062.. function:: cache_from_source(path, debug_override=None)
1063
1064 Return the :pep:`3147` path to the byte-compiled file associated with the
1065 source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return
1066 value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.
1067 The ``cpython-32`` string comes from the current magic tag (see
1068 :func:`get_tag`; if :attr:`sys.implementation.cache_tag` is not defined then
1069 :exc:`NotImplementedError` will be raised). The returned path will end in
Serhiy Storchaka0e90e992013-11-29 12:19:53 +02001070 ``.pyc`` when ``__debug__`` is ``True`` or ``.pyo`` for an optimized Python
1071 (i.e. ``__debug__`` is ``False``). By passing in ``True`` or ``False`` for
Brett Cannona3c96152013-06-14 22:26:30 -04001072 *debug_override* you can override the system's value for ``__debug__`` for
1073 extension selection.
1074
1075 *path* need not exist.
1076
1077 .. versionadded:: 3.4
1078
1079
1080.. function:: source_from_cache(path)
1081
1082 Given the *path* to a :pep:`3147` file name, return the associated source code
1083 file path. For example, if *path* is
1084 ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be
1085 ``/foo/bar/baz.py``. *path* need not exist, however if it does not conform
1086 to :pep:`3147` format, a ``ValueError`` is raised. If
1087 :attr:`sys.implementation.cache_tag` is not defined,
1088 :exc:`NotImplementedError` is raised.
1089
1090 .. versionadded:: 3.4
1091
Brett Cannonf24fecd2013-06-16 18:37:53 -04001092.. function:: decode_source(source_bytes)
1093
1094 Decode the given bytes representing source code and return it as a string
1095 with universal newlines (as required by
1096 :meth:`importlib.abc.InspectLoader.get_source`).
1097
1098 .. versionadded:: 3.4
1099
Brett Cannond200bf52012-05-13 13:45:09 -04001100.. function:: resolve_name(name, package)
1101
1102 Resolve a relative module name to an absolute one.
1103
1104 If **name** has no leading dots, then **name** is simply returned. This
1105 allows for usage such as
1106 ``importlib.util.resolve_name('sys', __package__)`` without doing a
1107 check to see if the **package** argument is needed.
1108
1109 :exc:`ValueError` is raised if **name** is a relative module name but
1110 package is a false value (e.g. ``None`` or the empty string).
1111 :exc:`ValueError` is also raised a relative name would escape its containing
1112 package (e.g. requesting ``..bacon`` from within the ``spam`` package).
1113
1114 .. versionadded:: 3.3
1115
Eric Snow6029e082014-01-25 15:32:46 -07001116.. function:: find_spec(name, package=None)
1117
1118 Find the :term:`spec <module spec>` for a module, optionally relative to
1119 the specified **package** name. If the module is in :attr:`sys.modules`,
1120 then ``sys.modules[name].__spec__`` is returned (unless the spec would be
1121 ``None`` or is not set, in which case :exc:`ValueError` is raised).
1122 Otherwise a search using :attr:`sys.meta_path` is done. ``None`` is
1123 returned if no spec is found.
1124
1125 If **name** is for a submodule (contains a dot), the parent module is
1126 automatically imported.
1127
1128 **name** and **package** work the same as for :func:`import_module`.
1129
1130 .. versionadded:: 3.4
1131
Brett Cannon2a17bde2014-05-30 14:55:29 -04001132.. function:: module_from_spec(spec)
1133
1134 Create a new module based on **spec**.
1135
1136 If the module object is from ``spec.loader.create_module()``, then any
1137 pre-existing attributes will not be reset. Also, no :exc:`AttributeError`
1138 will be raised if triggered while accessing **spec** or setting an attribute
1139 on the module.
1140
1141 This function is preferred over using :class:`types.ModuleType` to create a
1142 new module as **spec** is used to set as many import-controlled attributes on
1143 the module as possible.
1144
1145 .. versionadded:: 3.5
1146
Georg Brandl8a1caa22010-07-29 16:01:11 +00001147.. decorator:: module_for_loader
Brett Cannond2e7b332009-02-17 02:45:03 +00001148
Brett Cannona22faca2013-05-28 17:50:14 -04001149 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
Guido van Rossum09613542009-03-30 20:34:57 +00001150 to handle selecting the proper
Brett Cannond2e7b332009-02-17 02:45:03 +00001151 module object to load with. The decorated method is expected to have a call
Brett Cannon2a922ed2009-03-09 03:35:50 +00001152 signature taking two positional arguments
1153 (e.g. ``load_module(self, module)``) for which the second argument
Guido van Rossum09613542009-03-30 20:34:57 +00001154 will be the module **object** to be used by the loader.
Brett Cannonefad00d2012-04-27 17:27:14 -04001155 Note that the decorator will not work on static methods because of the
1156 assumption of two arguments.
Brett Cannond2e7b332009-02-17 02:45:03 +00001157
Guido van Rossum09613542009-03-30 20:34:57 +00001158 The decorated method will take in the **name** of the module to be loaded
1159 as expected for a :term:`loader`. If the module is not found in
Brett Cannon3dc48d62013-05-28 18:35:54 -04001160 :data:`sys.modules` then a new one is constructed. Regardless of where the
1161 module came from, :attr:`__loader__` set to **self** and :attr:`__package__`
1162 is set based on what :meth:`importlib.abc.InspectLoader.is_package` returns
1163 (if available). These attributes are set unconditionally to support
1164 reloading.
Brett Cannonefad00d2012-04-27 17:27:14 -04001165
1166 If an exception is raised by the decorated method and a module was added to
Brett Cannona87e31c2013-09-13 16:52:19 -04001167 :data:`sys.modules`, then the module will be removed to prevent a partially
1168 initialized module from being in left in :data:`sys.modules`. If the module
1169 was already in :data:`sys.modules` then it is left alone.
Brett Cannond2e7b332009-02-17 02:45:03 +00001170
Brett Cannonefad00d2012-04-27 17:27:14 -04001171 .. versionchanged:: 3.3
Georg Brandl61063cc2012-06-24 22:48:30 +02001172 :attr:`__loader__` and :attr:`__package__` are automatically set
1173 (when possible).
Brett Cannon57b46f52009-03-02 14:38:26 +00001174
Brett Cannon3dc48d62013-05-28 18:35:54 -04001175 .. versionchanged:: 3.4
Brett Cannon0dbb4c72013-05-31 18:56:47 -04001176 Set :attr:`__name__`, :attr:`__loader__` :attr:`__package__`
1177 unconditionally to support reloading.
1178
1179 .. deprecated:: 3.4
Eric Snowb523f842013-11-22 09:05:39 -07001180 The import machinery now directly performs all the functionality
1181 provided by this function.
Brett Cannon3dc48d62013-05-28 18:35:54 -04001182
Georg Brandl8a1caa22010-07-29 16:01:11 +00001183.. decorator:: set_loader
Brett Cannon2cf03a82009-03-10 05:17:37 +00001184
Brett Cannona22faca2013-05-28 17:50:14 -04001185 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
1186 to set the :attr:`__loader__`
1187 attribute on the returned module. If the attribute is already set the
1188 decorator does nothing. It is assumed that the first positional argument to
1189 the wrapped method (i.e. ``self``) is what :attr:`__loader__` should be set
1190 to.
Brett Cannon2cf03a82009-03-10 05:17:37 +00001191
Brett Cannon4802bec2013-03-13 10:41:36 -07001192 .. versionchanged:: 3.4
Brett Cannon4c14b5d2013-05-04 13:56:58 -04001193 Set ``__loader__`` if set to ``None``, as if the attribute does not
Brett Cannon4802bec2013-03-13 10:41:36 -07001194 exist.
1195
Eric Snowca2d8542013-12-16 23:06:52 -07001196 .. deprecated:: 3.4
1197 The import machinery takes care of this automatically.
1198
Georg Brandl8a1caa22010-07-29 16:01:11 +00001199.. decorator:: set_package
Brett Cannon57b46f52009-03-02 14:38:26 +00001200
Brett Cannona22faca2013-05-28 17:50:14 -04001201 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module` to set the :attr:`__package__` attribute on the returned module. If :attr:`__package__`
1202 is set and has a value other than ``None`` it will not be changed.
Brett Cannon16248a42009-04-01 20:47:14 +00001203
Eric Snowca2d8542013-12-16 23:06:52 -07001204 .. deprecated:: 3.4
1205 The import machinery takes care of this automatically.
1206
Eric Snowb523f842013-11-22 09:05:39 -07001207.. function:: spec_from_loader(name, loader, *, origin=None, is_package=None)
1208
1209 A factory function for creating a :class:`ModuleSpec` instance based
1210 on a loader. The parameters have the same meaning as they do for
1211 ModuleSpec. The function uses available :term:`loader` APIs, such as
1212 :meth:`InspectLoader.is_package`, to fill in any missing
1213 information on the spec.
1214
1215 .. versionadded:: 3.4
1216
1217.. function:: spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)
1218
1219 A factory function for creating a :class:`ModuleSpec` instance based
1220 on the path to a file. Missing information will be filled in on the
1221 spec by making use of loader APIs and by the implication that the
1222 module will be file-based.
1223
1224 .. versionadded:: 3.4
Brett Cannona04dbe42014-04-04 13:53:38 -04001225
1226.. class:: LazyLoader(loader)
1227
1228 A class which postpones the execution of the loader of a module until the
1229 module has an attribute accessed.
1230
1231 This class **only** works with loaders that define
1232 :meth:`importlib.abc.Loader.exec_module` as control over what module type
1233 is used for the module is required. For the same reasons, the loader
1234 **cannot** define :meth:`importlib.abc.Loader.create_module`. Finally,
1235 modules which substitute the object placed into :attr:`sys.modules` will
1236 not work as there is no way to properly replace the module references
1237 throughout the interpreter safely; :exc:`ValueError` is raised if such a
1238 substitution is detected.
1239
1240 .. note::
1241 For projects where startup time is critical, this class allows for
1242 potentially minimizing the cost of loading a module if it is never used.
1243 For projects where startup time is not essential then use of this class is
1244 **heavily** discouraged due to error messages created during loading being
1245 postponed and thus occurring out of context.
1246
1247 .. versionadded:: 3.5
1248
1249 .. classmethod:: factory(loader)
1250
1251 A static method which returns a callable that creates a lazy loader. This
1252 is meant to be used in situations where the loader is passed by class
1253 instead of by instance.
1254 ::
1255
1256 suffixes = importlib.machinery.SOURCE_SUFFIXES
1257 loader = importlib.machinery.SourceFileLoader
1258 lazy_loader = importlib.util.LazyLoader.factory(loader)
1259 finder = importlib.machinery.FileFinder(path, [(lazy_loader, suffixes)])