blob: b587fc9c98fe3478910b21da811638cb92b2bb09 [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,
203:func:`imp.reload` will reuse the *same* module object, and simply
204reinitialise 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
213
Barry Warsawdadebab2012-07-31 16:03:09 -0400214If the named module is not found in :data:`sys.modules`, then Python's import
215protocol is invoked to find and load the module. This protocol consists of
216two conceptual objects, :term:`finders <finder>` and :term:`loaders <loader>`.
217A finder's job is to determine whether it can find the named module using
Nick Coghlan49417742012-08-02 23:03:58 +1000218whatever strategy it knows about. Objects that implement both of these
219interfaces are referred to as :term:`importers <importer>` - they return
220themselves when they find that they can load the requested module.
Barry Warsawdadebab2012-07-31 16:03:09 -0400221
Andrew Svetlove2cf03e2012-11-15 16:28:21 +0200222Python includes a number of default finders and importers. The first one
223knows how to locate built-in modules, and the second knows how to locate
224frozen modules. A third default finder searches an :term:`import path`
Nick Coghlan49417742012-08-02 23:03:58 +1000225for modules. The :term:`import path` is a list of locations that may
226name file system paths or zip files. It can also be extended to search
227for any locatable resource, such as those identified by URLs.
Barry Warsawdadebab2012-07-31 16:03:09 -0400228
229The import machinery is extensible, so new finders can be added to extend the
230range and scope of module searching.
Barry Warsawd7d21942012-07-29 16:36:17 -0400231
232Finders do not actually load modules. If they can find the named module, they
Barry Warsawdadebab2012-07-31 16:03:09 -0400233return a :term:`loader`, which the import machinery then invokes to load the
234module and create the corresponding module object.
Barry Warsawd7d21942012-07-29 16:36:17 -0400235
236The following sections describe the protocol for finders and loaders in more
237detail, including how you can create and register new ones to extend the
238import machinery.
239
240
241Import hooks
242------------
243
244.. index::
245 single: import hooks
246 single: meta hooks
247 single: path hooks
248 pair: hooks; import
249 pair: hooks; meta
250 pair: hooks; path
251
252The import machinery is designed to be extensible; the primary mechanism for
253this are the *import hooks*. There are two types of import hooks: *meta
Barry Warsawdadebab2012-07-31 16:03:09 -0400254hooks* and *import path hooks*.
Barry Warsawd7d21942012-07-29 16:36:17 -0400255
256Meta hooks are called at the start of import processing, before any other
Barry Warsawdadebab2012-07-31 16:03:09 -0400257import processing has occurred, other than :data:`sys.modules` cache look up.
258This allows meta hooks to override :data:`sys.path` processing, frozen
259modules, or even built-in modules. Meta hooks are registered by adding new
260finder objects to :data:`sys.meta_path`, as described below.
Barry Warsawd7d21942012-07-29 16:36:17 -0400261
Barry Warsawdadebab2012-07-31 16:03:09 -0400262Import path hooks are called as part of :data:`sys.path` (or
263``package.__path__``) processing, at the point where their associated path
264item is encountered. Import path hooks are registered by adding new callables
265to :data:`sys.path_hooks` as described below.
Barry Warsawd7d21942012-07-29 16:36:17 -0400266
267
268The meta path
269-------------
270
271.. index::
272 single: sys.meta_path
273 pair: finder; find_module
274 pair: finder; find_loader
275
276When the named module is not found in :data:`sys.modules`, Python next
277searches :data:`sys.meta_path`, which contains a list of meta path finder
278objects. These finders are queried in order to see if they know how to handle
279the named module. Meta path finders must implement a method called
Barry Warsawdadebab2012-07-31 16:03:09 -0400280:meth:`find_module()` which takes two arguments, a name and an import path.
281The meta path finder can use any strategy it wants to determine whether it can
282handle the named module or not.
Barry Warsawd7d21942012-07-29 16:36:17 -0400283
284If the meta path finder knows how to handle the named module, it returns a
285loader object. If it cannot handle the named module, it returns ``None``. If
286:data:`sys.meta_path` processing reaches the end of its list without returning
Brett Cannon82da8882013-07-04 17:48:16 -0400287a loader, then an :exc:`ImportError` is raised. Any other exceptions raised
Barry Warsawd7d21942012-07-29 16:36:17 -0400288are simply propagated up, aborting the import process.
289
290The :meth:`find_module()` method of meta path finders is called with two
291arguments. The first is the fully qualified name of the module being
Nick Coghlan49417742012-08-02 23:03:58 +1000292imported, for example ``foo.bar.baz``. The second argument is the path
293entries to use for the module search. For top-level modules, the second
294argument is ``None``, but for submodules or subpackages, the second
295argument is the value of the parent package's ``__path__`` attribute. If
296the appropriate ``__path__`` attribute cannot be accessed, an
297:exc:`ImportError` is raised.
298
299The meta path may be traversed multiple times for a single import request.
300For example, assuming none of the modules involved has already been cached,
301importing ``foo.bar.baz`` will first perform a top level import, calling
302``mpf.find_module("foo", None)`` on each meta path finder (``mpf``). After
303``foo`` has been imported, ``foo.bar`` will be imported by traversing the
304meta path a second time, calling
305``mpf.find_module("foo.bar", foo.__path__)``. Once ``foo.bar`` has been
306imported, the final traversal will call
307``mpf.find_module("foo.bar.baz", foo.bar.__path__)``.
308
309Some meta path finders only support top level imports. These importers will
310always return ``None`` when anything other than ``None`` is passed as the
311second argument.
Barry Warsawd7d21942012-07-29 16:36:17 -0400312
313Python's default :data:`sys.meta_path` has three meta path finders, one that
314knows how to import built-in modules, one that knows how to import frozen
Barry Warsawdadebab2012-07-31 16:03:09 -0400315modules, and one that knows how to import modules from an :term:`import path`
Nick Coghlan1685db02012-08-20 13:49:08 +1000316(i.e. the :term:`path based finder`).
Barry Warsawd7d21942012-07-29 16:36:17 -0400317
318
Barry Warsawdadebab2012-07-31 16:03:09 -0400319Loaders
320=======
Barry Warsawd7d21942012-07-29 16:36:17 -0400321
Barry Warsawdadebab2012-07-31 16:03:09 -0400322If and when a module loader is found its
Barry Warsawc1e721b2012-07-30 16:24:12 -0400323:meth:`~importlib.abc.Loader.load_module` method is called, with a single
324argument, the fully qualified name of the module being imported. This method
325has several responsibilities, and should return the module object it has
326loaded [#fnlo]_. If it cannot load the module, it should raise an
327:exc:`ImportError`, although any other exception raised during
328:meth:`load_module()` will be propagated.
Barry Warsawd7d21942012-07-29 16:36:17 -0400329
Barry Warsawdadebab2012-07-31 16:03:09 -0400330In many cases, the finder and loader can be the same object; in such cases the
331:meth:`finder.find_module()` would just return ``self``.
Barry Warsawd7d21942012-07-29 16:36:17 -0400332
333Loaders must satisfy the following requirements:
334
335 * If there is an existing module object with the given name in
336 :data:`sys.modules`, the loader must use that existing module. (Otherwise,
Nick Coghlan49417742012-08-02 23:03:58 +1000337 :func:`imp.reload` will not work correctly.) If the named module does
Barry Warsawc1e721b2012-07-30 16:24:12 -0400338 not exist in :data:`sys.modules`, the loader must create a new module
Barry Warsawd7d21942012-07-29 16:36:17 -0400339 object and add it to :data:`sys.modules`.
340
341 Note that the module *must* exist in :data:`sys.modules` before the loader
342 executes the module code. This is crucial because the module code may
343 (directly or indirectly) import itself; adding it to :data:`sys.modules`
344 beforehand prevents unbounded recursion in the worst case and multiple
345 loading in the best.
346
Barry Warsawdadebab2012-07-31 16:03:09 -0400347 If loading fails, the loader must remove any modules it has inserted into
348 :data:`sys.modules`, but it must remove **only** the failing module, and
349 only if the loader itself has loaded it explicitly. Any module already in
350 the :data:`sys.modules` cache, and any module that was successfully loaded
351 as a side-effect, must remain in the cache.
Barry Warsawd7d21942012-07-29 16:36:17 -0400352
353 * The loader may set the ``__file__`` attribute of the module. If set, this
354 attribute's value must be a string. The loader may opt to leave
355 ``__file__`` unset if it has no semantic meaning (e.g. a module loaded from
Brett Cannon4b4e38e2013-05-25 11:32:50 -0400356 a database). If ``__file__`` is set, it may also be appropriate to set the
357 ``__cached__`` attribute which is the path to any compiled version of the
358 code (e.g. byte-compiled file). The file does not need to exist to set this
359 attribute; the path can simply point to whether the compiled file would
360 exist (see :pep:`3147`).
Barry Warsawd7d21942012-07-29 16:36:17 -0400361
362 * The loader may set the ``__name__`` attribute of the module. While not
363 required, setting this attribute is highly recommended so that the
364 :meth:`repr()` of the module is more informative.
365
Nick Coghlan49417742012-08-02 23:03:58 +1000366 * If the module is a package (either regular or namespace), the loader must
367 set the module object's ``__path__`` attribute. The value must be
368 iterable, but may be empty if ``__path__`` has no further significance
Nick Coghlan1685db02012-08-20 13:49:08 +1000369 to the loader. If ``__path__`` is not empty, it must produce strings
Nick Coghlan49417742012-08-02 23:03:58 +1000370 when iterated over. More details on the semantics of ``__path__`` are
Georg Brandla81b4812012-08-11 08:43:59 +0200371 given :ref:`below <package-path-rules>`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400372
373 * The ``__loader__`` attribute must be set to the loader object that loaded
374 the module. This is mostly for introspection and reloading, but can be
Nick Coghlan1685db02012-08-20 13:49:08 +1000375 used for additional loader-specific functionality, for example getting
Brett Cannon4802bec2013-03-13 10:41:36 -0700376 data associated with a loader. If the attribute is missing or set to ``None``
377 then the import machinery will automatically set it **after** the module has
378 been imported.
Barry Warsawd7d21942012-07-29 16:36:17 -0400379
Brett Cannon4802bec2013-03-13 10:41:36 -0700380 * The module's ``__package__`` attribute must be set. Its value must be a
Barry Warsawdadebab2012-07-31 16:03:09 -0400381 string, but it can be the same value as its ``__name__``. If the attribute
382 is set to ``None`` or is missing, the import system will fill it in with a
Brett Cannon4802bec2013-03-13 10:41:36 -0700383 more appropriate value **after** the module has been imported.
384 When the module is a package, its ``__package__`` value should be set to its
385 ``__name__``. When the module is not a package, ``__package__`` should be
386 set to the empty string for top-level modules, or for submodules, to the
387 parent package's name. See :pep:`366` for further details.
Barry Warsawd7d21942012-07-29 16:36:17 -0400388
389 This attribute is used instead of ``__name__`` to calculate explicit
390 relative imports for main modules, as defined in :pep:`366`.
391
392 * If the module is a Python module (as opposed to a built-in module or a
Barry Warsawc1e721b2012-07-30 16:24:12 -0400393 dynamically loaded extension), the loader should execute the module's code
394 in the module's global name space (``module.__dict__``).
Barry Warsawd7d21942012-07-29 16:36:17 -0400395
396
397Module reprs
398------------
399
400By default, all modules have a usable repr, however depending on the
Barry Warsawc1e721b2012-07-30 16:24:12 -0400401attributes set above, and hooks in the loader, you can more explicitly control
Barry Warsawd7d21942012-07-29 16:36:17 -0400402the repr of module objects.
403
404Loaders may implement a :meth:`module_repr()` method which takes a single
405argument, the module object. When ``repr(module)`` is called for a module
406with a loader supporting this protocol, whatever is returned from
Barry Warsawc1e721b2012-07-30 16:24:12 -0400407``module.__loader__.module_repr(module)`` is returned as the module's repr
408without further processing. This return value must be a string.
Barry Warsawd7d21942012-07-29 16:36:17 -0400409
410If the module has no ``__loader__`` attribute, or the loader has no
411:meth:`module_repr()` method, then the module object implementation itself
412will craft a default repr using whatever information is available. It will
413try to use the ``module.__name__``, ``module.__file__``, and
414``module.__loader__`` as input into the repr, with defaults for whatever
415information is missing.
416
417Here are the exact rules used:
418
Nick Coghlan49417742012-08-02 23:03:58 +1000419 * If the module has a ``__loader__`` and that loader has a
Barry Warsawd7d21942012-07-29 16:36:17 -0400420 :meth:`module_repr()` method, call it with a single argument, which is the
421 module object. The value returned is used as the module's repr.
422
423 * If an exception occurs in :meth:`module_repr()`, the exception is caught
424 and discarded, and the calculation of the module's repr continues as if
425 :meth:`module_repr()` did not exist.
426
Nick Coghlan49417742012-08-02 23:03:58 +1000427 * If the module has a ``__file__`` attribute, this is used as part of the
Barry Warsawd7d21942012-07-29 16:36:17 -0400428 module's repr.
429
Brett Cannon4c14b5d2013-05-04 13:56:58 -0400430 * If the module has no ``__file__`` but does have a ``__loader__`` that is not
431 ``None``, then the loader's repr is used as part of the module's repr.
Barry Warsawd7d21942012-07-29 16:36:17 -0400432
433 * Otherwise, just use the module's ``__name__`` in the repr.
434
435This example, from :pep:`420` shows how a loader can craft its own module
436repr::
437
438 class NamespaceLoader:
439 @classmethod
440 def module_repr(cls, module):
441 return "<module '{}' (namespace)>".format(module.__name__)
442
443
Nick Coghlan49417742012-08-02 23:03:58 +1000444.. _package-path-rules:
445
Barry Warsawd7d21942012-07-29 16:36:17 -0400446module.__path__
447---------------
448
449By definition, if a module has an ``__path__`` attribute, it is a package,
450regardless of its value.
451
452A package's ``__path__`` attribute is used during imports of its subpackages.
453Within the import machinery, it functions much the same as :data:`sys.path`,
454i.e. providing a list of locations to search for modules during import.
455However, ``__path__`` is typically much more constrained than
456:data:`sys.path`.
457
Nick Coghlan49417742012-08-02 23:03:58 +1000458``__path__`` must be an iterable of strings, but it may be empty.
459The same rules used for :data:`sys.path` also apply to a package's
460``__path__``, and :data:`sys.path_hooks` (described below) are
461consulted when traversing a package's ``__path__``.
Barry Warsawd7d21942012-07-29 16:36:17 -0400462
463A package's ``__init__.py`` file may set or alter the package's ``__path__``
464attribute, and this was typically the way namespace packages were implemented
465prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no
466longer need to supply ``__init__.py`` files containing only ``__path__``
467manipulation code; the namespace loader automatically sets ``__path__``
468correctly for the namespace package.
469
470
Nick Coghlan1685db02012-08-20 13:49:08 +1000471The Path Based Finder
472=====================
Barry Warsawd7d21942012-07-29 16:36:17 -0400473
474.. index::
Nick Coghlan1685db02012-08-20 13:49:08 +1000475 single: path based finder
Barry Warsawd7d21942012-07-29 16:36:17 -0400476
477As mentioned previously, Python comes with several default meta path finders.
Nick Coghlan1685db02012-08-20 13:49:08 +1000478One of these, called the :term:`path based finder`, searches an :term:`import
Barry Warsawdadebab2012-07-31 16:03:09 -0400479path`, which contains a list of :term:`path entries <path entry>`. Each path
480entry names a location to search for modules.
Barry Warsawd7d21942012-07-29 16:36:17 -0400481
Nick Coghlan1685db02012-08-20 13:49:08 +1000482The path based finder itself doesn't know how to import anything. Instead, it
Nick Coghlan49417742012-08-02 23:03:58 +1000483traverses the individual path entries, associating each of them with a
484path entry finder that knows how to handle that particular kind of path.
485
486The default set of path entry finders implement all the semantics for finding
487modules on the file system, handling special file types such as Python source
488code (``.py`` files), Python byte code (``.pyc`` and ``.pyo`` files) and
489shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport`
490module in the standard library, the default path entry finders also handle
491loading all of these file types (other than shared libraries) from zipfiles.
Barry Warsawdadebab2012-07-31 16:03:09 -0400492
493Path entries need not be limited to file system locations. They can refer to
Nick Coghlan1685db02012-08-20 13:49:08 +1000494URLs, database queries, or any other location that can be specified as a
Nick Coghlan49417742012-08-02 23:03:58 +1000495string.
Barry Warsawdadebab2012-07-31 16:03:09 -0400496
Nick Coghlan1685db02012-08-20 13:49:08 +1000497The path based finder provides additional hooks and protocols so that you
Barry Warsawdadebab2012-07-31 16:03:09 -0400498can extend and customize the types of searchable path entries. For example,
499if you wanted to support path entries as network URLs, you could write a hook
500that implements HTTP semantics to find modules on the web. This hook (a
501callable) would return a :term:`path entry finder` supporting the protocol
502described below, which was then used to get a loader for the module from the
503web.
Barry Warsawd7d21942012-07-29 16:36:17 -0400504
505A word of warning: this section and the previous both use the term *finder*,
506distinguishing between them by using the terms :term:`meta path finder` and
Barry Warsawdadebab2012-07-31 16:03:09 -0400507:term:`path entry finder`. These two types of finders are very similar,
508support similar protocols, and function in similar ways during the import
509process, but it's important to keep in mind that they are subtly different.
510In particular, meta path finders operate at the beginning of the import
511process, as keyed off the :data:`sys.meta_path` traversal.
Barry Warsawd7d21942012-07-29 16:36:17 -0400512
Nick Coghlan1685db02012-08-20 13:49:08 +1000513By contrast, path entry finders are in a sense an implementation detail
514of the path based finder, and in fact, if the path based finder were to be
Barry Warsawdadebab2012-07-31 16:03:09 -0400515removed from :data:`sys.meta_path`, none of the path entry finder semantics
516would be invoked.
Barry Warsawd7d21942012-07-29 16:36:17 -0400517
518
Barry Warsawdadebab2012-07-31 16:03:09 -0400519Path entry finders
520------------------
Barry Warsawd7d21942012-07-29 16:36:17 -0400521
522.. index::
523 single: sys.path
524 single: sys.path_hooks
525 single: sys.path_importer_cache
526 single: PYTHONPATH
527
Nick Coghlan1685db02012-08-20 13:49:08 +1000528The :term:`path based finder` is responsible for finding and loading Python
Barry Warsawdadebab2012-07-31 16:03:09 -0400529modules and packages whose location is specified with a string :term:`path
530entry`. Most path entries name locations in the file system, but they need
531not be limited to this.
532
Nick Coghlan1685db02012-08-20 13:49:08 +1000533As a meta path finder, the :term:`path based finder` implements the
Barry Warsawd7d21942012-07-29 16:36:17 -0400534:meth:`find_module()` protocol previously described, however it exposes
535additional hooks that can be used to customize how modules are found and
Barry Warsawdadebab2012-07-31 16:03:09 -0400536loaded from the :term:`import path`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400537
Nick Coghlan1685db02012-08-20 13:49:08 +1000538Three variables are used by the :term:`path based finder`, :data:`sys.path`,
Barry Warsawdadebab2012-07-31 16:03:09 -0400539:data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__``
Nick Coghlan49417742012-08-02 23:03:58 +1000540attributes on package objects are also used. These provide additional ways
541that the import machinery can be customized.
Barry Warsawd7d21942012-07-29 16:36:17 -0400542
543:data:`sys.path` contains a list of strings providing search locations for
544modules and packages. It is initialized from the :data:`PYTHONPATH`
545environment variable and various other installation- and
546implementation-specific defaults. Entries in :data:`sys.path` can name
547directories on the file system, zip files, and potentially other "locations"
Barry Warsawdadebab2012-07-31 16:03:09 -0400548(see the :mod:`site` module) that should be searched for modules, such as
Barry Warsaw82c1c782012-11-20 15:22:51 -0500549URLs, or database queries. Only strings and bytes should be present on
550:data:`sys.path`; all other data types are ignored. The encoding of bytes
551entries is determined by the individual :term:`path entry finders <path entry
552finder>`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400553
Nick Coghlan1685db02012-08-20 13:49:08 +1000554The :term:`path based finder` is a :term:`meta path finder`, so the import
Nick Coghlan49417742012-08-02 23:03:58 +1000555machinery begins the :term:`import path` search by calling the path
Nick Coghlan1685db02012-08-20 13:49:08 +1000556based finder's :meth:`find_module()` method as described previously. When
Nick Coghlan49417742012-08-02 23:03:58 +1000557the ``path`` argument to :meth:`find_module()` is given, it will be a
558list of string paths to traverse - typically a package's ``__path__``
559attribute for an import within that package. If the ``path`` argument
560is ``None``, this indicates a top level import and :data:`sys.path` is used.
Barry Warsawd7d21942012-07-29 16:36:17 -0400561
Nick Coghlan1685db02012-08-20 13:49:08 +1000562The path based finder iterates over every entry in the search path, and
Barry Warsawdadebab2012-07-31 16:03:09 -0400563for each of these, looks for an appropriate :term:`path entry finder` for the
564path entry. Because this can be an expensive operation (e.g. there may be
Nick Coghlan1685db02012-08-20 13:49:08 +1000565`stat()` call overheads for this search), the path based finder maintains
Barry Warsawdadebab2012-07-31 16:03:09 -0400566a cache mapping path entries to path entry finders. This cache is maintained
Nick Coghlan1685db02012-08-20 13:49:08 +1000567in :data:`sys.path_importer_cache` (despite the name, this cache actually
568stores finder objects rather than being limited to :term:`importer` objects).
569In this way, the expensive search for a particular :term:`path entry`
570location's :term:`path entry finder` need only be done once. User code is
571free to remove cache entries from :data:`sys.path_importer_cache` forcing
572the path based finder to perform the path entry search again [#fnpic]_.
Barry Warsawd7d21942012-07-29 16:36:17 -0400573
Nick Coghlan1685db02012-08-20 13:49:08 +1000574If the path entry is not present in the cache, the path based finder iterates
Barry Warsaw82c1c782012-11-20 15:22:51 -0500575over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry
576hooks <path entry hook>` in this list is called with a single argument, the
577path entry to be searched. This callable may either return a :term:`path
578entry finder` that can handle the path entry, or it may raise
579:exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to
580signal that the hook cannot find a :term:`path entry finder` for that
581:term:`path entry`. The exception is ignored and :term:`import path`
582iteration continues. The hook should expect either a string or bytes object;
583the encoding of bytes objects is up to the hook (e.g. it may be a file system
584encoding, UTF-8, or something else), and if the hook cannot decode the
585argument, it should raise :exc:`ImportError`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400586
Barry Warsawdadebab2012-07-31 16:03:09 -0400587If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder`
Nick Coghlan1685db02012-08-20 13:49:08 +1000588being returned, then the path based finder's :meth:`find_module()` method
589will store ``None`` in :data:`sys.path_importer_cache` (to indicate that
590there is no finder for this path entry) and return ``None``, indicating that
Nick Coghlan49417742012-08-02 23:03:58 +1000591this :term:`meta path finder` could not find the module.
Barry Warsawd7d21942012-07-29 16:36:17 -0400592
Barry Warsawdadebab2012-07-31 16:03:09 -0400593If a :term:`path entry finder` *is* returned by one of the :term:`path entry
594hook` callables on :data:`sys.path_hooks`, then the following protocol is used
595to ask the finder for a module loader, which is then used to load the module.
Barry Warsawd7d21942012-07-29 16:36:17 -0400596
597
Barry Warsawdadebab2012-07-31 16:03:09 -0400598Path entry finder protocol
599--------------------------
Barry Warsawd7d21942012-07-29 16:36:17 -0400600
Nick Coghlan49417742012-08-02 23:03:58 +1000601In order to support imports of modules and initialized packages and also to
602contribute portions to namespace packages, path entry finders must implement
603the :meth:`find_loader()` method.
Barry Warsawd7d21942012-07-29 16:36:17 -0400604
605:meth:`find_loader()` takes one argument, the fully qualified name of the
606module being imported. :meth:`find_loader()` returns a 2-tuple where the
607first item is the loader and the second item is a namespace :term:`portion`.
608When the first item (i.e. the loader) is ``None``, this means that while the
Nick Coghlan49417742012-08-02 23:03:58 +1000609path entry finder does not have a loader for the named module, it knows that the
610path entry contributes to a namespace portion for the named module. This will
611almost always be the case where Python is asked to import a namespace package
612that has no physical presence on the file system. When a path entry finder
613returns ``None`` for the loader, the second item of the 2-tuple return value
614must be a sequence, although it can be empty.
Barry Warsawd7d21942012-07-29 16:36:17 -0400615
616If :meth:`find_loader()` returns a non-``None`` loader value, the portion is
Nick Coghlan1685db02012-08-20 13:49:08 +1000617ignored and the loader is returned from the path based finder, terminating
618the search through the path entries.
Nick Coghlan49417742012-08-02 23:03:58 +1000619
620For backwards compatibility with other implementations of the import
621protocol, many path entry finders also support the same,
622traditional :meth:`find_module()` method that meta path finders support.
623However path entry finder :meth:`find_module()` methods are never called
624with a ``path`` argument (they are expected to record the appropriate
625path information from the initial call to the path hook).
626
627The :meth:`find_module()` method on path entry finders is deprecated,
628as it does not allow the path entry finder to contribute portions to
629namespace packages. Instead path entry finders should implement the
630:meth:`find_loader()` method as described above. If it exists on the path
631entry finder, the import system will always call :meth:`find_loader()`
632in preference to :meth:`find_module()`.
633
634
635Replacing the standard import system
636====================================
637
638The most reliable mechanism for replacing the entire import system is to
639delete the default contents of :data:`sys.meta_path`, replacing them
640entirely with a custom meta path hook.
641
642If it is acceptable to only alter the behaviour of import statements
643without affecting other APIs that access the import system, then replacing
644the builtin :func:`__import__` function may be sufficient. This technique
645may also be employed at the module level to only alter the behaviour of
646import statements within that module.
647
648To selectively prevent import of some modules from a hook early on the
649meta path (rather than disabling the standard import system entirely),
Brett Cannon82da8882013-07-04 17:48:16 -0400650it is sufficient to raise :exc:`ImportError` directly from
Nick Coghlan49417742012-08-02 23:03:58 +1000651:meth:`find_module` instead of returning ``None``. The latter indicates
652that the meta path search should continue. while raising an exception
653terminates it immediately.
Barry Warsawd7d21942012-07-29 16:36:17 -0400654
655
656Open issues
657===========
658
Barry Warsawd7d21942012-07-29 16:36:17 -0400659XXX It would be really nice to have a diagram.
660
Barry Warsawc1e721b2012-07-30 16:24:12 -0400661XXX * (import_machinery.rst) how about a section devoted just to the
662attributes of modules and packages, perhaps expanding upon or supplanting the
663related entries in the data model reference page?
664
Barry Warsawdadebab2012-07-31 16:03:09 -0400665XXX runpy, pkgutil, et al in the library manual should all get "See Also"
666links at the top pointing to the new import system section.
667
Barry Warsawd7d21942012-07-29 16:36:17 -0400668
669References
670==========
671
672The import machinery has evolved considerably since Python's early days. The
673original `specification for packages
674<http://www.python.org/doc/essays/packages.html>`_ is still available to read,
675although some details have changed since the writing of that document.
676
677The original specification for :data:`sys.meta_path` was :pep:`302`, with
Barry Warsawdadebab2012-07-31 16:03:09 -0400678subsequent extension in :pep:`420`.
679
680:pep:`420` introduced :term:`namespace packages <namespace package>` for
681Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as an
682alternative to :meth:`find_module`.
Barry Warsawd7d21942012-07-29 16:36:17 -0400683
684:pep:`366` describes the addition of the ``__package__`` attribute for
685explicit relative imports in main modules.
Barry Warsawc1e721b2012-07-30 16:24:12 -0400686
Nick Coghlan1685db02012-08-20 13:49:08 +1000687:pep:`328` introduced absolute and explicit relative imports and initially
688proposed ``__name__`` for semantics :pep:`366` would eventually specify for
Barry Warsawdadebab2012-07-31 16:03:09 -0400689``__package__``.
690
691:pep:`338` defines executing modules as scripts.
692
Barry Warsawc1e721b2012-07-30 16:24:12 -0400693
Georg Brandl44ea77b2013-03-28 13:28:44 +0100694.. rubric:: Footnotes
Barry Warsawc1e721b2012-07-30 16:24:12 -0400695
696.. [#fnmo] See :class:`types.ModuleType`.
697
Nick Coghlan1685db02012-08-20 13:49:08 +1000698.. [#fnlo] The importlib implementation avoids using the return value
Barry Warsawc1e721b2012-07-30 16:24:12 -0400699 directly. Instead, it gets the module object by looking the module name up
Nick Coghlan1685db02012-08-20 13:49:08 +1000700 in :data:`sys.modules`. The indirect effect of this is that an imported
Barry Warsawc1e721b2012-07-30 16:24:12 -0400701 module may replace itself in :data:`sys.modules`. This is
702 implementation-specific behavior that is not guaranteed to work in other
703 Python implementations.
704
Barry Warsawc1e721b2012-07-30 16:24:12 -0400705.. [#fnpic] In legacy code, it is possible to find instances of
706 :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It
Nick Coghlan1685db02012-08-20 13:49:08 +1000707 is recommended that code be changed to use ``None`` instead. See
Barry Warsawc1e721b2012-07-30 16:24:12 -0400708 :ref:`portingpythoncode` for more details.