blob: d549b2674e85ab25ad91693cf763552ed2ccb808 [file] [log] [blame]
Barry Warsawd7d21942012-07-29 16:36:17 -04001
Barry Warsawdadebab2012-07-31 16:03:09 -04002.. _importsystem:
Barry Warsawd7d21942012-07-29 16:36:17 -04003
Barry Warsawdadebab2012-07-31 16:03:09 -04004*****************
5The import system
6*****************
Barry Warsawd7d21942012-07-29 16:36:17 -04007
8.. index:: single: import machinery
9
10Python code in one :term:`module` gains access to the code in another module
Barry Warsawc1e721b2012-07-30 16:24:12 -040011by the process of :term:`importing` it. The :keyword:`import` statement is
12the most common way of invoking the import machinery, but it is not the only
13way. Functions such as :func:`importlib.import_module` and built-in
14:func:`__import__` can also be used to invoke the import machinery.
Barry Warsawd7d21942012-07-29 16:36:17 -040015
16The :keyword:`import` statement combines two operations; it searches for the
17named module, then it binds the results of that search to a name in the local
18scope. The search operation of the :keyword:`import` statement is defined as
Nick Coghlan49417742012-08-02 23:03:58 +100019a call to the :func:`__import__` function, with the appropriate arguments.
20The return value of :func:`__import__` is used to perform the name
Barry Warsawc1e721b2012-07-30 16:24:12 -040021binding operation of the :keyword:`import` statement. See the
22:keyword:`import` statement for the exact details of that name binding
23operation.
Barry Warsawd7d21942012-07-29 16:36:17 -040024
Barry Warsawc1e721b2012-07-30 16:24:12 -040025A direct call to :func:`__import__` performs only the module search and, if
26found, the module creation operation. While certain side-effects may occur,
27such as the importing of parent packages, and the updating of various caches
28(including :data:`sys.modules`), only the :keyword:`import` statement performs
29a name binding operation.
Barry Warsawd7d21942012-07-29 16:36:17 -040030
Nick Coghlan49417742012-08-02 23:03:58 +100031When calling :func:`__import__` as part of an import statement, the
32import system first checks the module global namespace for a function by
33that name. If it is not found, then the standard builtin :func:`__import__`
34is called. Other mechanisms for invoking the import system (such as
35:func:`importlib.import_module`) do not perform this check and will always
36use the standard import system.
37
Barry Warsawd7d21942012-07-29 16:36:17 -040038When a module is first imported, Python searches for the module and if found,
Barry Warsawc1e721b2012-07-30 16:24:12 -040039it creates a module object [#fnmo]_, initializing it. If the named module
Brett Cannon82da8882013-07-04 17:48:16 -040040cannot be found, an :exc:`ImportError` is raised. Python implements various
Barry Warsawc1e721b2012-07-30 16:24:12 -040041strategies to search for the named module when the import machinery is
42invoked. These strategies can be modified and extended by using various hooks
Nick Coghlan49417742012-08-02 23:03:58 +100043described in the sections below.
Barry Warsawc1e721b2012-07-30 16:24:12 -040044
Nick Coghlan1685db02012-08-20 13:49:08 +100045.. versionchanged:: 3.3
46 The import system has been updated to fully implement the second phase
Andrew Svetlove2cf03e2012-11-15 16:28:21 +020047 of :pep:`302`. There is no longer any implicit import machinery - the full
Nick Coghlan1685db02012-08-20 13:49:08 +100048 import system is exposed through :data:`sys.meta_path`. In addition,
Andrew Svetlove2cf03e2012-11-15 16:28:21 +020049 native namespace package support has been implemented (see :pep:`420`).
Nick Coghlan1685db02012-08-20 13:49:08 +100050
Barry Warsawc1e721b2012-07-30 16:24:12 -040051
52:mod:`importlib`
53================
54
55The :mod:`importlib` module provides a rich API for interacting with the
56import system. For example :func:`importlib.import_module` provides a
57recommended, simpler API than built-in :func:`__import__` for invoking the
58import machinery. Refer to the :mod:`importlib` library documentation for
59additional detail.
60
Barry Warsawd7d21942012-07-29 16:36:17 -040061
62
63Packages
64========
65
66.. index::
67 single: package
68
69Python has only one type of module object, and all modules are of this type,
70regardless of whether the module is implemented in Python, C, or something
71else. To help organize modules and provide a naming hierarchy, Python has a
Barry Warsawc1e721b2012-07-30 16:24:12 -040072concept of :term:`packages <package>`.
Barry Warsawd7d21942012-07-29 16:36:17 -040073
Barry Warsawc1e721b2012-07-30 16:24:12 -040074You can think of packages as the directories on a file system and modules as
75files within directories, but don't take this analogy too literally since
76packages and modules need not originate from the file system. For the
77purposes of this documentation, we'll use this convenient analogy of
78directories and files. Like file system directories, packages are organized
79hierarchically, and packages may themselves contain subpackages, as well as
80regular modules.
Barry Warsawd7d21942012-07-29 16:36:17 -040081
Barry Warsawc1e721b2012-07-30 16:24:12 -040082It's important to keep in mind that all packages are modules, but not all
83modules are packages. Or put another way, packages are just a special kind of
Nick Coghlan49417742012-08-02 23:03:58 +100084module. Specifically, any module that contains a ``__path__`` attribute is
Barry Warsawc1e721b2012-07-30 16:24:12 -040085considered a package.
86
87All modules have a name. Subpackage names are separated from their parent
88package name by dots, akin to Python's standard attribute access syntax. Thus
89you might have a module called :mod:`sys` and a package called :mod:`email`,
90which in turn has a subpackage called :mod:`email.mime` and a module within
91that subpackage called :mod:`email.mime.text`.
Barry Warsawd7d21942012-07-29 16:36:17 -040092
93
94Regular packages
95----------------
96
97.. index::
98 pair: package; regular
99
100Python defines two types of packages, :term:`regular packages <regular
101package>` and :term:`namespace packages <namespace package>`. Regular
102packages are traditional packages as they existed in Python 3.2 and earlier.
103A regular package is typically implemented as a directory containing an
104``__init__.py`` file. When a regular package is imported, this
Nick Coghlan49417742012-08-02 23:03:58 +1000105``__init__.py`` file is implicitly executed, and the objects it defines are
Barry Warsawd7d21942012-07-29 16:36:17 -0400106bound to names in the package's namespace. The ``__init__.py`` file can
107contain the same Python code that any other module can contain, and Python
108will add some additional attributes to the module when it is imported.
109
Barry Warsawd7d21942012-07-29 16:36:17 -0400110For example, the following file system layout defines a top level ``parent``
111package with three subpackages::
112
113 parent/
114 __init__.py
115 one/
116 __init__.py
117 two/
118 __init__.py
119 three/
120 __init__.py
121
Nick Coghlan49417742012-08-02 23:03:58 +1000122Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and
Barry Warsawd7d21942012-07-29 16:36:17 -0400123``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or
Nick Coghlan49417742012-08-02 23:03:58 +1000124``parent.three`` will execute ``parent/two/__init__.py`` and
Barry Warsawd7d21942012-07-29 16:36:17 -0400125``parent/three/__init__.py`` respectively.
126
Barry Warsawc1e721b2012-07-30 16:24:12 -0400127
128Namespace packages
129------------------
130
131.. index::
132 pair:: package; namespace
133 pair:: package; portion
134
135A namespace package is a composite of various :term:`portions <portion>`,
136where each portion contributes a subpackage to the parent package. Portions
137may reside in different locations on the file system. Portions may also be
138found in zip files, on the network, or anywhere else that Python searches
139during import. Namespace packages may or may not correspond directly to
140objects on the file system; they may be virtual modules that have no concrete
141representation.
142
Nick Coghlan49417742012-08-02 23:03:58 +1000143Namespace packages do not use an ordinary list for their ``__path__``
144attribute. They instead use a custom iterable type which will automatically
145perform a new search for package portions on the next import attempt within
146that package if the path of their parent package (or :data:`sys.path` for a
147top level package) changes.
148
Barry Warsawd7d21942012-07-29 16:36:17 -0400149With namespace packages, there is no ``parent/__init__.py`` file. In fact,
150there may be multiple ``parent`` directories found during import search, where
Barry Warsawc1e721b2012-07-30 16:24:12 -0400151each one is provided by a different portion. Thus ``parent/one`` may not be
Barry Warsawd7d21942012-07-29 16:36:17 -0400152physically located next to ``parent/two``. In this case, Python will create a
153namespace package for the top-level ``parent`` package whenever it or one of
154its subpackages is imported.
155
Barry Warsawc1e721b2012-07-30 16:24:12 -0400156See also :pep:`420` for the namespace package specification.
157
Barry Warsawd7d21942012-07-29 16:36:17 -0400158
159Searching
160=========
161
162To begin the search, Python needs the :term:`fully qualified <qualified name>`
163name of the module (or package, but for the purposes of this discussion, the
164difference is immaterial) being imported. This name may come from various
165arguments to the :keyword:`import` statement, or from the parameters to the
Barry Warsawc1e721b2012-07-30 16:24:12 -0400166:func:`importlib.import_module` or :func:`__import__` functions.
Barry Warsawd7d21942012-07-29 16:36:17 -0400167
168This name will be used in various phases of the import search, and it may be
169the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python
170first tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``.
Brett Cannon82da8882013-07-04 17:48:16 -0400171If any of the intermediate imports fail, an :exc:`ImportError` is raised.
Barry Warsawd7d21942012-07-29 16:36:17 -0400172
173
174The module cache
175----------------
176
177.. index::
178 single: sys.modules
179
180The first place checked during import search is :data:`sys.modules`. This
181mapping serves as a cache of all modules that have been previously imported,
182including the intermediate paths. So if ``foo.bar.baz`` was previously
183imported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``,
184and ``foo.bar.baz``. Each key will have as its value the corresponding module
185object.
186
187During import, the module name is looked up in :data:`sys.modules` and if
188present, the associated value is the module satisfying the import, and the
189process completes. However, if the value is ``None``, then an
Brett Cannon82da8882013-07-04 17:48:16 -0400190:exc:`ImportError` is raised. If the module name is missing, Python will
Barry Warsawd7d21942012-07-29 16:36:17 -0400191continue searching for the module.
192
Nick Coghlan49417742012-08-02 23:03:58 +1000193:data:`sys.modules` is writable. Deleting a key may not destroy the
194associated module (as other modules may hold references to it),
195but it will invalidate the cache entry for the named module, causing
196Python to search anew for the named module upon its next
197import. The key can also be assigned to ``None``, forcing the next import
Brett Cannon82da8882013-07-04 17:48:16 -0400198of the module to result in an :exc:`ImportError`.
Nick Coghlan49417742012-08-02 23:03:58 +1000199
200Beware though, as if you keep a reference to the module object,
Barry Warsawd7d21942012-07-29 16:36:17 -0400201invalidate its cache entry in :data:`sys.modules`, and then re-import the
Nick Coghlan49417742012-08-02 23:03:58 +1000202named module, the two module objects will *not* be the same. By contrast,
Berker Peksag7e732a72015-07-25 13:02:37 +0300203:func:`importlib.reload` will reuse the *same* module object, and simply
Nick Coghlan49417742012-08-02 23:03:58 +1000204reinitialise the module contents by rerunning the module's code.
Barry Warsawd7d21942012-07-29 16:36:17 -0400205
206
207Finders and loaders
208-------------------
209
210.. index::
211 single: finder
212 single: loader
Eric Snowb523f842013-11-22 09:05:39 -0700213 single: module spec
Barry Warsawd7d21942012-07-29 16:36:17 -0400214
Barry Warsawdadebab2012-07-31 16:03:09 -0400215If the named module is not found in :data:`sys.modules`, then Python's import
216protocol is invoked to find and load the module. This protocol consists of
217two conceptual objects, :term:`finders <finder>` and :term:`loaders <loader>`.
218A finder's job is to determine whether it can find the named module using
Nick Coghlan49417742012-08-02 23:03:58 +1000219whatever strategy it knows about. Objects that implement both of these
220interfaces are referred to as :term:`importers <importer>` - they return
221themselves when they find that they can load the requested module.
Barry Warsawdadebab2012-07-31 16:03:09 -0400222
Andrew Svetlove2cf03e2012-11-15 16:28:21 +0200223Python includes a number of default finders and importers. The first one
224knows how to locate built-in modules, and the second knows how to locate
225frozen modules. A third default finder searches an :term:`import path`
Nick Coghlan49417742012-08-02 23:03:58 +1000226for modules. The :term:`import path` is a list of locations that may
227name file system paths or zip files. It can also be extended to search
228for any locatable resource, such as those identified by URLs.
Barry Warsawdadebab2012-07-31 16:03:09 -0400229
230The import machinery is extensible, so new finders can be added to extend the
231range and scope of module searching.
Barry Warsawd7d21942012-07-29 16:36:17 -0400232
233Finders do not actually load modules. If they can find the named module, they
Georg Brandl472a65a2013-11-24 12:39:56 +0100234return a :dfn:`module spec`, an encapsulation of the module's import-related
Eric Snowb523f842013-11-22 09:05:39 -0700235information, which the import machinery then uses when loading the module.
Barry Warsawd7d21942012-07-29 16:36:17 -0400236
237The following sections describe the protocol for finders and loaders in more
238detail, including how you can create and register new ones to extend the
239import machinery.
240
Eric Snowb523f842013-11-22 09:05:39 -0700241.. versionchanged:: 3.4
242 In previous versions of Python, finders returned :term:`loaders <loader>`
243 directly, whereas now they return module specs which *contain* loaders.
244 Loaders are still used during import but have fewer responsibilities.
Barry Warsawd7d21942012-07-29 16:36:17 -0400245
246Import hooks
247------------
248
249.. index::
250 single: import hooks
251 single: meta hooks
252 single: path hooks
253 pair: hooks; import
254 pair: hooks; meta
255 pair: hooks; path
256
257The import machinery is designed to be extensible; the primary mechanism for
258this are the *import hooks*. There are two types of import hooks: *meta
Barry Warsawdadebab2012-07-31 16:03:09 -0400259hooks* and *import path hooks*.
Barry Warsawd7d21942012-07-29 16:36:17 -0400260
261Meta hooks are called at the start of import processing, before any other
Barry Warsawdadebab2012-07-31 16:03:09 -0400262import processing has occurred, other than :data:`sys.modules` cache look up.
263This allows meta hooks to override :data:`sys.path` processing, frozen
264modules, or even built-in modules. Meta hooks are registered by adding new
265finder objects to :data:`sys.meta_path`, as described below.
Barry Warsawd7d21942012-07-29 16:36:17 -0400266
Barry Warsawdadebab2012-07-31 16:03:09 -0400267Import path hooks are called as part of :data:`sys.path` (or
268``package.__path__``) processing, at the point where their associated path
269item is encountered. Import path hooks are registered by adding new callables
270to :data:`sys.path_hooks` as described below.
Barry Warsawd7d21942012-07-29 16:36:17 -0400271
272
273The meta path
274-------------
275
276.. index::
277 single: sys.meta_path
Eric Snowb523f842013-11-22 09:05:39 -0700278 pair: finder; find_spec
Barry Warsawd7d21942012-07-29 16:36:17 -0400279
280When the named module is not found in :data:`sys.modules`, Python next
281searches :data:`sys.meta_path`, which contains a list of meta path finder
282objects. These finders are queried in order to see if they know how to handle
283the named module. Meta path finders must implement a method called
Eric Snow7cff4cd2013-12-16 23:10:50 -0700284:meth:`~importlib.abc.MetaPathFinder.find_spec()` which takes three arguments:
285a name, an import path, and (optionally) a target module. The meta path
286finder can use any strategy it wants to determine whether it can handle
287the named module or not.
Barry Warsawd7d21942012-07-29 16:36:17 -0400288
289If the meta path finder knows how to handle the named module, it returns a
Eric Snowb523f842013-11-22 09:05:39 -0700290spec object. If it cannot handle the named module, it returns ``None``. If
Barry Warsawd7d21942012-07-29 16:36:17 -0400291:data:`sys.meta_path` processing reaches the end of its list without returning
Eric Snowb523f842013-11-22 09:05:39 -0700292a spec, then an :exc:`ImportError` is raised. Any other exceptions raised
Barry Warsawd7d21942012-07-29 16:36:17 -0400293are simply propagated up, aborting the import process.
294
Eric Snow7cff4cd2013-12-16 23:10:50 -0700295The :meth:`~importlib.abc.MetaPathFinder.find_spec()` method of meta path
296finders is called with two or three arguments. The first is the fully
297qualified name of the module being imported, for example ``foo.bar.baz``.
298The second argument is the path entries to use for the module search. For
299top-level modules, the second argument is ``None``, but for submodules or
300subpackages, the second argument is the value of the parent package's
301``__path__`` attribute. If the appropriate ``__path__`` attribute cannot
302be accessed, an :exc:`ImportError` is raised. The third argument is an
303existing module object that will be the target of loading later. The
304import system passes in a target module only during reload.
Nick Coghlan49417742012-08-02 23:03:58 +1000305
306The meta path may be traversed multiple times for a single import request.
307For example, assuming none of the modules involved has already been cached,
308importing ``foo.bar.baz`` will first perform a top level import, calling
Eric Snow7cff4cd2013-12-16 23:10:50 -0700309``mpf.find_spec("foo", None, None)`` on each meta path finder (``mpf``). After
Nick Coghlan49417742012-08-02 23:03:58 +1000310``foo`` has been imported, ``foo.bar`` will be imported by traversing the
311meta path a second time, calling
Eric Snow7cff4cd2013-12-16 23:10:50 -0700312``mpf.find_spec("foo.bar", foo.__path__, None)``. Once ``foo.bar`` has been
Nick Coghlan49417742012-08-02 23:03:58 +1000313imported, the final traversal will call
Eric Snow7cff4cd2013-12-16 23:10:50 -0700314``mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)``.
Nick Coghlan49417742012-08-02 23:03:58 +1000315
316Some meta path finders only support top level imports. These importers will
317always return ``None`` when anything other than ``None`` is passed as the
318second argument.
Barry Warsawd7d21942012-07-29 16:36:17 -0400319
320Python's default :data:`sys.meta_path` has three meta path finders, one that
321knows how to import built-in modules, one that knows how to import frozen
Barry Warsawdadebab2012-07-31 16:03:09 -0400322modules, and one that knows how to import modules from an :term:`import path`
Nick Coghlan1685db02012-08-20 13:49:08 +1000323(i.e. the :term:`path based finder`).
Barry Warsawd7d21942012-07-29 16:36:17 -0400324
Eric Snowb523f842013-11-22 09:05:39 -0700325.. versionchanged:: 3.4
Eric Snow7cff4cd2013-12-16 23:10:50 -0700326 The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path
327 finders replaced :meth:`~importlib.abc.MetaPathFinder.find_module`, which
328 is now deprecated. While it will continue to work without change, the
329 import machinery will try it only if the finder does not implement
330 ``find_spec()``.
Barry Warsawd7d21942012-07-29 16:36:17 -0400331
Eric Snowb523f842013-11-22 09:05:39 -0700332
333Loading
Barry Warsawdadebab2012-07-31 16:03:09 -0400334=======
Barry Warsawd7d21942012-07-29 16:36:17 -0400335
Eric Snowb523f842013-11-22 09:05:39 -0700336If and when a module spec is found, the import machinery will use it (and
337the loader it contains) when loading the module. Here is an approximation
338of what happens during the loading portion of import::
Barry Warsawd7d21942012-07-29 16:36:17 -0400339
Eric Snowb523f842013-11-22 09:05:39 -0700340 module = None
341 if spec.loader is not None and hasattr(spec.loader, 'create_module'):
Brett Cannon02d84542015-01-09 11:39:21 -0500342 # It is assumed 'exec_module' will also be defined on the loader.
Eric Snowb523f842013-11-22 09:05:39 -0700343 module = spec.loader.create_module(spec)
344 if module is None:
345 module = ModuleType(spec.name)
346 # The import-related module attributes get set here:
347 _init_module_attrs(spec, module)
Barry Warsawd7d21942012-07-29 16:36:17 -0400348
Eric Snowb523f842013-11-22 09:05:39 -0700349 if spec.loader is None:
350 if spec.submodule_search_locations is not None:
351 # namespace package
352 sys.modules[spec.name] = module
353 else:
354 # unsupported
355 raise ImportError
356 elif not hasattr(spec.loader, 'exec_module'):
357 module = spec.loader.load_module(spec.name)
Eric Snow7cff4cd2013-12-16 23:10:50 -0700358 # Set __loader__ and __package__ if missing.
Eric Snowb523f842013-11-22 09:05:39 -0700359 else:
360 sys.modules[spec.name] = module
361 try:
362 spec.loader.exec_module(module)
363 except BaseException:
364 try:
365 del sys.modules[spec.name]
366 except KeyError:
367 pass
368 raise
Eric Snow7cff4cd2013-12-16 23:10:50 -0700369 return sys.modules[spec.name]
Eric Snowb523f842013-11-22 09:05:39 -0700370
371Note the following details:
Barry Warsawd7d21942012-07-29 16:36:17 -0400372
373 * If there is an existing module object with the given name in
Eric Snowb523f842013-11-22 09:05:39 -0700374 :data:`sys.modules`, import will have already returned it.
Barry Warsawd7d21942012-07-29 16:36:17 -0400375
Eric Snowb523f842013-11-22 09:05:39 -0700376 * The module will exist in :data:`sys.modules` before the loader
Barry Warsawd7d21942012-07-29 16:36:17 -0400377 executes the module code. This is crucial because the module code may
378 (directly or indirectly) import itself; adding it to :data:`sys.modules`
379 beforehand prevents unbounded recursion in the worst case and multiple
380 loading in the best.
381
Eric Snowb523f842013-11-22 09:05:39 -0700382 * If loading fails, the failing module -- and only the failing module --
383 gets removed from :data:`sys.modules`. Any module already in the
384 :data:`sys.modules` cache, and any module that was successfully loaded
385 as a side-effect, must remain in the cache. This contrasts with
386 reloading where even the failing module is left in :data:`sys.modules`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400387
Eric Snowb523f842013-11-22 09:05:39 -0700388 * After the module is created but before execution, the import machinery
Eric Snow7cff4cd2013-12-16 23:10:50 -0700389 sets the import-related module attributes ("_init_module_attrs" in
390 the pseudo-code example above), as summarized in a
391 :ref:`later section <import-mod-attrs>`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400392
Eric Snowb523f842013-11-22 09:05:39 -0700393 * Module execution is the key moment of loading in which the module's
394 namespace gets populated. Execution is entirely delegated to the
395 loader, which gets to decide what gets populated and how.
Barry Warsawd7d21942012-07-29 16:36:17 -0400396
Eric Snowb523f842013-11-22 09:05:39 -0700397 * The module created during loading and passed to exec_module() may
398 not be the one returned at the end of import [#fnlo]_.
Barry Warsawd7d21942012-07-29 16:36:17 -0400399
Eric Snowb523f842013-11-22 09:05:39 -0700400.. versionchanged:: 3.4
401 The import system has taken over the boilerplate responsibilities of
Eric Snow7cff4cd2013-12-16 23:10:50 -0700402 loaders. These were previously performed by the
403 :meth:`importlib.abc.Loader.load_module` method.
Barry Warsawd7d21942012-07-29 16:36:17 -0400404
Eric Snowb523f842013-11-22 09:05:39 -0700405Loaders
406-------
Barry Warsawd7d21942012-07-29 16:36:17 -0400407
Eric Snowb523f842013-11-22 09:05:39 -0700408Module loaders provide the critical function of loading: module execution.
Eric Snow7cff4cd2013-12-16 23:10:50 -0700409The import machinery calls the :meth:`importlib.abc.Loader.exec_module`
Eric Snowb523f842013-11-22 09:05:39 -0700410method with a single argument, the module object to execute. Any value
Eric Snow7cff4cd2013-12-16 23:10:50 -0700411returned from :meth:`~importlib.abc.Loader.exec_module` is ignored.
Eric Snowb523f842013-11-22 09:05:39 -0700412
413Loaders must satisfy the following requirements:
Barry Warsawd7d21942012-07-29 16:36:17 -0400414
415 * If the module is a Python module (as opposed to a built-in module or a
Barry Warsawc1e721b2012-07-30 16:24:12 -0400416 dynamically loaded extension), the loader should execute the module's code
417 in the module's global name space (``module.__dict__``).
Barry Warsawd7d21942012-07-29 16:36:17 -0400418
Eric Snow7cff4cd2013-12-16 23:10:50 -0700419 * If the loader cannot execute the module, it should raise an
Eric Snowb523f842013-11-22 09:05:39 -0700420 :exc:`ImportError`, although any other exception raised during
Eric Snow7cff4cd2013-12-16 23:10:50 -0700421 :meth:`~importlib.abc.Loader.exec_module` will be propagated.
Barry Warsawd7d21942012-07-29 16:36:17 -0400422
Eric Snowb523f842013-11-22 09:05:39 -0700423In many cases, the finder and loader can be the same object; in such cases the
Eric Snow7cff4cd2013-12-16 23:10:50 -0700424:meth:`~importlib.abc.MetaPathFinder.find_spec` method would just return a
425spec with the loader set to ``self``.
Barry Warsawd7d21942012-07-29 16:36:17 -0400426
Eric Snowb523f842013-11-22 09:05:39 -0700427Module loaders may opt in to creating the module object during loading
Eric Snow7cff4cd2013-12-16 23:10:50 -0700428by implementing a :meth:`~importlib.abc.Loader.create_module` method.
429It takes one argument, the module spec, and returns the new module object
430to use during loading. ``create_module()`` does not need to set any attributes
Brett Cannon02d84542015-01-09 11:39:21 -0500431on the module object. If the method returns ``None``, the
Eric Snow7cff4cd2013-12-16 23:10:50 -0700432import machinery will create the new module itself.
Barry Warsawd7d21942012-07-29 16:36:17 -0400433
Eric Snowb523f842013-11-22 09:05:39 -0700434.. versionadded:: 3.4
435 The create_module() method of loaders.
Barry Warsawd7d21942012-07-29 16:36:17 -0400436
Eric Snowb523f842013-11-22 09:05:39 -0700437.. versionchanged:: 3.4
Eric Snow7cff4cd2013-12-16 23:10:50 -0700438 The :meth:`~importlib.abc.Loader.load_module` method was replaced by
439 :meth:`~importlib.abc.Loader.exec_module` and the import
Eric Snowb523f842013-11-22 09:05:39 -0700440 machinery assumed all the boilerplate responsibilities of loading.
Barry Warsawd7d21942012-07-29 16:36:17 -0400441
Eric Snowb523f842013-11-22 09:05:39 -0700442 For compatibility with existing loaders, the import machinery will use
Eric Snow7cff4cd2013-12-16 23:10:50 -0700443 the ``load_module()`` method of loaders if it exists and the loader does
Larry Hastingsbfd715e2014-01-05 04:35:56 -0800444 not also implement ``exec_module()``. However, ``load_module()`` has been
Eric Snow7cff4cd2013-12-16 23:10:50 -0700445 deprecated and loaders should implement ``exec_module()`` instead.
Barry Warsawd7d21942012-07-29 16:36:17 -0400446
Eric Snow7cff4cd2013-12-16 23:10:50 -0700447 The ``load_module()`` method must implement all the boilerplate loading
Eric Snowb523f842013-11-22 09:05:39 -0700448 functionality described above in addition to executing the module. All
449 the same constraints apply, with some additional clarification:
Barry Warsawd7d21942012-07-29 16:36:17 -0400450
Eric Snowb523f842013-11-22 09:05:39 -0700451 * If there is an existing module object with the given name in
452 :data:`sys.modules`, the loader must use that existing module.
Eric Snow7cff4cd2013-12-16 23:10:50 -0700453 (Otherwise, :func:`importlib.reload` will not work correctly.) If the
Eric Snowb523f842013-11-22 09:05:39 -0700454 named module does not exist in :data:`sys.modules`, the loader
455 must create a new module object and add it to :data:`sys.modules`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400456
Eric Snowb523f842013-11-22 09:05:39 -0700457 * The module *must* exist in :data:`sys.modules` before the loader
458 executes the module code, to prevent unbounded recursion or multiple
459 loading.
Barry Warsawd7d21942012-07-29 16:36:17 -0400460
Eric Snowb523f842013-11-22 09:05:39 -0700461 * If loading fails, the loader must remove any modules it has inserted
462 into :data:`sys.modules`, but it must remove **only** the failing
Brett Cannond0c4ef12014-11-07 11:29:33 -0500463 module(s), and only if the loader itself has loaded the module(s)
464 explicitly.
Barry Warsawd7d21942012-07-29 16:36:17 -0400465
Brett Cannon02d84542015-01-09 11:39:21 -0500466.. versionchanged:: 3.5
467 A :exc:`DeprecationWarning` is raised when ``exec_module()`` is defined but
468 ``create_module()`` is not. Starting in Python 3.6 it will be an error to not
469 define ``create_module()`` on a loader attached to a ModuleSpec.
470
Barry Warsaw2097f532015-04-22 18:29:16 -0400471Submodules
472----------
473
474When a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the
475``import`` or ``import-from`` statements, or built-in ``__import__()``) a
476binding is placed in the parent module's namespace to the submodule object.
477For example, if package ``spam`` has a submodule ``foo``, after importing
478``spam.foo``, ``spam`` will have an attribute ``foo`` which is bound to the
479submodule. Let's say you have the following directory structure::
480
481 spam/
482 __init__.py
483 foo.py
484 bar.py
485
486and ``spam/__init__.py`` has the following lines in it::
487
488 from .foo import Foo
489 from .bar import Bar
490
491then executing the following puts a name binding to ``foo`` and ``bar`` in the
492``spam`` module::
493
494 >>> import spam
495 >>> spam.foo
496 <module 'spam.foo' from '/tmp/imports/spam/foo.py'>
497 >>> spam.bar
498 <module 'spam.bar' from '/tmp/imports/spam/bar.py'>
499
500Given Python's familiar name binding rules this might seem surprising, but
501it's actually a fundamental feature of the import system. The invariant
502holding is that if you have ``sys.modules['spam']`` and
503``sys.modules['spam.foo']`` (as you would after the above import), the latter
504must appear as the ``foo`` attribute of the former.
505
Eric Snowb523f842013-11-22 09:05:39 -0700506Module spec
507-----------
Barry Warsawd7d21942012-07-29 16:36:17 -0400508
Eric Snowb523f842013-11-22 09:05:39 -0700509The import machinery uses a variety of information about each module
510during import, especially before loading. Most of the information is
511common to all modules. The purpose of a module's spec is to encapsulate
512this import-related information on a per-module basis.
Barry Warsawd7d21942012-07-29 16:36:17 -0400513
Eric Snowb523f842013-11-22 09:05:39 -0700514Using a spec during import allows state to be transferred between import
515system components, e.g. between the finder that creates the module spec
516and the loader that executes it. Most importantly, it allows the
517import machinery to perform the boilerplate operations of loading,
518whereas without a module spec the loader had that responsibility.
Barry Warsawd7d21942012-07-29 16:36:17 -0400519
Eric Snowb523f842013-11-22 09:05:39 -0700520See :class:`~importlib.machinery.ModuleSpec` for more specifics on what
521information a module's spec may hold.
522
523.. versionadded:: 3.4
524
Georg Brandl472a65a2013-11-24 12:39:56 +0100525.. _import-mod-attrs:
526
Eric Snowb523f842013-11-22 09:05:39 -0700527Import-related module attributes
528--------------------------------
529
530The import machinery fills in these attributes on each module object
531during loading, based on the module's spec, before the loader executes
532the module.
533
534.. attribute:: __name__
535
536 The ``__name__`` attribute must be set to the fully-qualified name of
537 the module. This name is used to uniquely identify the module in
538 the import system.
539
540.. attribute:: __loader__
541
542 The ``__loader__`` attribute must be set to the loader object that
543 the import machinery used when loading the module. This is mostly
544 for introspection, but can be used for additional loader-specific
545 functionality, for example getting data associated with a loader.
546
547.. attribute:: __package__
548
549 The module's ``__package__`` attribute must be set. Its value must
550 be a string, but it can be the same value as its ``__name__``. When
551 the module is a package, its ``__package__`` value should be set to
552 its ``__name__``. When the module is not a package, ``__package__``
553 should be set to the empty string for top-level modules, or for
554 submodules, to the parent package's name. See :pep:`366` for further
555 details.
556
557 This attribute is used instead of ``__name__`` to calculate explicit
558 relative imports for main modules, as defined in :pep:`366`.
559
560.. attribute:: __spec__
561
562 The ``__spec__`` attribute must be set to the module spec that was
563 used when importing the module. This is used primarily for
Eric Snowe50f9aa2014-03-28 18:10:33 -0600564 introspection and during reloading. Setting ``__spec__``
565 appropriately applies equally to :ref:`modules initialized during
566 interpreter startup <programs>`. The one exception is ``__main__``,
567 where ``__spec__`` is :ref:`set to None in some cases <main_spec>`.
Eric Snowb523f842013-11-22 09:05:39 -0700568
Eric Snow7cff4cd2013-12-16 23:10:50 -0700569 .. versionadded:: 3.4
570
Eric Snowb523f842013-11-22 09:05:39 -0700571.. attribute:: __path__
572
573 If the module is a package (either regular or namespace), the module
574 object's ``__path__`` attribute must be set. The value must be
575 iterable, but may be empty if ``__path__`` has no further significance.
576 If ``__path__`` is not empty, it must produce strings when iterated
577 over. More details on the semantics of ``__path__`` are given
578 :ref:`below <package-path-rules>`.
579
580 Non-package modules should not have a ``__path__`` attribute.
581
582.. attribute:: __file__
583.. attribute:: __cached__
584
585 ``__file__`` is optional. If set, this attribute's value must be a
586 string. The import system may opt to leave ``__file__`` unset if it
587 has no semantic meaning (e.g. a module loaded from a database).
588
589 If ``__file__`` is set, it may also be appropriate to set the
590 ``__cached__`` attribute which is the path to any compiled version of
591 the code (e.g. byte-compiled file). The file does not need to exist
592 to set this attribute; the path can simply point to where the
593 compiled file would exist (see :pep:`3147`).
594
595 It is also appropriate to set ``__cached__`` when ``__file__`` is not
596 set. However, that scenario is quite atypical. Ultimately, the
597 loader is what makes use of ``__file__`` and/or ``__cached__``. So
598 if a loader can load from a cached module but otherwise does not load
599 from a file, that atypical scenario may be appropriate.
Barry Warsawd7d21942012-07-29 16:36:17 -0400600
Nick Coghlan49417742012-08-02 23:03:58 +1000601.. _package-path-rules:
602
Barry Warsawd7d21942012-07-29 16:36:17 -0400603module.__path__
604---------------
605
606By definition, if a module has an ``__path__`` attribute, it is a package,
607regardless of its value.
608
609A package's ``__path__`` attribute is used during imports of its subpackages.
610Within the import machinery, it functions much the same as :data:`sys.path`,
611i.e. providing a list of locations to search for modules during import.
612However, ``__path__`` is typically much more constrained than
613:data:`sys.path`.
614
Nick Coghlan49417742012-08-02 23:03:58 +1000615``__path__`` must be an iterable of strings, but it may be empty.
616The same rules used for :data:`sys.path` also apply to a package's
617``__path__``, and :data:`sys.path_hooks` (described below) are
618consulted when traversing a package's ``__path__``.
Barry Warsawd7d21942012-07-29 16:36:17 -0400619
620A package's ``__init__.py`` file may set or alter the package's ``__path__``
621attribute, and this was typically the way namespace packages were implemented
622prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no
623longer need to supply ``__init__.py`` files containing only ``__path__``
Eric Snowb523f842013-11-22 09:05:39 -0700624manipulation code; the import machinery automatically sets ``__path__``
Barry Warsawd7d21942012-07-29 16:36:17 -0400625correctly for the namespace package.
626
Eric Snowb523f842013-11-22 09:05:39 -0700627Module reprs
628------------
629
630By default, all modules have a usable repr, however depending on the
631attributes set above, and in the module's spec, you can more explicitly
632control the repr of module objects.
633
634If the module has a spec (``__spec__``), the import machinery will try
635to generate a repr from it. If that fails or there is no spec, the import
636system will craft a default repr using whatever information is available
637on the module. It will try to use the ``module.__name__``,
638``module.__file__``, and ``module.__loader__`` as input into the repr,
639with defaults for whatever information is missing.
640
641Here are the exact rules used:
642
643 * If the module has a ``__spec__`` attribute, the information in the spec
644 is used to generate the repr. The "name", "loader", "origin", and
645 "has_location" attributes are consulted.
646
647 * If the module has a ``__file__`` attribute, this is used as part of the
648 module's repr.
649
650 * If the module has no ``__file__`` but does have a ``__loader__`` that is not
651 ``None``, then the loader's repr is used as part of the module's repr.
652
653 * Otherwise, just use the module's ``__name__`` in the repr.
654
655.. versionchanged:: 3.4
Eric Snow7cff4cd2013-12-16 23:10:50 -0700656 Use of :meth:`loader.module_repr() <importlib.abc.Loader.module_repr>`
657 has been deprecated and the module spec is now used by the import
658 machinery to generate a module repr.
Eric Snowb523f842013-11-22 09:05:39 -0700659
660 For backward compatibility with Python 3.3, the module repr will be
Eric Snow7cff4cd2013-12-16 23:10:50 -0700661 generated by calling the loader's
662 :meth:`~importlib.abc.Loader.module_repr` method, if defined, before
663 trying either approach described above. However, the method is deprecated.
Eric Snowb523f842013-11-22 09:05:39 -0700664
Barry Warsawd7d21942012-07-29 16:36:17 -0400665
Nick Coghlan1685db02012-08-20 13:49:08 +1000666The Path Based Finder
667=====================
Barry Warsawd7d21942012-07-29 16:36:17 -0400668
669.. index::
Nick Coghlan1685db02012-08-20 13:49:08 +1000670 single: path based finder
Barry Warsawd7d21942012-07-29 16:36:17 -0400671
672As mentioned previously, Python comes with several default meta path finders.
Eric Snow7cff4cd2013-12-16 23:10:50 -0700673One of these, called the :term:`path based finder`
Serhiy Storchaka2a614522013-12-23 18:21:57 +0200674(:class:`~importlib.machinery.PathFinder`), searches an :term:`import path`,
Eric Snow7cff4cd2013-12-16 23:10:50 -0700675which contains a list of :term:`path entries <path entry>`. Each path
Barry Warsawdadebab2012-07-31 16:03:09 -0400676entry names a location to search for modules.
Barry Warsawd7d21942012-07-29 16:36:17 -0400677
Nick Coghlan1685db02012-08-20 13:49:08 +1000678The path based finder itself doesn't know how to import anything. Instead, it
Nick Coghlan49417742012-08-02 23:03:58 +1000679traverses the individual path entries, associating each of them with a
680path entry finder that knows how to handle that particular kind of path.
681
682The default set of path entry finders implement all the semantics for finding
683modules on the file system, handling special file types such as Python source
Brett Cannonf299abd2015-04-13 14:21:02 -0400684code (``.py`` files), Python byte code (``.pyc`` files) and
Nick Coghlan49417742012-08-02 23:03:58 +1000685shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport`
686module in the standard library, the default path entry finders also handle
687loading all of these file types (other than shared libraries) from zipfiles.
Barry Warsawdadebab2012-07-31 16:03:09 -0400688
689Path entries need not be limited to file system locations. They can refer to
Nick Coghlan1685db02012-08-20 13:49:08 +1000690URLs, database queries, or any other location that can be specified as a
Nick Coghlan49417742012-08-02 23:03:58 +1000691string.
Barry Warsawdadebab2012-07-31 16:03:09 -0400692
Nick Coghlan1685db02012-08-20 13:49:08 +1000693The path based finder provides additional hooks and protocols so that you
Barry Warsawdadebab2012-07-31 16:03:09 -0400694can extend and customize the types of searchable path entries. For example,
695if you wanted to support path entries as network URLs, you could write a hook
696that implements HTTP semantics to find modules on the web. This hook (a
697callable) would return a :term:`path entry finder` supporting the protocol
698described below, which was then used to get a loader for the module from the
699web.
Barry Warsawd7d21942012-07-29 16:36:17 -0400700
701A word of warning: this section and the previous both use the term *finder*,
702distinguishing between them by using the terms :term:`meta path finder` and
Barry Warsawdadebab2012-07-31 16:03:09 -0400703:term:`path entry finder`. These two types of finders are very similar,
704support similar protocols, and function in similar ways during the import
705process, but it's important to keep in mind that they are subtly different.
706In particular, meta path finders operate at the beginning of the import
707process, as keyed off the :data:`sys.meta_path` traversal.
Barry Warsawd7d21942012-07-29 16:36:17 -0400708
Nick Coghlan1685db02012-08-20 13:49:08 +1000709By contrast, path entry finders are in a sense an implementation detail
710of the path based finder, and in fact, if the path based finder were to be
Barry Warsawdadebab2012-07-31 16:03:09 -0400711removed from :data:`sys.meta_path`, none of the path entry finder semantics
712would be invoked.
Barry Warsawd7d21942012-07-29 16:36:17 -0400713
714
Barry Warsawdadebab2012-07-31 16:03:09 -0400715Path entry finders
716------------------
Barry Warsawd7d21942012-07-29 16:36:17 -0400717
718.. index::
719 single: sys.path
720 single: sys.path_hooks
721 single: sys.path_importer_cache
722 single: PYTHONPATH
723
Eric Snow7cff4cd2013-12-16 23:10:50 -0700724The :term:`path based finder` is responsible for finding and loading
725Python modules and packages whose location is specified with a string
726:term:`path entry`. Most path entries name locations in the file system,
727but they need not be limited to this.
Barry Warsawdadebab2012-07-31 16:03:09 -0400728
Nick Coghlan1685db02012-08-20 13:49:08 +1000729As a meta path finder, the :term:`path based finder` implements the
Eric Snow7cff4cd2013-12-16 23:10:50 -0700730:meth:`~importlib.abc.MetaPathFinder.find_spec` protocol previously
731described, however it exposes additional hooks that can be used to
732customize how modules are found and loaded from the :term:`import path`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400733
Nick Coghlan1685db02012-08-20 13:49:08 +1000734Three variables are used by the :term:`path based finder`, :data:`sys.path`,
Barry Warsawdadebab2012-07-31 16:03:09 -0400735:data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__``
Nick Coghlan49417742012-08-02 23:03:58 +1000736attributes on package objects are also used. These provide additional ways
737that the import machinery can be customized.
Barry Warsawd7d21942012-07-29 16:36:17 -0400738
739:data:`sys.path` contains a list of strings providing search locations for
740modules and packages. It is initialized from the :data:`PYTHONPATH`
741environment variable and various other installation- and
742implementation-specific defaults. Entries in :data:`sys.path` can name
743directories on the file system, zip files, and potentially other "locations"
Barry Warsawdadebab2012-07-31 16:03:09 -0400744(see the :mod:`site` module) that should be searched for modules, such as
Barry Warsaw82c1c782012-11-20 15:22:51 -0500745URLs, or database queries. Only strings and bytes should be present on
746:data:`sys.path`; all other data types are ignored. The encoding of bytes
747entries is determined by the individual :term:`path entry finders <path entry
748finder>`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400749
Nick Coghlan1685db02012-08-20 13:49:08 +1000750The :term:`path based finder` is a :term:`meta path finder`, so the import
Nick Coghlan49417742012-08-02 23:03:58 +1000751machinery begins the :term:`import path` search by calling the path
Eric Snow7cff4cd2013-12-16 23:10:50 -0700752based finder's :meth:`~importlib.machinery.PathFinder.find_spec` method as
753described previously. When the ``path`` argument to
754:meth:`~importlib.machinery.PathFinder.find_spec` is given, it will be a
Nick Coghlan49417742012-08-02 23:03:58 +1000755list of string paths to traverse - typically a package's ``__path__``
Eric Snow7cff4cd2013-12-16 23:10:50 -0700756attribute for an import within that package. If the ``path`` argument is
757``None``, this indicates a top level import and :data:`sys.path` is used.
Barry Warsawd7d21942012-07-29 16:36:17 -0400758
Nick Coghlan1685db02012-08-20 13:49:08 +1000759The path based finder iterates over every entry in the search path, and
Eric Snow7cff4cd2013-12-16 23:10:50 -0700760for each of these, looks for an appropriate :term:`path entry finder`
761(:class:`~importlib.abc.PathEntryFinder`) for the
Barry Warsawdadebab2012-07-31 16:03:09 -0400762path entry. Because this can be an expensive operation (e.g. there may be
Nick Coghlan1685db02012-08-20 13:49:08 +1000763`stat()` call overheads for this search), the path based finder maintains
Barry Warsawdadebab2012-07-31 16:03:09 -0400764a cache mapping path entries to path entry finders. This cache is maintained
Nick Coghlan1685db02012-08-20 13:49:08 +1000765in :data:`sys.path_importer_cache` (despite the name, this cache actually
766stores finder objects rather than being limited to :term:`importer` objects).
767In this way, the expensive search for a particular :term:`path entry`
768location's :term:`path entry finder` need only be done once. User code is
769free to remove cache entries from :data:`sys.path_importer_cache` forcing
770the path based finder to perform the path entry search again [#fnpic]_.
Barry Warsawd7d21942012-07-29 16:36:17 -0400771
Nick Coghlan1685db02012-08-20 13:49:08 +1000772If the path entry is not present in the cache, the path based finder iterates
Barry Warsaw82c1c782012-11-20 15:22:51 -0500773over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry
774hooks <path entry hook>` in this list is called with a single argument, the
775path entry to be searched. This callable may either return a :term:`path
776entry finder` that can handle the path entry, or it may raise
777:exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to
Eric Snow7cff4cd2013-12-16 23:10:50 -0700778signal that the hook cannot find a :term:`path entry finder`.
779for that :term:`path entry`. The
780exception is ignored and :term:`import path` iteration continues. The hook
781should expect either a string or bytes object; the encoding of bytes objects
782is up to the hook (e.g. it may be a file system encoding, UTF-8, or something
783else), and if the hook cannot decode the argument, it should raise
784:exc:`ImportError`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400785
Barry Warsawdadebab2012-07-31 16:03:09 -0400786If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder`
Eric Snow7cff4cd2013-12-16 23:10:50 -0700787being returned, then the path based finder's
788:meth:`~importlib.machinery.PathFinder.find_spec` method will store ``None``
789in :data:`sys.path_importer_cache` (to indicate that there is no finder for
790this path entry) and return ``None``, indicating that this
791:term:`meta path finder` could not find the module.
Barry Warsawd7d21942012-07-29 16:36:17 -0400792
Barry Warsawdadebab2012-07-31 16:03:09 -0400793If a :term:`path entry finder` *is* returned by one of the :term:`path entry
794hook` callables on :data:`sys.path_hooks`, then the following protocol is used
Eric Snowb523f842013-11-22 09:05:39 -0700795to ask the finder for a module spec, which is then used when loading the
796module.
Barry Warsawd7d21942012-07-29 16:36:17 -0400797
Brett Cannonb6e25562014-11-21 12:19:28 -0500798The current working directory -- denoted by an empty string -- is handled
799slightly differently from other entries on :data:`sys.path`. First, if the
800current working directory is found to not exist, no value is stored in
801:data:`sys.path_importer_cache`. Second, the value for the current working
802directory is looked up fresh for each module lookup. Third, the path used for
803:data:`sys.path_importer_cache` and returned by
804:meth:`importlib.machinery.PathFinder.find_spec` will be the actual current
805working directory and not the empty string.
806
Barry Warsawdadebab2012-07-31 16:03:09 -0400807Path entry finder protocol
808--------------------------
Barry Warsawd7d21942012-07-29 16:36:17 -0400809
Nick Coghlan49417742012-08-02 23:03:58 +1000810In order to support imports of modules and initialized packages and also to
811contribute portions to namespace packages, path entry finders must implement
Eric Snow7cff4cd2013-12-16 23:10:50 -0700812the :meth:`~importlib.abc.PathEntryFinder.find_spec` method.
Barry Warsawd7d21942012-07-29 16:36:17 -0400813
Eric Snow7cff4cd2013-12-16 23:10:50 -0700814:meth:`~importlib.abc.PathEntryFinder.find_spec` takes two argument, the
815fully qualified name of the module being imported, and the (optional) target
816module. ``find_spec()`` returns a fully populated spec for the module.
817This spec will always have "loader" set (with one exception).
Barry Warsawd7d21942012-07-29 16:36:17 -0400818
Eric Snowb523f842013-11-22 09:05:39 -0700819To indicate to the import machinery that the spec represents a namespace
820:term:`portion`. the path entry finder sets "loader" on the spec to
821``None`` and "submodule_search_locations" to a list containing the
822portion.
Nick Coghlan49417742012-08-02 23:03:58 +1000823
Eric Snowb523f842013-11-22 09:05:39 -0700824.. versionchanged:: 3.4
Eric Snow7cff4cd2013-12-16 23:10:50 -0700825 :meth:`~importlib.abc.PathEntryFinder.find_spec` replaced
826 :meth:`~importlib.abc.PathEntryFinder.find_loader` and
827 :meth:`~importlib.abc.PathEntryFinder.find_module`, both of which
828 are now deprecated, but will be used if ``find_spec()`` is not defined.
Nick Coghlan49417742012-08-02 23:03:58 +1000829
Eric Snowb523f842013-11-22 09:05:39 -0700830 Older path entry finders may implement one of these two deprecated methods
Eric Snow7cff4cd2013-12-16 23:10:50 -0700831 instead of ``find_spec()``. The methods are still respected for the
832 sake of backward compatibility. Howevever, if ``find_spec()`` is
833 implemented on the path entry finder, the legacy methods are ignored.
Eric Snowb523f842013-11-22 09:05:39 -0700834
Eric Snow7cff4cd2013-12-16 23:10:50 -0700835 :meth:`~importlib.abc.PathEntryFinder.find_loader` takes one argument, the
836 fully qualified name of the module being imported. ``find_loader()``
837 returns a 2-tuple where the first item is the loader and the second item
838 is a namespace :term:`portion`. When the first item (i.e. the loader) is
839 ``None``, this means that while the path entry finder does not have a
840 loader for the named module, it knows that the path entry contributes to
841 a namespace portion for the named module. This will almost always be the
842 case where Python is asked to import a namespace package that has no
843 physical presence on the file system. When a path entry finder returns
844 ``None`` for the loader, the second item of the 2-tuple return value must
845 be a sequence, although it can be empty.
Eric Snowb523f842013-11-22 09:05:39 -0700846
Eric Snow7cff4cd2013-12-16 23:10:50 -0700847 If ``find_loader()`` returns a non-``None`` loader value, the portion is
Eric Snowb523f842013-11-22 09:05:39 -0700848 ignored and the loader is returned from the path based finder, terminating
849 the search through the path entries.
850
851 For backwards compatibility with other implementations of the import
852 protocol, many path entry finders also support the same,
Eric Snow7cff4cd2013-12-16 23:10:50 -0700853 traditional ``find_module()`` method that meta path finders support.
854 However path entry finder ``find_module()`` methods are never called
Eric Snowb523f842013-11-22 09:05:39 -0700855 with a ``path`` argument (they are expected to record the appropriate
856 path information from the initial call to the path hook).
857
Eric Snow7cff4cd2013-12-16 23:10:50 -0700858 The ``find_module()`` method on path entry finders is deprecated,
Eric Snowb523f842013-11-22 09:05:39 -0700859 as it does not allow the path entry finder to contribute portions to
Eric Snow7cff4cd2013-12-16 23:10:50 -0700860 namespace packages. If both ``find_loader()`` and ``find_module()``
Eric Snowb523f842013-11-22 09:05:39 -0700861 exist on a path entry finder, the import system will always call
Eric Snow7cff4cd2013-12-16 23:10:50 -0700862 ``find_loader()`` in preference to ``find_module()``.
Nick Coghlan49417742012-08-02 23:03:58 +1000863
864
865Replacing the standard import system
866====================================
867
868The most reliable mechanism for replacing the entire import system is to
869delete the default contents of :data:`sys.meta_path`, replacing them
870entirely with a custom meta path hook.
871
872If it is acceptable to only alter the behaviour of import statements
873without affecting other APIs that access the import system, then replacing
874the builtin :func:`__import__` function may be sufficient. This technique
875may also be employed at the module level to only alter the behaviour of
876import statements within that module.
877
878To selectively prevent import of some modules from a hook early on the
879meta path (rather than disabling the standard import system entirely),
Brett Cannon82da8882013-07-04 17:48:16 -0400880it is sufficient to raise :exc:`ImportError` directly from
Eric Snow7cff4cd2013-12-16 23:10:50 -0700881:meth:`~importlib.abc.MetaPathFinder.find_spec` instead of returning
882``None``. The latter indicates that the meta path search should continue,
883while raising an exception terminates it immediately.
Barry Warsawd7d21942012-07-29 16:36:17 -0400884
885
Eric Snowe50f9aa2014-03-28 18:10:33 -0600886Special considerations for __main__
887===================================
888
889The :mod:`__main__` module is a special case relative to Python's import
890system. As noted :ref:`elsewhere <programs>`, the ``__main__`` module
891is directly initialized at interpreter startup, much like :mod:`sys` and
892:mod:`builtins`. However, unlike those two, it doesn't strictly
893qualify as a built-in module. This is because the manner in which
894``__main__`` is initialized depends on the flags and other options with
895which the interpreter is invoked.
896
897.. _main_spec:
898
899__main__.__spec__
900-----------------
901
902Depending on how :mod:`__main__` is initialized, ``__main__.__spec__``
903gets set appropriately or to ``None``.
904
905When Python is started with the :option:`-m` option, ``__spec__`` is set
Nick Coghlan9aa00d12014-03-29 15:39:42 +1000906to the module spec of the corresponding module or package. ``__spec__`` is
907also populated when the ``__main__`` module is loaded as part of executing a
908directory, zipfile or other :data:`sys.path` entry.
Eric Snowe50f9aa2014-03-28 18:10:33 -0600909
910In :ref:`the remaining cases <using-on-interface-options>`
Nick Coghlan9aa00d12014-03-29 15:39:42 +1000911``__main__.__spec__`` is set to ``None``, as the code used to populate the
912:mod:`__main__` does not correspond directly with an importable module:
Eric Snowe50f9aa2014-03-28 18:10:33 -0600913
914- interactive prompt
915- -c switch
916- running from stdin
917- running directly from a source or bytecode file
918
Nick Coghlan9aa00d12014-03-29 15:39:42 +1000919Note that ``__main__.__spec__`` is always ``None`` in the last case,
920*even if* the file could technically be imported directly as a module
921instead. Use the :option:`-m` switch if valid module metadata is desired
922in :mod:`__main__`.
923
924Note also that even when ``__main__`` corresponds with an importable module
925and ``__main__.__spec__`` is set accordingly, they're still considered
926*distinct* modules. This is due to the fact that blocks guarded by
927``if __name__ == "__main__":`` checks only execute when the module is used
928to populate the ``__main__`` namespace, and not during normal import.
929
Eric Snowe50f9aa2014-03-28 18:10:33 -0600930
Barry Warsawd7d21942012-07-29 16:36:17 -0400931Open issues
932===========
933
Barry Warsawd7d21942012-07-29 16:36:17 -0400934XXX It would be really nice to have a diagram.
935
Barry Warsawc1e721b2012-07-30 16:24:12 -0400936XXX * (import_machinery.rst) how about a section devoted just to the
937attributes of modules and packages, perhaps expanding upon or supplanting the
938related entries in the data model reference page?
939
Barry Warsawdadebab2012-07-31 16:03:09 -0400940XXX runpy, pkgutil, et al in the library manual should all get "See Also"
941links at the top pointing to the new import system section.
942
Eric Snowe50f9aa2014-03-28 18:10:33 -0600943XXX Add more explanation regarding the different ways in which
944``__main__`` is initialized?
945
946XXX Add more info on ``__main__`` quirks/pitfalls (i.e. copy from
947:pep:`395`).
948
Barry Warsawd7d21942012-07-29 16:36:17 -0400949
950References
951==========
952
953The import machinery has evolved considerably since Python's early days. The
954original `specification for packages
Georg Brandl525d3552014-10-29 10:26:56 +0100955<http://legacy.python.org/doc/essays/packages.html>`_ is still available to read,
Barry Warsawd7d21942012-07-29 16:36:17 -0400956although some details have changed since the writing of that document.
957
958The original specification for :data:`sys.meta_path` was :pep:`302`, with
Barry Warsawdadebab2012-07-31 16:03:09 -0400959subsequent extension in :pep:`420`.
960
961:pep:`420` introduced :term:`namespace packages <namespace package>` for
962Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as an
963alternative to :meth:`find_module`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400964
965:pep:`366` describes the addition of the ``__package__`` attribute for
966explicit relative imports in main modules.
Barry Warsawc1e721b2012-07-30 16:24:12 -0400967
Nick Coghlan1685db02012-08-20 13:49:08 +1000968:pep:`328` introduced absolute and explicit relative imports and initially
969proposed ``__name__`` for semantics :pep:`366` would eventually specify for
Barry Warsawdadebab2012-07-31 16:03:09 -0400970``__package__``.
971
972:pep:`338` defines executing modules as scripts.
973
Eric Snowb523f842013-11-22 09:05:39 -0700974:pep:`451` adds the encapsulation of per-module import state in spec
975objects. It also off-loads most of the boilerplate responsibilities of
976loaders back onto the import machinery. These changes allow the
977deprecation of several APIs in the import system and also addition of new
978methods to finders and loaders.
Barry Warsawc1e721b2012-07-30 16:24:12 -0400979
Georg Brandl44ea77b2013-03-28 13:28:44 +0100980.. rubric:: Footnotes
Barry Warsawc1e721b2012-07-30 16:24:12 -0400981
982.. [#fnmo] See :class:`types.ModuleType`.
983
Nick Coghlan1685db02012-08-20 13:49:08 +1000984.. [#fnlo] The importlib implementation avoids using the return value
Barry Warsawc1e721b2012-07-30 16:24:12 -0400985 directly. Instead, it gets the module object by looking the module name up
Nick Coghlan1685db02012-08-20 13:49:08 +1000986 in :data:`sys.modules`. The indirect effect of this is that an imported
Barry Warsawc1e721b2012-07-30 16:24:12 -0400987 module may replace itself in :data:`sys.modules`. This is
988 implementation-specific behavior that is not guaranteed to work in other
989 Python implementations.
990
Barry Warsawc1e721b2012-07-30 16:24:12 -0400991.. [#fnpic] In legacy code, it is possible to find instances of
992 :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It
Nick Coghlan1685db02012-08-20 13:49:08 +1000993 is recommended that code be changed to use ``None`` instead. See
Barry Warsawc1e721b2012-07-30 16:24:12 -0400994 :ref:`portingpythoncode` for more details.