blob: 953e21b3a3569c039a95763b4a827fe768b0ed32 [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
Eric Snow338502b2016-05-28 11:56:53 -060055 :pep:`420`
56 Implicit namespace packages
57
Brett Cannon07fbd782014-02-06 09:46:08 -050058 :pep:`451`
59 A ModuleSpec Type for the Import System
60
Nick Coghland5cacbb2015-05-23 22:24:10 +100061 :pep:`488`
62 Elimination of PYO files
63
64 :pep:`489`
65 Multi-phase extension module initialization
66
Brett Cannon8917d5e2010-01-13 19:21:00 +000067 :pep:`3120`
Brett Cannonafccd632009-01-20 02:21:27 +000068 Using UTF-8 as the Default Source Encoding
69
Brett Cannon30b7a902010-06-27 21:49:22 +000070 :pep:`3147`
71 PYC Repository Directories
72
Brett Cannonafccd632009-01-20 02:21:27 +000073
74Functions
75---------
76
Brett Cannoncb4996a2012-08-06 16:34:44 -040077.. function:: __import__(name, globals=None, locals=None, fromlist=(), level=0)
Brett Cannonafccd632009-01-20 02:21:27 +000078
Brett Cannonf23e3742010-06-27 23:57:46 +000079 An implementation of the built-in :func:`__import__` function.
Brett Cannonafccd632009-01-20 02:21:27 +000080
Brett Cannon3fa84222015-02-20 10:34:20 -050081 .. note::
82 Programmatic importing of modules should use :func:`import_module`
83 instead of this function.
84
Brett Cannonafccd632009-01-20 02:21:27 +000085.. function:: import_module(name, package=None)
86
Brett Cannon33418c82009-01-22 18:37:20 +000087 Import a module. The *name* argument specifies what module to
Brett Cannonafccd632009-01-20 02:21:27 +000088 import in absolute or relative terms
89 (e.g. either ``pkg.mod`` or ``..mod``). If the name is
Guido van Rossum09613542009-03-30 20:34:57 +000090 specified in relative terms, then the *package* argument must be set to
91 the name of the package which is to act as the anchor for resolving the
Brett Cannonafccd632009-01-20 02:21:27 +000092 package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
Brett Cannon2c318a12009-02-07 01:15:27 +000093 ``pkg.mod``).
Brett Cannon78246b62009-01-25 04:56:30 +000094
Brett Cannon2c318a12009-02-07 01:15:27 +000095 The :func:`import_module` function acts as a simplifying wrapper around
Brett Cannon9f4cb1c2009-04-01 23:26:47 +000096 :func:`importlib.__import__`. This means all semantics of the function are
Brett Cannon3fa84222015-02-20 10:34:20 -050097 derived from :func:`importlib.__import__`. The most important difference
98 between these two functions is that :func:`import_module` returns the
99 specified package or module (e.g. ``pkg.mod``), while :func:`__import__`
100 returns the top-level package or module (e.g. ``pkg``).
101
102 If you are dynamically importing a module that was created since the
103 interpreter began execution (e.g., created a Python source file), you may
104 need to call :func:`invalidate_caches` in order for the new module to be
105 noticed by the import system.
Guido van Rossum09613542009-03-30 20:34:57 +0000106
Brett Cannon98620d82013-12-13 13:57:41 -0500107 .. versionchanged:: 3.3
108 Parent packages are automatically imported.
109
Brett Cannonee78a2b2012-05-12 17:43:17 -0400110.. function:: find_loader(name, path=None)
111
112 Find the loader for a module, optionally within the specified *path*. If the
113 module is in :attr:`sys.modules`, then ``sys.modules[name].__loader__`` is
Brett Cannon32799232013-03-13 11:09:08 -0700114 returned (unless the loader would be ``None`` or is not set, in which case
Brett Cannonee78a2b2012-05-12 17:43:17 -0400115 :exc:`ValueError` is raised). Otherwise a search using :attr:`sys.meta_path`
116 is done. ``None`` is returned if no loader is found.
117
Brett Cannon56b4ca72012-11-17 09:30:55 -0500118 A dotted name does not have its parent's implicitly imported as that requires
119 loading them and that may not be desired. To properly import a submodule you
120 will need to import all parent packages of the submodule and use the correct
121 argument to *path*.
Brett Cannonee78a2b2012-05-12 17:43:17 -0400122
Brett Cannon32799232013-03-13 11:09:08 -0700123 .. versionadded:: 3.3
124
125 .. versionchanged:: 3.4
126 If ``__loader__`` is not set, raise :exc:`ValueError`, just like when the
127 attribute is set to ``None``.
128
Eric Snowca2d8542013-12-16 23:06:52 -0700129 .. deprecated:: 3.4
Eric Snow6029e082014-01-25 15:32:46 -0700130 Use :func:`importlib.util.find_spec` instead.
Eric Snowca2d8542013-12-16 23:06:52 -0700131
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100132.. function:: invalidate_caches()
133
Brett Cannonf4dc9202012-08-10 12:21:12 -0400134 Invalidate the internal caches of finders stored at
135 :data:`sys.meta_path`. If a finder implements ``invalidate_caches()`` then it
Brett Cannon4067aa22013-04-27 23:20:32 -0400136 will be called to perform the invalidation. This function should be called
137 if any modules are created/installed while your program is running to
138 guarantee all finders will notice the new module's existence.
Antoine Pitrouc541f8e2012-02-20 01:48:16 +0100139
140 .. versionadded:: 3.3
141
Brett Cannon3fe35e62013-06-14 15:04:26 -0400142.. function:: reload(module)
143
144 Reload a previously imported *module*. The argument must be a module object,
145 so it must have been successfully imported before. This is useful if you
146 have edited the module source file using an external editor and want to try
147 out the new version without leaving the Python interpreter. The return value
Brett Cannon8ad37862013-10-25 13:52:46 -0400148 is the module object (which can be different if re-importing causes a
149 different object to be placed in :data:`sys.modules`).
Brett Cannon3fe35e62013-06-14 15:04:26 -0400150
Brett Cannon8ad37862013-10-25 13:52:46 -0400151 When :func:`reload` is executed:
Brett Cannon3fe35e62013-06-14 15:04:26 -0400152
Larry Hastings3732ed22014-03-15 21:13:56 -0700153 * Python module's code is recompiled and the module-level code re-executed,
Brett Cannon3fe35e62013-06-14 15:04:26 -0400154 defining a new set of objects which are bound to names in the module's
155 dictionary by reusing the :term:`loader` which originally loaded the
156 module. The ``init`` function of extension modules is not called a second
157 time.
158
159 * As with all other objects in Python the old objects are only reclaimed
160 after their reference counts drop to zero.
161
162 * The names in the module namespace are updated to point to any new or
163 changed objects.
164
165 * Other references to the old objects (such as names external to the module) are
166 not rebound to refer to the new objects and must be updated in each namespace
167 where they occur if that is desired.
168
169 There are a number of other caveats:
170
Brett Cannon3fe35e62013-06-14 15:04:26 -0400171 When a module is reloaded, its dictionary (containing the module's global
172 variables) is retained. Redefinitions of names will override the old
173 definitions, so this is generally not a problem. If the new version of a
174 module does not define a name that was defined by the old version, the old
175 definition remains. This feature can be used to the module's advantage if it
176 maintains a global table or cache of objects --- with a :keyword:`try`
177 statement it can test for the table's presence and skip its initialization if
178 desired::
179
180 try:
181 cache
182 except NameError:
183 cache = {}
184
Robert Collins1ae28d22015-08-05 08:20:53 +1200185 It is generally not very useful to reload built-in or dynamically loaded
186 modules. Reloading :mod:`sys`, :mod:`__main__`, :mod:`builtins` and other
187 key modules is not recommended. In many cases extension modules are not
188 designed to be initialized more than once, and may fail in arbitrary ways
189 when reloaded.
Brett Cannon3fe35e62013-06-14 15:04:26 -0400190
191 If a module imports objects from another module using :keyword:`from` ...
192 :keyword:`import` ..., calling :func:`reload` for the other module does not
193 redefine the objects imported from it --- one way around this is to
194 re-execute the :keyword:`from` statement, another is to use :keyword:`import`
195 and qualified names (*module.name*) instead.
196
197 If a module instantiates instances of a class, reloading the module that
198 defines the class does not affect the method definitions of the instances ---
199 they continue to use the old class definition. The same is true for derived
200 classes.
201
202 .. versionadded:: 3.4
203
Brett Cannon78246b62009-01-25 04:56:30 +0000204
Brett Cannon2a922ed2009-03-09 03:35:50 +0000205:mod:`importlib.abc` -- Abstract base classes related to import
206---------------------------------------------------------------
207
208.. module:: importlib.abc
209 :synopsis: Abstract base classes related to import
210
211The :mod:`importlib.abc` module contains all of the core abstract base classes
212used by :keyword:`import`. Some subclasses of the core abstract base classes
213are also provided to help in implementing the core ABCs.
214
Andrew Svetlova8656542012-08-13 22:19:01 +0300215ABC hierarchy::
216
217 object
Brett Cannon1b799182012-08-17 14:08:24 -0400218 +-- Finder (deprecated)
Andrew Svetlova8656542012-08-13 22:19:01 +0300219 | +-- MetaPathFinder
220 | +-- PathEntryFinder
221 +-- Loader
222 +-- ResourceLoader --------+
223 +-- InspectLoader |
224 +-- ExecutionLoader --+
225 +-- FileLoader
226 +-- SourceLoader
Andrew Svetlova8656542012-08-13 22:19:01 +0300227
Brett Cannon2a922ed2009-03-09 03:35:50 +0000228
229.. class:: Finder
230
Brett Cannon1b799182012-08-17 14:08:24 -0400231 An abstract base class representing a :term:`finder`.
232
233 .. deprecated:: 3.3
234 Use :class:`MetaPathFinder` or :class:`PathEntryFinder` instead.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000235
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200236 .. abstractmethod:: find_module(fullname, path=None)
Brett Cannonb46a1792012-02-27 18:15:42 -0500237
Brett Cannonf4dc9202012-08-10 12:21:12 -0400238 An abstact method for finding a :term:`loader` for the specified
239 module. Originally specified in :pep:`302`, this method was meant
240 for use in :data:`sys.meta_path` and in the path-based import subsystem.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000241
Brett Cannon100883f2013-04-09 16:59:39 -0400242 .. versionchanged:: 3.4
243 Returns ``None`` when called instead of raising
244 :exc:`NotImplementedError`.
245
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000246
Brett Cannon077ef452012-08-02 17:50:06 -0400247.. class:: MetaPathFinder
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000248
Brett Cannonf4dc9202012-08-10 12:21:12 -0400249 An abstract base class representing a :term:`meta path finder`. For
250 compatibility, this is a subclass of :class:`Finder`.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000251
252 .. versionadded:: 3.3
253
Eric Snowca2d8542013-12-16 23:06:52 -0700254 .. method:: find_spec(fullname, path, target=None)
255
256 An abstract method for finding a :term:`spec <module spec>` for
257 the specified module. If this is a top-level import, *path* will
258 be ``None``. Otherwise, this is a search for a subpackage or
259 module and *path* will be the value of :attr:`__path__` from the
260 parent package. If a spec cannot be found, ``None`` is returned.
261 When passed in, ``target`` is a module object that the finder may
262 use to make a more educated about what spec to return.
263
264 .. versionadded:: 3.4
265
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000266 .. method:: find_module(fullname, path)
267
Eric Snowca2d8542013-12-16 23:06:52 -0700268 A legacy method for finding a :term:`loader` for the specified
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000269 module. If this is a top-level import, *path* will be ``None``.
Ezio Melotti1f67e802012-10-21 07:24:13 +0300270 Otherwise, this is a search for a subpackage or module and *path*
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000271 will be the value of :attr:`__path__` from the parent
272 package. If a loader cannot be found, ``None`` is returned.
273
Brett Cannon8d942292014-01-07 15:52:42 -0500274 If :meth:`find_spec` is defined, backwards-compatible functionality is
275 provided.
276
Brett Cannon100883f2013-04-09 16:59:39 -0400277 .. versionchanged:: 3.4
278 Returns ``None`` when called instead of raising
Brett Cannon8d942292014-01-07 15:52:42 -0500279 :exc:`NotImplementedError`. Can use :meth:`find_spec` to provide
280 functionality.
Brett Cannon100883f2013-04-09 16:59:39 -0400281
Eric Snowca2d8542013-12-16 23:06:52 -0700282 .. deprecated:: 3.4
283 Use :meth:`find_spec` instead.
284
Brett Cannonf4dc9202012-08-10 12:21:12 -0400285 .. method:: invalidate_caches()
286
287 An optional method which, when called, should invalidate any internal
Brett Cannona6e85812012-08-11 19:41:27 -0400288 cache used by the finder. Used by :func:`importlib.invalidate_caches`
289 when invalidating the caches of all finders on :data:`sys.meta_path`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400290
Brett Cannon100883f2013-04-09 16:59:39 -0400291 .. versionchanged:: 3.4
292 Returns ``None`` when called instead of ``NotImplemented``.
293
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000294
Brett Cannon077ef452012-08-02 17:50:06 -0400295.. class:: PathEntryFinder
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000296
Brett Cannonf4dc9202012-08-10 12:21:12 -0400297 An abstract base class representing a :term:`path entry finder`. Though
298 it bears some similarities to :class:`MetaPathFinder`, ``PathEntryFinder``
299 is meant for use only within the path-based import subsystem provided
300 by :class:`PathFinder`. This ABC is a subclass of :class:`Finder` for
Brett Cannon100883f2013-04-09 16:59:39 -0400301 compatibility reasons only.
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000302
303 .. versionadded:: 3.3
304
Eric Snowca2d8542013-12-16 23:06:52 -0700305 .. method:: find_spec(fullname, target=None)
306
307 An abstract method for finding a :term:`spec <module spec>` for
308 the specified module. The finder will search for the module only
309 within the :term:`path entry` to which it is assigned. If a spec
310 cannot be found, ``None`` is returned. When passed in, ``target``
311 is a module object that the finder may use to make a more educated
312 about what spec to return.
313
314 .. versionadded:: 3.4
315
Brett Cannon4067aa22013-04-27 23:20:32 -0400316 .. method:: find_loader(fullname)
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000317
Eric Snowca2d8542013-12-16 23:06:52 -0700318 A legacy method for finding a :term:`loader` for the specified
Brett Cannonf4dc9202012-08-10 12:21:12 -0400319 module. Returns a 2-tuple of ``(loader, portion)`` where ``portion``
320 is a sequence of file system locations contributing to part of a namespace
321 package. The loader may be ``None`` while specifying ``portion`` to
322 signify the contribution of the file system locations to a namespace
323 package. An empty list can be used for ``portion`` to signify the loader
Brett Cannon100883f2013-04-09 16:59:39 -0400324 is not part of a namespace package. If ``loader`` is ``None`` and
325 ``portion`` is the empty list then no loader or location for a namespace
326 package were found (i.e. failure to find anything for the module).
327
Brett Cannon8d942292014-01-07 15:52:42 -0500328 If :meth:`find_spec` is defined then backwards-compatible functionality is
329 provided.
330
Brett Cannon100883f2013-04-09 16:59:39 -0400331 .. versionchanged:: 3.4
332 Returns ``(None, [])`` instead of raising :exc:`NotImplementedError`.
Brett Cannon8d942292014-01-07 15:52:42 -0500333 Uses :meth:`find_spec` when available to provide functionality.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400334
Eric Snowca2d8542013-12-16 23:06:52 -0700335 .. deprecated:: 3.4
336 Use :meth:`find_spec` instead.
337
Brett Cannon4067aa22013-04-27 23:20:32 -0400338 .. method:: find_module(fullname)
Brett Cannonf4dc9202012-08-10 12:21:12 -0400339
340 A concrete implementation of :meth:`Finder.find_module` which is
341 equivalent to ``self.find_loader(fullname)[0]``.
342
Eric Snowca2d8542013-12-16 23:06:52 -0700343 .. deprecated:: 3.4
344 Use :meth:`find_spec` instead.
345
Brett Cannonf4dc9202012-08-10 12:21:12 -0400346 .. method:: invalidate_caches()
347
348 An optional method which, when called, should invalidate any internal
Brett Cannona6e85812012-08-11 19:41:27 -0400349 cache used by the finder. Used by :meth:`PathFinder.invalidate_caches`
Brett Cannonf4dc9202012-08-10 12:21:12 -0400350 when invalidating the caches of all cached finders.
Brett Cannonb46a1792012-02-27 18:15:42 -0500351
Brett Cannon2a922ed2009-03-09 03:35:50 +0000352
353.. class:: Loader
354
355 An abstract base class for a :term:`loader`.
Guido van Rossum09613542009-03-30 20:34:57 +0000356 See :pep:`302` for the exact definition for a loader.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000357
Eric Snowca2d8542013-12-16 23:06:52 -0700358 .. method:: create_module(spec)
359
Brett Cannon02d84542015-01-09 11:39:21 -0500360 A method that returns the module object to use when
361 importing a module. This method may return ``None``,
362 indicating that default module creation semantics should take place.
Eric Snowca2d8542013-12-16 23:06:52 -0700363
364 .. versionadded:: 3.4
365
Brett Cannon02d84542015-01-09 11:39:21 -0500366 .. versionchanged:: 3.5
367 Starting in Python 3.6, this method will not be optional when
368 :meth:`exec_module` is defined.
369
Eric Snowca2d8542013-12-16 23:06:52 -0700370 .. method:: exec_module(module)
371
372 An abstract method that executes the module in its own namespace
373 when a module is imported or reloaded. The module should already
374 be initialized when exec_module() is called.
375
376 .. versionadded:: 3.4
377
Brett Cannon9c751b72009-03-09 16:28:16 +0000378 .. method:: load_module(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000379
Eric Snowca2d8542013-12-16 23:06:52 -0700380 A legacy method for loading a module. If the module cannot be
Brett Cannon2a922ed2009-03-09 03:35:50 +0000381 loaded, :exc:`ImportError` is raised, otherwise the loaded module is
382 returned.
383
Guido van Rossum09613542009-03-30 20:34:57 +0000384 If the requested module already exists in :data:`sys.modules`, that
Brett Cannon2a922ed2009-03-09 03:35:50 +0000385 module should be used and reloaded.
Guido van Rossum09613542009-03-30 20:34:57 +0000386 Otherwise the loader should create a new module and insert it into
387 :data:`sys.modules` before any loading begins, to prevent recursion
388 from the import. If the loader inserted a module and the load fails, it
Brett Cannon2a922ed2009-03-09 03:35:50 +0000389 must be removed by the loader from :data:`sys.modules`; modules already
390 in :data:`sys.modules` before the loader began execution should be left
Eric Snowb523f842013-11-22 09:05:39 -0700391 alone (see :func:`importlib.util.module_for_loader`).
Brett Cannon2a922ed2009-03-09 03:35:50 +0000392
Guido van Rossum09613542009-03-30 20:34:57 +0000393 The loader should set several attributes on the module.
394 (Note that some of these attributes can change when a module is
Eric Snowb523f842013-11-22 09:05:39 -0700395 reloaded):
Brett Cannon2a922ed2009-03-09 03:35:50 +0000396
397 - :attr:`__name__`
398 The name of the module.
399
400 - :attr:`__file__`
401 The path to where the module data is stored (not set for built-in
402 modules).
403
Brett Cannon2cefb3c2013-05-25 11:26:11 -0400404 - :attr:`__cached__`
405 The path to where a compiled version of the module is/should be
406 stored (not set when the attribute would be inappropriate).
407
Brett Cannon2a922ed2009-03-09 03:35:50 +0000408 - :attr:`__path__`
Guido van Rossum09613542009-03-30 20:34:57 +0000409 A list of strings specifying the search path within a
Brett Cannon2a922ed2009-03-09 03:35:50 +0000410 package. This attribute is not set on modules.
411
412 - :attr:`__package__`
413 The parent package for the module/package. If the module is
414 top-level then it has a value of the empty string. The
Brett Cannon100883f2013-04-09 16:59:39 -0400415 :func:`importlib.util.module_for_loader` decorator can handle the
416 details for :attr:`__package__`.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000417
418 - :attr:`__loader__`
Brett Cannon100883f2013-04-09 16:59:39 -0400419 The loader used to load the module. The
420 :func:`importlib.util.module_for_loader` decorator can handle the
421 details for :attr:`__package__`.
422
Brett Cannon8d942292014-01-07 15:52:42 -0500423 When :meth:`exec_module` is available then backwards-compatible
424 functionality is provided.
425
Brett Cannon100883f2013-04-09 16:59:39 -0400426 .. versionchanged:: 3.4
427 Raise :exc:`ImportError` when called instead of
Brett Cannon8d942292014-01-07 15:52:42 -0500428 :exc:`NotImplementedError`. Functionality provided when
429 :meth:`exec_module` is available.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000430
Eric Snowca2d8542013-12-16 23:06:52 -0700431 .. deprecated:: 3.4
432 The recommended API for loading a module is :meth:`exec_module`
Brett Cannon02d84542015-01-09 11:39:21 -0500433 (and :meth:`create_module`). Loaders should implement
Eric Snowca2d8542013-12-16 23:06:52 -0700434 it instead of load_module(). The import machinery takes care of
435 all the other responsibilities of load_module() when exec_module()
436 is implemented.
437
Barry Warsawd7d21942012-07-29 16:36:17 -0400438 .. method:: module_repr(module)
439
Eric Snowca2d8542013-12-16 23:06:52 -0700440 A legacy method which when implemented calculates and returns the
Brett Cannon100883f2013-04-09 16:59:39 -0400441 given module's repr, as a string. The module type's default repr() will
442 use the result of this method as appropriate.
Barry Warsawd7d21942012-07-29 16:36:17 -0400443
Georg Brandl526575d2013-04-11 16:10:13 +0200444 .. versionadded:: 3.3
Barry Warsawd7d21942012-07-29 16:36:17 -0400445
Brett Cannon100883f2013-04-09 16:59:39 -0400446 .. versionchanged:: 3.4
Georg Brandl526575d2013-04-11 16:10:13 +0200447 Made optional instead of an abstractmethod.
Brett Cannon100883f2013-04-09 16:59:39 -0400448
Eric Snowca2d8542013-12-16 23:06:52 -0700449 .. deprecated:: 3.4
450 The import machinery now takes care of this automatically.
451
Brett Cannon2a922ed2009-03-09 03:35:50 +0000452
453.. class:: ResourceLoader
454
455 An abstract base class for a :term:`loader` which implements the optional
456 :pep:`302` protocol for loading arbitrary resources from the storage
457 back-end.
458
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200459 .. abstractmethod:: get_data(path)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000460
461 An abstract method to return the bytes for the data located at *path*.
Guido van Rossum09613542009-03-30 20:34:57 +0000462 Loaders that have a file-like storage back-end
Brett Cannon16248a42009-04-01 20:47:14 +0000463 that allows storing arbitrary data
Guido van Rossum09613542009-03-30 20:34:57 +0000464 can implement this abstract method to give direct access
Andrew Svetlov08af0002014-04-01 01:13:30 +0300465 to the data stored. :exc:`OSError` is to be raised if the *path* cannot
Brett Cannon2a922ed2009-03-09 03:35:50 +0000466 be found. The *path* is expected to be constructed using a module's
Brett Cannon16248a42009-04-01 20:47:14 +0000467 :attr:`__file__` attribute or an item from a package's :attr:`__path__`.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000468
Brett Cannon100883f2013-04-09 16:59:39 -0400469 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300470 Raises :exc:`OSError` instead of :exc:`NotImplementedError`.
Brett Cannon100883f2013-04-09 16:59:39 -0400471
Brett Cannon2a922ed2009-03-09 03:35:50 +0000472
473.. class:: InspectLoader
474
475 An abstract base class for a :term:`loader` which implements the optional
Guido van Rossum09613542009-03-30 20:34:57 +0000476 :pep:`302` protocol for loaders that inspect modules.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000477
Brett Cannona113ac52009-03-15 01:41:33 +0000478 .. method:: get_code(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000479
R David Murray0ae7ae12014-01-08 18:16:02 -0500480 Return the code object for a module, or ``None`` if the module does not
481 have a code object (as would be the case, for example, for a built-in
482 module). Raise an :exc:`ImportError` if loader cannot find the
483 requested module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000484
Brett Cannon3b62ca82013-05-27 21:11:04 -0400485 .. note::
486 While the method has a default implementation, it is suggested that
487 it be overridden if possible for performance.
488
R David Murray1b00f252012-08-15 10:43:58 -0400489 .. index::
490 single: universal newlines; importlib.abc.InspectLoader.get_source method
491
Brett Cannon100883f2013-04-09 16:59:39 -0400492 .. versionchanged:: 3.4
Brett Cannon3b62ca82013-05-27 21:11:04 -0400493 No longer abstract and a concrete implementation is provided.
Brett Cannon100883f2013-04-09 16:59:39 -0400494
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200495 .. abstractmethod:: get_source(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000496
497 An abstract method to return the source of a module. It is returned as
R David Murray1b00f252012-08-15 10:43:58 -0400498 a text string using :term:`universal newlines`, translating all
R David Murrayee0a9452012-08-15 11:05:36 -0400499 recognized line separators into ``'\n'`` characters. Returns ``None``
500 if no source is available (e.g. a built-in module). Raises
501 :exc:`ImportError` if the loader cannot find the module specified.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000502
Brett Cannon100883f2013-04-09 16:59:39 -0400503 .. versionchanged:: 3.4
504 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
505
Brett Cannona113ac52009-03-15 01:41:33 +0000506 .. method:: is_package(fullname)
Brett Cannon2a922ed2009-03-09 03:35:50 +0000507
Brett Cannona113ac52009-03-15 01:41:33 +0000508 An abstract method to return a true value if the module is a package, a
509 false value otherwise. :exc:`ImportError` is raised if the
510 :term:`loader` cannot find the module.
Brett Cannon2a922ed2009-03-09 03:35:50 +0000511
Brett Cannon100883f2013-04-09 16:59:39 -0400512 .. versionchanged:: 3.4
513 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
514
Brett Cannon6eaac132014-05-09 12:28:22 -0400515 .. staticmethod:: source_to_code(data, path='<string>')
Brett Cannon9ffe85e2013-05-26 16:45:10 -0400516
517 Create a code object from Python source.
518
519 The *data* argument can be whatever the :func:`compile` function
520 supports (i.e. string or bytes). The *path* argument should be
521 the "path" to where the source code originated from, which can be an
522 abstract concept (e.g. location in a zip file).
523
Brett Cannon6eaac132014-05-09 12:28:22 -0400524 With the subsequent code object one can execute it in a module by
525 running ``exec(code, module.__dict__)``.
526
Brett Cannon9ffe85e2013-05-26 16:45:10 -0400527 .. versionadded:: 3.4
528
Brett Cannon6eaac132014-05-09 12:28:22 -0400529 .. versionchanged:: 3.5
530 Made the method static.
531
Eric Snowca2d8542013-12-16 23:06:52 -0700532 .. method:: exec_module(module)
533
534 Implementation of :meth:`Loader.exec_module`.
535
536 .. versionadded:: 3.4
537
Brett Cannon0dbb4c72013-05-31 18:56:47 -0400538 .. method:: load_module(fullname)
539
Eric Snowca2d8542013-12-16 23:06:52 -0700540 Implementation of :meth:`Loader.load_module`.
541
542 .. deprecated:: 3.4
543 use :meth:`exec_module` instead.
Brett Cannon0dbb4c72013-05-31 18:56:47 -0400544
Brett Cannon2a922ed2009-03-09 03:35:50 +0000545
Brett Cannon69194272009-07-20 04:23:48 +0000546.. class:: ExecutionLoader
547
548 An abstract base class which inherits from :class:`InspectLoader` that,
Brett Cannon23460292009-07-20 22:59:00 +0000549 when implemented, helps a module to be executed as a script. The ABC
Brett Cannon69194272009-07-20 04:23:48 +0000550 represents an optional :pep:`302` protocol.
551
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200552 .. abstractmethod:: get_filename(fullname)
Brett Cannon69194272009-07-20 04:23:48 +0000553
Brett Cannonf23e3742010-06-27 23:57:46 +0000554 An abstract method that is to return the value of :attr:`__file__` for
Brett Cannon69194272009-07-20 04:23:48 +0000555 the specified module. If no path is available, :exc:`ImportError` is
556 raised.
557
Brett Cannonf23e3742010-06-27 23:57:46 +0000558 If source code is available, then the method should return the path to
559 the source file, regardless of whether a bytecode was used to load the
560 module.
561
Brett Cannon100883f2013-04-09 16:59:39 -0400562 .. versionchanged:: 3.4
563 Raises :exc:`ImportError` instead of :exc:`NotImplementedError`.
564
Brett Cannonf23e3742010-06-27 23:57:46 +0000565
Brett Cannon938d44d2012-04-22 19:58:33 -0400566.. class:: FileLoader(fullname, path)
567
568 An abstract base class which inherits from :class:`ResourceLoader` and
Andrew Svetlova60de4f2013-02-17 16:55:58 +0200569 :class:`ExecutionLoader`, providing concrete implementations of
Brett Cannon938d44d2012-04-22 19:58:33 -0400570 :meth:`ResourceLoader.get_data` and :meth:`ExecutionLoader.get_filename`.
571
572 The *fullname* argument is a fully resolved name of the module the loader is
573 to handle. The *path* argument is the path to the file for the module.
574
575 .. versionadded:: 3.3
576
577 .. attribute:: name
578
579 The name of the module the loader can handle.
580
581 .. attribute:: path
582
583 Path to the file of the module.
584
Barry Warsawd7d21942012-07-29 16:36:17 -0400585 .. method:: load_module(fullname)
Brett Cannonc0499522012-05-11 14:48:41 -0400586
Barry Warsawd7d21942012-07-29 16:36:17 -0400587 Calls super's ``load_module()``.
Brett Cannonc0499522012-05-11 14:48:41 -0400588
Eric Snowca2d8542013-12-16 23:06:52 -0700589 .. deprecated:: 3.4
590 Use :meth:`Loader.exec_module` instead.
591
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200592 .. abstractmethod:: get_filename(fullname)
Brett Cannon938d44d2012-04-22 19:58:33 -0400593
Barry Warsawd7d21942012-07-29 16:36:17 -0400594 Returns :attr:`path`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400595
Berker Peksag6e9d2e62015-12-08 12:14:50 +0200596 .. abstractmethod:: get_data(path)
Brett Cannon938d44d2012-04-22 19:58:33 -0400597
Brett Cannon3b62ca82013-05-27 21:11:04 -0400598 Reads *path* as a binary file and returns the bytes from it.
Brett Cannon938d44d2012-04-22 19:58:33 -0400599
600
Brett Cannonf23e3742010-06-27 23:57:46 +0000601.. class:: SourceLoader
602
603 An abstract base class for implementing source (and optionally bytecode)
604 file loading. The class inherits from both :class:`ResourceLoader` and
605 :class:`ExecutionLoader`, requiring the implementation of:
606
607 * :meth:`ResourceLoader.get_data`
608 * :meth:`ExecutionLoader.get_filename`
Brett Cannon6dfbff32010-07-21 09:48:31 +0000609 Should only return the path to the source file; sourceless
Brett Cannona81d5272013-06-16 19:17:12 -0400610 loading is not supported.
Brett Cannonf23e3742010-06-27 23:57:46 +0000611
612 The abstract methods defined by this class are to add optional bytecode
Brett Cannon5650e4f2012-11-18 10:03:31 -0500613 file support. Not implementing these optional methods (or causing them to
614 raise :exc:`NotImplementedError`) causes the loader to
Brett Cannonf23e3742010-06-27 23:57:46 +0000615 only work with source code. Implementing the methods allows the loader to
616 work with source *and* bytecode files; it does not allow for *sourceless*
617 loading where only bytecode is provided. Bytecode files are an
618 optimization to speed up loading by removing the parsing step of Python's
619 compiler, and so no bytecode-specific API is exposed.
620
Brett Cannon773468f2012-08-02 17:35:34 -0400621 .. method:: path_stats(path)
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100622
623 Optional abstract method which returns a :class:`dict` containing
624 metadata about the specifed path. Supported dictionary keys are:
625
626 - ``'mtime'`` (mandatory): an integer or floating-point number
627 representing the modification time of the source code;
628 - ``'size'`` (optional): the size in bytes of the source code.
629
630 Any other keys in the dictionary are ignored, to allow for future
Andrew Svetlov08af0002014-04-01 01:13:30 +0300631 extensions. If the path cannot be handled, :exc:`OSError` is raised.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100632
633 .. versionadded:: 3.3
634
Brett Cannon100883f2013-04-09 16:59:39 -0400635 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300636 Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
Brett Cannon100883f2013-04-09 16:59:39 -0400637
Brett Cannon773468f2012-08-02 17:35:34 -0400638 .. method:: path_mtime(path)
Brett Cannonf23e3742010-06-27 23:57:46 +0000639
640 Optional abstract method which returns the modification time for the
641 specified path.
642
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100643 .. deprecated:: 3.3
644 This method is deprecated in favour of :meth:`path_stats`. You don't
645 have to implement it, but it is still available for compatibility
Andrew Svetlov08af0002014-04-01 01:13:30 +0300646 purposes. Raise :exc:`OSError` if the path cannot be handled.
Brett Cannon100883f2013-04-09 16:59:39 -0400647
Georg Brandldf48b972014-03-24 09:06:18 +0100648 .. versionchanged:: 3.4
Andrew Svetlov08af0002014-04-01 01:13:30 +0300649 Raise :exc:`OSError` instead of :exc:`NotImplementedError`.
Antoine Pitrou5136ac02012-01-13 18:52:16 +0100650
Brett Cannon773468f2012-08-02 17:35:34 -0400651 .. method:: set_data(path, data)
Brett Cannonf23e3742010-06-27 23:57:46 +0000652
653 Optional abstract method which writes the specified bytes to a file
Brett Cannon61b14252010-07-03 21:48:25 +0000654 path. Any intermediate directories which do not exist are to be created
655 automatically.
656
657 When writing to the path fails because the path is read-only
Brett Cannon2cefb3c2013-05-25 11:26:11 -0400658 (:attr:`errno.EACCES`/:exc:`PermissionError`), do not propagate the
659 exception.
Brett Cannonf23e3742010-06-27 23:57:46 +0000660
Brett Cannon100883f2013-04-09 16:59:39 -0400661 .. versionchanged:: 3.4
662 No longer raises :exc:`NotImplementedError` when called.
663
Brett Cannon773468f2012-08-02 17:35:34 -0400664 .. method:: get_code(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000665
666 Concrete implementation of :meth:`InspectLoader.get_code`.
667
Eric Snowca2d8542013-12-16 23:06:52 -0700668 .. method:: exec_module(module)
669
670 Concrete implementation of :meth:`Loader.exec_module`.
671
672 .. versionadded:: 3.4
673
Brett Cannon773468f2012-08-02 17:35:34 -0400674 .. method:: load_module(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000675
Eric Snowca2d8542013-12-16 23:06:52 -0700676 Concrete implementation of :meth:`Loader.load_module`.
677
678 .. deprecated:: 3.4
679 Use :meth:`exec_module` instead.
Brett Cannonf23e3742010-06-27 23:57:46 +0000680
Brett Cannon773468f2012-08-02 17:35:34 -0400681 .. method:: get_source(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000682
683 Concrete implementation of :meth:`InspectLoader.get_source`.
684
Brett Cannon773468f2012-08-02 17:35:34 -0400685 .. method:: is_package(fullname)
Brett Cannonf23e3742010-06-27 23:57:46 +0000686
687 Concrete implementation of :meth:`InspectLoader.is_package`. A module
Brett Cannonea0b8232012-06-15 20:00:53 -0400688 is determined to be a package if its file path (as provided by
689 :meth:`ExecutionLoader.get_filename`) is a file named
690 ``__init__`` when the file extension is removed **and** the module name
691 itself does not end in ``__init__``.
Brett Cannonf23e3742010-06-27 23:57:46 +0000692
Brett Cannon69194272009-07-20 04:23:48 +0000693
Brett Cannon78246b62009-01-25 04:56:30 +0000694:mod:`importlib.machinery` -- Importers and path hooks
695------------------------------------------------------
696
697.. module:: importlib.machinery
698 :synopsis: Importers and path hooks
699
700This module contains the various objects that help :keyword:`import`
701find and load modules.
702
Brett Cannoncb66eb02012-05-11 12:58:42 -0400703.. attribute:: SOURCE_SUFFIXES
704
705 A list of strings representing the recognized file suffixes for source
706 modules.
707
708 .. versionadded:: 3.3
709
710.. attribute:: DEBUG_BYTECODE_SUFFIXES
711
712 A list of strings representing the file suffixes for non-optimized bytecode
713 modules.
714
715 .. versionadded:: 3.3
716
Brett Cannonf299abd2015-04-13 14:21:02 -0400717 .. deprecated:: 3.5
718 Use :attr:`BYTECODE_SUFFIXES` instead.
719
Brett Cannoncb66eb02012-05-11 12:58:42 -0400720.. attribute:: OPTIMIZED_BYTECODE_SUFFIXES
721
722 A list of strings representing the file suffixes for optimized bytecode
723 modules.
724
725 .. versionadded:: 3.3
726
Brett Cannonf299abd2015-04-13 14:21:02 -0400727 .. deprecated:: 3.5
728 Use :attr:`BYTECODE_SUFFIXES` instead.
729
Brett Cannoncb66eb02012-05-11 12:58:42 -0400730.. attribute:: BYTECODE_SUFFIXES
731
732 A list of strings representing the recognized file suffixes for bytecode
Brett Cannonf299abd2015-04-13 14:21:02 -0400733 modules (including the leading dot).
Brett Cannoncb66eb02012-05-11 12:58:42 -0400734
735 .. versionadded:: 3.3
736
Brett Cannonf299abd2015-04-13 14:21:02 -0400737 .. versionchanged:: 3.5
738 The value is no longer dependent on ``__debug__``.
739
Brett Cannoncb66eb02012-05-11 12:58:42 -0400740.. attribute:: EXTENSION_SUFFIXES
741
Nick Coghlan76e07702012-07-18 23:14:57 +1000742 A list of strings representing the recognized file suffixes for
Brett Cannoncb66eb02012-05-11 12:58:42 -0400743 extension modules.
744
745 .. versionadded:: 3.3
746
Nick Coghlanc5afd422012-07-18 23:59:08 +1000747.. function:: all_suffixes()
Nick Coghlan76e07702012-07-18 23:14:57 +1000748
749 Returns a combined list of strings representing all file suffixes for
Nick Coghlanc5afd422012-07-18 23:59:08 +1000750 modules recognized by the standard import machinery. This is a
Nick Coghlan76e07702012-07-18 23:14:57 +1000751 helper for code which simply needs to know if a filesystem path
Nick Coghlanc5afd422012-07-18 23:59:08 +1000752 potentially refers to a module without needing any details on the kind
Martin Panterd21e0b52015-10-10 10:36:22 +0000753 of module (for example, :func:`inspect.getmodulename`).
Nick Coghlan76e07702012-07-18 23:14:57 +1000754
755 .. versionadded:: 3.3
756
757
Brett Cannon78246b62009-01-25 04:56:30 +0000758.. class:: BuiltinImporter
759
Brett Cannon2a922ed2009-03-09 03:35:50 +0000760 An :term:`importer` for built-in modules. All known built-in modules are
761 listed in :data:`sys.builtin_module_names`. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000762 :class:`importlib.abc.MetaPathFinder` and
763 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000764
765 Only class methods are defined by this class to alleviate the need for
766 instantiation.
767
Nick Coghland5cacbb2015-05-23 22:24:10 +1000768 .. versionchanged:: 3.5
769 As part of :pep:`489`, the builtin importer now implements
770 :meth:`Loader.create_module` and :meth:`Loader.exec_module`
Eric Snowca2d8542013-12-16 23:06:52 -0700771
Brett Cannon78246b62009-01-25 04:56:30 +0000772
773.. class:: FrozenImporter
774
Brett Cannon2a922ed2009-03-09 03:35:50 +0000775 An :term:`importer` for frozen modules. This class implements the
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000776 :class:`importlib.abc.MetaPathFinder` and
777 :class:`importlib.abc.InspectLoader` ABCs.
Brett Cannon78246b62009-01-25 04:56:30 +0000778
779 Only class methods are defined by this class to alleviate the need for
780 instantiation.
781
Brett Cannondebb98d2009-02-16 04:18:01 +0000782
Nick Coghlanff794862012-08-02 21:45:24 +1000783.. class:: WindowsRegistryFinder
784
785 :term:`Finder` for modules declared in the Windows registry. This class
Nick Coghlan49417742012-08-02 23:03:58 +1000786 implements the :class:`importlib.abc.Finder` ABC.
Nick Coghlanff794862012-08-02 21:45:24 +1000787
788 Only class methods are defined by this class to alleviate the need for
789 instantiation.
790
791 .. versionadded:: 3.3
792
793
Brett Cannondebb98d2009-02-16 04:18:01 +0000794.. class:: PathFinder
795
Brett Cannon1b799182012-08-17 14:08:24 -0400796 A :term:`Finder` for :data:`sys.path` and package ``__path__`` attributes.
797 This class implements the :class:`importlib.abc.MetaPathFinder` ABC.
Brett Cannondebb98d2009-02-16 04:18:01 +0000798
Brett Cannon1b799182012-08-17 14:08:24 -0400799 Only class methods are defined by this class to alleviate the need for
800 instantiation.
Brett Cannondebb98d2009-02-16 04:18:01 +0000801
Eric Snowca2d8542013-12-16 23:06:52 -0700802 .. classmethod:: find_spec(fullname, path=None, target=None)
803
804 Class method that attempts to find a :term:`spec <module spec>`
805 for the module specified by *fullname* on :data:`sys.path` or, if
806 defined, on *path*. For each path entry that is searched,
807 :data:`sys.path_importer_cache` is checked. If a non-false object
808 is found then it is used as the :term:`path entry finder` to look
809 for the module being searched for. If no entry is found in
810 :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
811 searched for a finder for the path entry and, if found, is stored
812 in :data:`sys.path_importer_cache` along with being queried about
813 the module. If no finder is ever found then ``None`` is both
814 stored in the cache and returned.
815
816 .. versionadded:: 3.4
817
Brett Cannonb6e25562014-11-21 12:19:28 -0500818 .. versionchanged:: 3.5
819 If the current working directory -- represented by an empty string --
820 is no longer valid then ``None`` is returned but no value is cached
821 in :data:`sys.path_importer_cache`.
822
Brett Cannon1b799182012-08-17 14:08:24 -0400823 .. classmethod:: find_module(fullname, path=None)
Brett Cannondebb98d2009-02-16 04:18:01 +0000824
Eric Snowca2d8542013-12-16 23:06:52 -0700825 A legacy wrapper around :meth:`find_spec`.
826
827 .. deprecated:: 3.4
828 Use :meth:`find_spec` instead.
Brett Cannond2e7b332009-02-17 02:45:03 +0000829
Brett Cannonf4dc9202012-08-10 12:21:12 -0400830 .. classmethod:: invalidate_caches()
831
Eric Snowca2d8542013-12-16 23:06:52 -0700832 Calls :meth:`importlib.abc.PathEntryFinder.invalidate_caches` on all
833 finders stored in :attr:`sys.path_importer_cache`.
Brett Cannonf4dc9202012-08-10 12:21:12 -0400834
Eric Snowca2d8542013-12-16 23:06:52 -0700835 .. versionchanged:: 3.4
836 Calls objects in :data:`sys.path_hooks` with the current working
837 directory for ``''`` (i.e. the empty string).
Brett Cannon27e27f72013-10-18 11:39:04 -0400838
Brett Cannond2e7b332009-02-17 02:45:03 +0000839
Brett Cannon938d44d2012-04-22 19:58:33 -0400840.. class:: FileFinder(path, \*loader_details)
841
Nick Coghlan8a9080f2012-08-02 21:26:03 +1000842 A concrete implementation of :class:`importlib.abc.PathEntryFinder` which
843 caches results from the file system.
Brett Cannon938d44d2012-04-22 19:58:33 -0400844
845 The *path* argument is the directory for which the finder is in charge of
846 searching.
847
Brett Cannonac9f2f32012-08-10 13:47:54 -0400848 The *loader_details* argument is a variable number of 2-item tuples each
849 containing a loader and a sequence of file suffixes the loader recognizes.
Brett Cannon29b2f172013-06-21 18:31:55 -0400850 The loaders are expected to be callables which accept two arguments of
851 the module's name and the path to the file found.
Brett Cannon938d44d2012-04-22 19:58:33 -0400852
853 The finder will cache the directory contents as necessary, making stat calls
854 for each module search to verify the cache is not outdated. Because cache
855 staleness relies upon the granularity of the operating system's state
856 information of the file system, there is a potential race condition of
857 searching for a module, creating a new file, and then searching for the
858 module the new file represents. If the operations happen fast enough to fit
859 within the granularity of stat calls, then the module search will fail. To
860 prevent this from happening, when you create a module dynamically, make sure
861 to call :func:`importlib.invalidate_caches`.
862
863 .. versionadded:: 3.3
864
865 .. attribute:: path
866
867 The path the finder will search in.
868
Eric Snowca2d8542013-12-16 23:06:52 -0700869 .. method:: find_spec(fullname, target=None)
870
871 Attempt to find the spec to handle *fullname* within :attr:`path`.
872
873 .. versionadded:: 3.4
874
Brett Cannon1d753822013-06-16 19:06:55 -0400875 .. method:: find_loader(fullname)
Brett Cannon938d44d2012-04-22 19:58:33 -0400876
877 Attempt to find the loader to handle *fullname* within :attr:`path`.
878
879 .. method:: invalidate_caches()
880
881 Clear out the internal cache.
882
883 .. classmethod:: path_hook(\*loader_details)
884
885 A class method which returns a closure for use on :attr:`sys.path_hooks`.
886 An instance of :class:`FileFinder` is returned by the closure using the
887 path argument given to the closure directly and *loader_details*
888 indirectly.
889
890 If the argument to the closure is not an existing directory,
891 :exc:`ImportError` is raised.
892
893
894.. class:: SourceFileLoader(fullname, path)
895
896 A concrete implementation of :class:`importlib.abc.SourceLoader` by
897 subclassing :class:`importlib.abc.FileLoader` and providing some concrete
898 implementations of other methods.
899
900 .. versionadded:: 3.3
901
902 .. attribute:: name
903
904 The name of the module that this loader will handle.
905
906 .. attribute:: path
907
908 The path to the source file.
909
910 .. method:: is_package(fullname)
911
912 Return true if :attr:`path` appears to be for a package.
913
914 .. method:: path_stats(path)
915
916 Concrete implementation of :meth:`importlib.abc.SourceLoader.path_stats`.
917
918 .. method:: set_data(path, data)
919
920 Concrete implementation of :meth:`importlib.abc.SourceLoader.set_data`.
921
Brett Cannon062fcac2014-05-09 11:55:49 -0400922 .. method:: load_module(name=None)
923
924 Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
925 specifying the name of the module to load is optional.
926
Brett Cannon938d44d2012-04-22 19:58:33 -0400927
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200928.. class:: SourcelessFileLoader(fullname, path)
Brett Cannon938d44d2012-04-22 19:58:33 -0400929
930 A concrete implementation of :class:`importlib.abc.FileLoader` which can
931 import bytecode files (i.e. no source code files exist).
932
Marc-Andre Lemburg4fe29c92012-04-25 02:31:37 +0200933 Please note that direct use of bytecode files (and thus not source code
934 files) inhibits your modules from being usable by all Python
935 implementations or new versions of Python which change the bytecode
936 format.
Brett Cannon938d44d2012-04-22 19:58:33 -0400937
938 .. versionadded:: 3.3
939
940 .. attribute:: name
941
942 The name of the module the loader will handle.
943
944 .. attribute:: path
945
946 The path to the bytecode file.
947
948 .. method:: is_package(fullname)
949
950 Determines if the module is a package based on :attr:`path`.
951
952 .. method:: get_code(fullname)
953
954 Returns the code object for :attr:`name` created from :attr:`path`.
955
956 .. method:: get_source(fullname)
957
958 Returns ``None`` as bytecode files have no source when this loader is
959 used.
960
Brett Cannon062fcac2014-05-09 11:55:49 -0400961 .. method:: load_module(name=None)
962
963 Concrete implementation of :meth:`importlib.abc.Loader.load_module` where
964 specifying the name of the module to load is optional.
965
Brett Cannon938d44d2012-04-22 19:58:33 -0400966
967.. class:: ExtensionFileLoader(fullname, path)
968
Eric Snow51794452013-10-03 12:08:55 -0600969 A concrete implementation of :class:`importlib.abc.ExecutionLoader` for
Brett Cannon938d44d2012-04-22 19:58:33 -0400970 extension modules.
971
972 The *fullname* argument specifies the name of the module the loader is to
973 support. The *path* argument is the path to the extension module's file.
974
975 .. versionadded:: 3.3
976
977 .. attribute:: name
978
979 Name of the module the loader supports.
980
981 .. attribute:: path
982
983 Path to the extension module.
984
Nick Coghland5cacbb2015-05-23 22:24:10 +1000985 .. method:: create_module(spec)
Brett Cannon938d44d2012-04-22 19:58:33 -0400986
Nick Coghland5cacbb2015-05-23 22:24:10 +1000987 Creates the module object from the given specification in accordance
988 with :pep:`489`.
Brett Cannon938d44d2012-04-22 19:58:33 -0400989
Nick Coghland5cacbb2015-05-23 22:24:10 +1000990 .. versionadded:: 3.5
991
992 .. method:: exec_module(module)
993
994 Initializes the given module object in accordance with :pep:`489`.
995
996 .. versionadded:: 3.5
Eric Snowca2d8542013-12-16 23:06:52 -0700997
Brett Cannon938d44d2012-04-22 19:58:33 -0400998 .. method:: is_package(fullname)
999
Brett Cannonac9f2f32012-08-10 13:47:54 -04001000 Returns ``True`` if the file path points to a package's ``__init__``
1001 module based on :attr:`EXTENSION_SUFFIXES`.
Brett Cannon938d44d2012-04-22 19:58:33 -04001002
1003 .. method:: get_code(fullname)
1004
1005 Returns ``None`` as extension modules lack a code object.
1006
1007 .. method:: get_source(fullname)
1008
1009 Returns ``None`` as extension modules do not have source code.
1010
Eric Snow51794452013-10-03 12:08:55 -06001011 .. method:: get_filename(fullname)
1012
1013 Returns :attr:`path`.
1014
Eric Snowdcd01b42013-10-04 20:35:34 -06001015 .. versionadded:: 3.4
1016
Brett Cannon938d44d2012-04-22 19:58:33 -04001017
Eric Snowb523f842013-11-22 09:05:39 -07001018.. class:: ModuleSpec(name, loader, *, origin=None, loader_state=None, is_package=None)
1019
1020 A specification for a module's import-system-related state.
1021
1022 .. versionadded:: 3.4
1023
1024 .. attribute:: name
1025
1026 (``__name__``)
1027
1028 A string for the fully-qualified name of the module.
1029
1030 .. attribute:: loader
1031
1032 (``__loader__``)
1033
1034 The loader to use for loading. For namespace packages this should be
1035 set to None.
1036
1037 .. attribute:: origin
1038
1039 (``__file__``)
1040
1041 Name of the place from which the module is loaded, e.g. "builtin" for
1042 built-in modules and the filename for modules loaded from source.
1043 Normally "origin" should be set, but it may be None (the default)
1044 which indicates it is unspecified.
1045
1046 .. attribute:: submodule_search_locations
1047
1048 (``__path__``)
1049
1050 List of strings for where to find submodules, if a package (None
1051 otherwise).
1052
1053 .. attribute:: loader_state
1054
1055 Container of extra module-specific data for use during loading (or
1056 None).
1057
1058 .. attribute:: cached
1059
1060 (``__cached__``)
1061
1062 String for where the compiled module should be stored (or None).
1063
1064 .. attribute:: parent
1065
1066 (``__package__``)
1067
1068 (Read-only) Fully-qualified name of the package to which the module
1069 belongs as a submodule (or None).
1070
1071 .. attribute:: has_location
1072
Eric Snowb282b3d2013-12-10 22:16:41 -07001073 Boolean indicating whether or not the module's "origin"
Eric Snowb523f842013-11-22 09:05:39 -07001074 attribute refers to a loadable location.
1075
Brett Cannond2e7b332009-02-17 02:45:03 +00001076:mod:`importlib.util` -- Utility code for importers
1077---------------------------------------------------
1078
1079.. module:: importlib.util
Brett Cannon75321e82012-03-02 11:58:25 -05001080 :synopsis: Utility code for importers
Brett Cannond2e7b332009-02-17 02:45:03 +00001081
1082This module contains the various objects that help in the construction of
1083an :term:`importer`.
1084
Brett Cannon05a647d2013-06-14 19:02:34 -04001085.. attribute:: MAGIC_NUMBER
1086
1087 The bytes which represent the bytecode version number. If you need help with
1088 loading/writing bytecode then consider :class:`importlib.abc.SourceLoader`.
1089
1090 .. versionadded:: 3.4
1091
Brett Cannonf299abd2015-04-13 14:21:02 -04001092.. function:: cache_from_source(path, debug_override=None, *, optimization=None)
Brett Cannona3c96152013-06-14 22:26:30 -04001093
Brett Cannonf299abd2015-04-13 14:21:02 -04001094 Return the :pep:`3147`/:pep:`488` path to the byte-compiled file associated
1095 with the source *path*. For example, if *path* is ``/foo/bar/baz.py`` the return
Brett Cannona3c96152013-06-14 22:26:30 -04001096 value would be ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.
1097 The ``cpython-32`` string comes from the current magic tag (see
1098 :func:`get_tag`; if :attr:`sys.implementation.cache_tag` is not defined then
Brett Cannonf299abd2015-04-13 14:21:02 -04001099 :exc:`NotImplementedError` will be raised).
Brett Cannona3c96152013-06-14 22:26:30 -04001100
Brett Cannonf299abd2015-04-13 14:21:02 -04001101 The *optimization* parameter is used to specify the optimization level of the
1102 bytecode file. An empty string represents no optimization, so
1103 ``/foo/bar/baz.py`` with an *optimization* of ``''`` will result in a
1104 bytecode path of ``/foo/bar/__pycache__/baz.cpython-32.pyc``. ``None`` causes
1105 the interpter's optimization level to be used. Any other value's string
1106 representation being used, so ``/foo/bar/baz.py`` with an *optimization* of
1107 ``2`` will lead to the bytecode path of
1108 ``/foo/bar/__pycache__/baz.cpython-32.opt-2.pyc``. The string representation
1109 of *optimization* can only be alphanumeric, else :exc:`ValueError` is raised.
1110
1111 The *debug_override* parameter is deprecated and can be used to override
1112 the system's value for ``__debug__``. A ``True`` value is the equivalent of
1113 setting *optimization* to the empty string. A ``False`` value is the same as
1114 setting *optimization* to ``1``. If both *debug_override* an *optimization*
1115 are not ``None`` then :exc:`TypeError` is raised.
Brett Cannona3c96152013-06-14 22:26:30 -04001116
1117 .. versionadded:: 3.4
1118
Berker Peksagfe5f6142016-01-30 19:30:06 +02001119 .. versionchanged:: 3.5
Brett Cannonf299abd2015-04-13 14:21:02 -04001120 The *optimization* parameter was added and the *debug_override* parameter
1121 was deprecated.
1122
Brett Cannona3c96152013-06-14 22:26:30 -04001123
1124.. function:: source_from_cache(path)
1125
1126 Given the *path* to a :pep:`3147` file name, return the associated source code
1127 file path. For example, if *path* is
1128 ``/foo/bar/__pycache__/baz.cpython-32.pyc`` the returned path would be
1129 ``/foo/bar/baz.py``. *path* need not exist, however if it does not conform
Larry Hastings770ce202015-04-19 13:50:12 -07001130 to :pep:`3147` or :pep:`488` format, a ``ValueError`` is raised. If
Brett Cannona3c96152013-06-14 22:26:30 -04001131 :attr:`sys.implementation.cache_tag` is not defined,
1132 :exc:`NotImplementedError` is raised.
1133
1134 .. versionadded:: 3.4
1135
Brett Cannonf24fecd2013-06-16 18:37:53 -04001136.. function:: decode_source(source_bytes)
1137
1138 Decode the given bytes representing source code and return it as a string
1139 with universal newlines (as required by
1140 :meth:`importlib.abc.InspectLoader.get_source`).
1141
1142 .. versionadded:: 3.4
1143
Brett Cannond200bf52012-05-13 13:45:09 -04001144.. function:: resolve_name(name, package)
1145
1146 Resolve a relative module name to an absolute one.
1147
1148 If **name** has no leading dots, then **name** is simply returned. This
1149 allows for usage such as
1150 ``importlib.util.resolve_name('sys', __package__)`` without doing a
1151 check to see if the **package** argument is needed.
1152
1153 :exc:`ValueError` is raised if **name** is a relative module name but
1154 package is a false value (e.g. ``None`` or the empty string).
1155 :exc:`ValueError` is also raised a relative name would escape its containing
1156 package (e.g. requesting ``..bacon`` from within the ``spam`` package).
1157
1158 .. versionadded:: 3.3
1159
Eric Snow6029e082014-01-25 15:32:46 -07001160.. function:: find_spec(name, package=None)
1161
1162 Find the :term:`spec <module spec>` for a module, optionally relative to
1163 the specified **package** name. If the module is in :attr:`sys.modules`,
1164 then ``sys.modules[name].__spec__`` is returned (unless the spec would be
1165 ``None`` or is not set, in which case :exc:`ValueError` is raised).
1166 Otherwise a search using :attr:`sys.meta_path` is done. ``None`` is
1167 returned if no spec is found.
1168
1169 If **name** is for a submodule (contains a dot), the parent module is
1170 automatically imported.
1171
1172 **name** and **package** work the same as for :func:`import_module`.
1173
1174 .. versionadded:: 3.4
1175
Brett Cannon2a17bde2014-05-30 14:55:29 -04001176.. function:: module_from_spec(spec)
1177
Brett Cannon02d84542015-01-09 11:39:21 -05001178 Create a new module based on **spec** and ``spec.loader.create_module()``.
Brett Cannon2a17bde2014-05-30 14:55:29 -04001179
Brett Cannon02d84542015-01-09 11:39:21 -05001180 If ``spec.loader.create_module()`` does not return ``None``, then any
Brett Cannon2a17bde2014-05-30 14:55:29 -04001181 pre-existing attributes will not be reset. Also, no :exc:`AttributeError`
1182 will be raised if triggered while accessing **spec** or setting an attribute
1183 on the module.
1184
1185 This function is preferred over using :class:`types.ModuleType` to create a
1186 new module as **spec** is used to set as many import-controlled attributes on
1187 the module as possible.
1188
1189 .. versionadded:: 3.5
1190
Georg Brandl8a1caa22010-07-29 16:01:11 +00001191.. decorator:: module_for_loader
Brett Cannond2e7b332009-02-17 02:45:03 +00001192
Brett Cannona22faca2013-05-28 17:50:14 -04001193 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
Guido van Rossum09613542009-03-30 20:34:57 +00001194 to handle selecting the proper
Brett Cannond2e7b332009-02-17 02:45:03 +00001195 module object to load with. The decorated method is expected to have a call
Brett Cannon2a922ed2009-03-09 03:35:50 +00001196 signature taking two positional arguments
1197 (e.g. ``load_module(self, module)``) for which the second argument
Guido van Rossum09613542009-03-30 20:34:57 +00001198 will be the module **object** to be used by the loader.
Brett Cannonefad00d2012-04-27 17:27:14 -04001199 Note that the decorator will not work on static methods because of the
1200 assumption of two arguments.
Brett Cannond2e7b332009-02-17 02:45:03 +00001201
Guido van Rossum09613542009-03-30 20:34:57 +00001202 The decorated method will take in the **name** of the module to be loaded
1203 as expected for a :term:`loader`. If the module is not found in
Brett Cannon3dc48d62013-05-28 18:35:54 -04001204 :data:`sys.modules` then a new one is constructed. Regardless of where the
1205 module came from, :attr:`__loader__` set to **self** and :attr:`__package__`
1206 is set based on what :meth:`importlib.abc.InspectLoader.is_package` returns
1207 (if available). These attributes are set unconditionally to support
1208 reloading.
Brett Cannonefad00d2012-04-27 17:27:14 -04001209
1210 If an exception is raised by the decorated method and a module was added to
Brett Cannona87e31c2013-09-13 16:52:19 -04001211 :data:`sys.modules`, then the module will be removed to prevent a partially
1212 initialized module from being in left in :data:`sys.modules`. If the module
1213 was already in :data:`sys.modules` then it is left alone.
Brett Cannond2e7b332009-02-17 02:45:03 +00001214
Brett Cannonefad00d2012-04-27 17:27:14 -04001215 .. versionchanged:: 3.3
Georg Brandl61063cc2012-06-24 22:48:30 +02001216 :attr:`__loader__` and :attr:`__package__` are automatically set
1217 (when possible).
Brett Cannon57b46f52009-03-02 14:38:26 +00001218
Brett Cannon3dc48d62013-05-28 18:35:54 -04001219 .. versionchanged:: 3.4
Brett Cannon0dbb4c72013-05-31 18:56:47 -04001220 Set :attr:`__name__`, :attr:`__loader__` :attr:`__package__`
1221 unconditionally to support reloading.
1222
1223 .. deprecated:: 3.4
Eric Snowb523f842013-11-22 09:05:39 -07001224 The import machinery now directly performs all the functionality
1225 provided by this function.
Brett Cannon3dc48d62013-05-28 18:35:54 -04001226
Georg Brandl8a1caa22010-07-29 16:01:11 +00001227.. decorator:: set_loader
Brett Cannon2cf03a82009-03-10 05:17:37 +00001228
Brett Cannona22faca2013-05-28 17:50:14 -04001229 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module`
1230 to set the :attr:`__loader__`
1231 attribute on the returned module. If the attribute is already set the
1232 decorator does nothing. It is assumed that the first positional argument to
1233 the wrapped method (i.e. ``self``) is what :attr:`__loader__` should be set
1234 to.
Brett Cannon2cf03a82009-03-10 05:17:37 +00001235
Brett Cannon4802bec2013-03-13 10:41:36 -07001236 .. versionchanged:: 3.4
Brett Cannon4c14b5d2013-05-04 13:56:58 -04001237 Set ``__loader__`` if set to ``None``, as if the attribute does not
Brett Cannon4802bec2013-03-13 10:41:36 -07001238 exist.
1239
Eric Snowca2d8542013-12-16 23:06:52 -07001240 .. deprecated:: 3.4
1241 The import machinery takes care of this automatically.
1242
Georg Brandl8a1caa22010-07-29 16:01:11 +00001243.. decorator:: set_package
Brett Cannon57b46f52009-03-02 14:38:26 +00001244
Brett Cannona22faca2013-05-28 17:50:14 -04001245 A :term:`decorator` for :meth:`importlib.abc.Loader.load_module` to set the :attr:`__package__` attribute on the returned module. If :attr:`__package__`
1246 is set and has a value other than ``None`` it will not be changed.
Brett Cannon16248a42009-04-01 20:47:14 +00001247
Eric Snowca2d8542013-12-16 23:06:52 -07001248 .. deprecated:: 3.4
1249 The import machinery takes care of this automatically.
1250
Eric Snowb523f842013-11-22 09:05:39 -07001251.. function:: spec_from_loader(name, loader, *, origin=None, is_package=None)
1252
1253 A factory function for creating a :class:`ModuleSpec` instance based
1254 on a loader. The parameters have the same meaning as they do for
1255 ModuleSpec. The function uses available :term:`loader` APIs, such as
1256 :meth:`InspectLoader.is_package`, to fill in any missing
1257 information on the spec.
1258
1259 .. versionadded:: 3.4
1260
1261.. function:: spec_from_file_location(name, location, *, loader=None, submodule_search_locations=None)
1262
1263 A factory function for creating a :class:`ModuleSpec` instance based
1264 on the path to a file. Missing information will be filled in on the
1265 spec by making use of loader APIs and by the implication that the
1266 module will be file-based.
1267
1268 .. versionadded:: 3.4
Brett Cannona04dbe42014-04-04 13:53:38 -04001269
1270.. class:: LazyLoader(loader)
1271
1272 A class which postpones the execution of the loader of a module until the
1273 module has an attribute accessed.
1274
1275 This class **only** works with loaders that define
Brett Cannon02d84542015-01-09 11:39:21 -05001276 :meth:`~importlib.abc.Loader.exec_module` as control over what module type
1277 is used for the module is required. For those same reasons, the loader's
1278 :meth:`~importlib.abc.Loader.create_module` method will be ignored (i.e., the
Brett Cannon27c712e2016-02-20 18:40:02 -08001279 loader's method should only return ``None``; this excludes
1280 :class:`BuiltinImporter` and :class:`ExtensionFileLoader`). Finally,
Brett Cannona04dbe42014-04-04 13:53:38 -04001281 modules which substitute the object placed into :attr:`sys.modules` will
1282 not work as there is no way to properly replace the module references
1283 throughout the interpreter safely; :exc:`ValueError` is raised if such a
1284 substitution is detected.
1285
1286 .. note::
1287 For projects where startup time is critical, this class allows for
1288 potentially minimizing the cost of loading a module if it is never used.
1289 For projects where startup time is not essential then use of this class is
1290 **heavily** discouraged due to error messages created during loading being
1291 postponed and thus occurring out of context.
1292
1293 .. versionadded:: 3.5
1294
1295 .. classmethod:: factory(loader)
1296
1297 A static method which returns a callable that creates a lazy loader. This
1298 is meant to be used in situations where the loader is passed by class
1299 instead of by instance.
1300 ::
1301
1302 suffixes = importlib.machinery.SOURCE_SUFFIXES
1303 loader = importlib.machinery.SourceFileLoader
1304 lazy_loader = importlib.util.LazyLoader.factory(loader)
Brett Cannon3bf1d872016-01-22 14:03:27 -08001305 finder = importlib.machinery.FileFinder(path, (lazy_loader, suffixes))