Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 1 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 2 | .. _importsystem: |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 3 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 4 | ***************** |
| 5 | The import system |
| 6 | ***************** |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 7 | |
| 8 | .. index:: single: import machinery |
| 9 | |
| 10 | Python code in one :term:`module` gains access to the code in another module |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 11 | by the process of :term:`importing` it. The :keyword:`import` statement is |
| 12 | the most common way of invoking the import machinery, but it is not the only |
| 13 | way. Functions such as :func:`importlib.import_module` and built-in |
| 14 | :func:`__import__` can also be used to invoke the import machinery. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 15 | |
| 16 | The :keyword:`import` statement combines two operations; it searches for the |
| 17 | named module, then it binds the results of that search to a name in the local |
| 18 | scope. The search operation of the :keyword:`import` statement is defined as |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 19 | a call to the :func:`__import__` function, with the appropriate arguments. |
| 20 | The return value of :func:`__import__` is used to perform the name |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 21 | binding operation of the :keyword:`import` statement. See the |
| 22 | :keyword:`import` statement for the exact details of that name binding |
| 23 | operation. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 24 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 25 | A direct call to :func:`__import__` performs only the module search and, if |
| 26 | found, the module creation operation. While certain side-effects may occur, |
| 27 | such as the importing of parent packages, and the updating of various caches |
| 28 | (including :data:`sys.modules`), only the :keyword:`import` statement performs |
| 29 | a name binding operation. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 30 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 31 | When calling :func:`__import__` as part of an import statement, the |
| 32 | import system first checks the module global namespace for a function by |
| 33 | that name. If it is not found, then the standard builtin :func:`__import__` |
| 34 | is called. Other mechanisms for invoking the import system (such as |
| 35 | :func:`importlib.import_module`) do not perform this check and will always |
| 36 | use the standard import system. |
| 37 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 38 | When a module is first imported, Python searches for the module and if found, |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 39 | it creates a module object [#fnmo]_, initializing it. If the named module |
Brett Cannon | 82da888 | 2013-07-04 17:48:16 -0400 | [diff] [blame] | 40 | cannot be found, an :exc:`ImportError` is raised. Python implements various |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 41 | strategies to search for the named module when the import machinery is |
| 42 | invoked. These strategies can be modified and extended by using various hooks |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 43 | described in the sections below. |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 44 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 45 | .. versionchanged:: 3.3 |
| 46 | The import system has been updated to fully implement the second phase |
Andrew Svetlov | e2cf03e | 2012-11-15 16:28:21 +0200 | [diff] [blame] | 47 | of :pep:`302`. There is no longer any implicit import machinery - the full |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 48 | import system is exposed through :data:`sys.meta_path`. In addition, |
Andrew Svetlov | e2cf03e | 2012-11-15 16:28:21 +0200 | [diff] [blame] | 49 | native namespace package support has been implemented (see :pep:`420`). |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 50 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 51 | |
| 52 | :mod:`importlib` |
| 53 | ================ |
| 54 | |
| 55 | The :mod:`importlib` module provides a rich API for interacting with the |
| 56 | import system. For example :func:`importlib.import_module` provides a |
| 57 | recommended, simpler API than built-in :func:`__import__` for invoking the |
| 58 | import machinery. Refer to the :mod:`importlib` library documentation for |
| 59 | additional detail. |
| 60 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 61 | |
| 62 | |
| 63 | Packages |
| 64 | ======== |
| 65 | |
| 66 | .. index:: |
| 67 | single: package |
| 68 | |
| 69 | Python has only one type of module object, and all modules are of this type, |
| 70 | regardless of whether the module is implemented in Python, C, or something |
| 71 | else. To help organize modules and provide a naming hierarchy, Python has a |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 72 | concept of :term:`packages <package>`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 73 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 74 | You can think of packages as the directories on a file system and modules as |
| 75 | files within directories, but don't take this analogy too literally since |
| 76 | packages and modules need not originate from the file system. For the |
| 77 | purposes of this documentation, we'll use this convenient analogy of |
| 78 | directories and files. Like file system directories, packages are organized |
| 79 | hierarchically, and packages may themselves contain subpackages, as well as |
| 80 | regular modules. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 81 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 82 | It's important to keep in mind that all packages are modules, but not all |
| 83 | modules are packages. Or put another way, packages are just a special kind of |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 84 | module. Specifically, any module that contains a ``__path__`` attribute is |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 85 | considered a package. |
| 86 | |
| 87 | All modules have a name. Subpackage names are separated from their parent |
| 88 | package name by dots, akin to Python's standard attribute access syntax. Thus |
| 89 | you might have a module called :mod:`sys` and a package called :mod:`email`, |
| 90 | which in turn has a subpackage called :mod:`email.mime` and a module within |
| 91 | that subpackage called :mod:`email.mime.text`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 92 | |
| 93 | |
| 94 | Regular packages |
| 95 | ---------------- |
| 96 | |
| 97 | .. index:: |
| 98 | pair: package; regular |
| 99 | |
| 100 | Python defines two types of packages, :term:`regular packages <regular |
| 101 | package>` and :term:`namespace packages <namespace package>`. Regular |
| 102 | packages are traditional packages as they existed in Python 3.2 and earlier. |
| 103 | A regular package is typically implemented as a directory containing an |
| 104 | ``__init__.py`` file. When a regular package is imported, this |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 105 | ``__init__.py`` file is implicitly executed, and the objects it defines are |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 106 | bound to names in the package's namespace. The ``__init__.py`` file can |
| 107 | contain the same Python code that any other module can contain, and Python |
| 108 | will add some additional attributes to the module when it is imported. |
| 109 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 110 | For example, the following file system layout defines a top level ``parent`` |
| 111 | package 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 Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 122 | Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 123 | ``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 124 | ``parent.three`` will execute ``parent/two/__init__.py`` and |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 125 | ``parent/three/__init__.py`` respectively. |
| 126 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 127 | |
| 128 | Namespace packages |
| 129 | ------------------ |
| 130 | |
| 131 | .. index:: |
| 132 | pair:: package; namespace |
| 133 | pair:: package; portion |
| 134 | |
| 135 | A namespace package is a composite of various :term:`portions <portion>`, |
| 136 | where each portion contributes a subpackage to the parent package. Portions |
| 137 | may reside in different locations on the file system. Portions may also be |
| 138 | found in zip files, on the network, or anywhere else that Python searches |
| 139 | during import. Namespace packages may or may not correspond directly to |
| 140 | objects on the file system; they may be virtual modules that have no concrete |
| 141 | representation. |
| 142 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 143 | Namespace packages do not use an ordinary list for their ``__path__`` |
| 144 | attribute. They instead use a custom iterable type which will automatically |
| 145 | perform a new search for package portions on the next import attempt within |
| 146 | that package if the path of their parent package (or :data:`sys.path` for a |
| 147 | top level package) changes. |
| 148 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 149 | With namespace packages, there is no ``parent/__init__.py`` file. In fact, |
| 150 | there may be multiple ``parent`` directories found during import search, where |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 151 | each one is provided by a different portion. Thus ``parent/one`` may not be |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 152 | physically located next to ``parent/two``. In this case, Python will create a |
| 153 | namespace package for the top-level ``parent`` package whenever it or one of |
| 154 | its subpackages is imported. |
| 155 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 156 | See also :pep:`420` for the namespace package specification. |
| 157 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 158 | |
| 159 | Searching |
| 160 | ========= |
| 161 | |
| 162 | To begin the search, Python needs the :term:`fully qualified <qualified name>` |
| 163 | name of the module (or package, but for the purposes of this discussion, the |
| 164 | difference is immaterial) being imported. This name may come from various |
| 165 | arguments to the :keyword:`import` statement, or from the parameters to the |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 166 | :func:`importlib.import_module` or :func:`__import__` functions. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 167 | |
| 168 | This name will be used in various phases of the import search, and it may be |
| 169 | the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python |
| 170 | first tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``. |
Brett Cannon | 82da888 | 2013-07-04 17:48:16 -0400 | [diff] [blame] | 171 | If any of the intermediate imports fail, an :exc:`ImportError` is raised. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 172 | |
| 173 | |
| 174 | The module cache |
| 175 | ---------------- |
| 176 | |
| 177 | .. index:: |
| 178 | single: sys.modules |
| 179 | |
| 180 | The first place checked during import search is :data:`sys.modules`. This |
| 181 | mapping serves as a cache of all modules that have been previously imported, |
| 182 | including the intermediate paths. So if ``foo.bar.baz`` was previously |
| 183 | imported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``, |
| 184 | and ``foo.bar.baz``. Each key will have as its value the corresponding module |
| 185 | object. |
| 186 | |
| 187 | During import, the module name is looked up in :data:`sys.modules` and if |
| 188 | present, the associated value is the module satisfying the import, and the |
| 189 | process completes. However, if the value is ``None``, then an |
Brett Cannon | 82da888 | 2013-07-04 17:48:16 -0400 | [diff] [blame] | 190 | :exc:`ImportError` is raised. If the module name is missing, Python will |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 191 | continue searching for the module. |
| 192 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 193 | :data:`sys.modules` is writable. Deleting a key may not destroy the |
| 194 | associated module (as other modules may hold references to it), |
| 195 | but it will invalidate the cache entry for the named module, causing |
| 196 | Python to search anew for the named module upon its next |
| 197 | import. The key can also be assigned to ``None``, forcing the next import |
Brett Cannon | 82da888 | 2013-07-04 17:48:16 -0400 | [diff] [blame] | 198 | of the module to result in an :exc:`ImportError`. |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 199 | |
| 200 | Beware though, as if you keep a reference to the module object, |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 201 | invalidate its cache entry in :data:`sys.modules`, and then re-import the |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 202 | named module, the two module objects will *not* be the same. By contrast, |
| 203 | :func:`imp.reload` will reuse the *same* module object, and simply |
| 204 | reinitialise the module contents by rerunning the module's code. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 205 | |
| 206 | |
| 207 | Finders and loaders |
| 208 | ------------------- |
| 209 | |
| 210 | .. index:: |
| 211 | single: finder |
| 212 | single: loader |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 213 | single: module spec |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 214 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 215 | If the named module is not found in :data:`sys.modules`, then Python's import |
| 216 | protocol is invoked to find and load the module. This protocol consists of |
| 217 | two conceptual objects, :term:`finders <finder>` and :term:`loaders <loader>`. |
| 218 | A finder's job is to determine whether it can find the named module using |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 219 | whatever strategy it knows about. Objects that implement both of these |
| 220 | interfaces are referred to as :term:`importers <importer>` - they return |
| 221 | themselves when they find that they can load the requested module. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 222 | |
Andrew Svetlov | e2cf03e | 2012-11-15 16:28:21 +0200 | [diff] [blame] | 223 | Python includes a number of default finders and importers. The first one |
| 224 | knows how to locate built-in modules, and the second knows how to locate |
| 225 | frozen modules. A third default finder searches an :term:`import path` |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 226 | for modules. The :term:`import path` is a list of locations that may |
| 227 | name file system paths or zip files. It can also be extended to search |
| 228 | for any locatable resource, such as those identified by URLs. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 229 | |
| 230 | The import machinery is extensible, so new finders can be added to extend the |
| 231 | range and scope of module searching. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 232 | |
| 233 | Finders do not actually load modules. If they can find the named module, they |
Georg Brandl | 472a65a | 2013-11-24 12:39:56 +0100 | [diff] [blame] | 234 | return a :dfn:`module spec`, an encapsulation of the module's import-related |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 235 | information, which the import machinery then uses when loading the module. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 236 | |
| 237 | The following sections describe the protocol for finders and loaders in more |
| 238 | detail, including how you can create and register new ones to extend the |
| 239 | import machinery. |
| 240 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 241 | .. 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 Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 245 | |
| 246 | Import 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 | |
| 257 | The import machinery is designed to be extensible; the primary mechanism for |
| 258 | this are the *import hooks*. There are two types of import hooks: *meta |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 259 | hooks* and *import path hooks*. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 260 | |
| 261 | Meta hooks are called at the start of import processing, before any other |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 262 | import processing has occurred, other than :data:`sys.modules` cache look up. |
| 263 | This allows meta hooks to override :data:`sys.path` processing, frozen |
| 264 | modules, or even built-in modules. Meta hooks are registered by adding new |
| 265 | finder objects to :data:`sys.meta_path`, as described below. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 266 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 267 | Import path hooks are called as part of :data:`sys.path` (or |
| 268 | ``package.__path__``) processing, at the point where their associated path |
| 269 | item is encountered. Import path hooks are registered by adding new callables |
| 270 | to :data:`sys.path_hooks` as described below. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 271 | |
| 272 | |
| 273 | The meta path |
| 274 | ------------- |
| 275 | |
| 276 | .. index:: |
| 277 | single: sys.meta_path |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 278 | pair: finder; find_spec |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 279 | |
| 280 | When the named module is not found in :data:`sys.modules`, Python next |
| 281 | searches :data:`sys.meta_path`, which contains a list of meta path finder |
| 282 | objects. These finders are queried in order to see if they know how to handle |
| 283 | the named module. Meta path finders must implement a method called |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 284 | :meth:`find_spec()` which takes two arguments, a name and an import path. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 285 | The meta path finder can use any strategy it wants to determine whether it can |
| 286 | handle the named module or not. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 287 | |
| 288 | If the meta path finder knows how to handle the named module, it returns a |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 289 | spec object. If it cannot handle the named module, it returns ``None``. If |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 290 | :data:`sys.meta_path` processing reaches the end of its list without returning |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 291 | a spec, then an :exc:`ImportError` is raised. Any other exceptions raised |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 292 | are simply propagated up, aborting the import process. |
| 293 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 294 | The :meth:`find_spec()` method of meta path finders is called with two |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 295 | arguments. The first is the fully qualified name of the module being |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 296 | imported, for example ``foo.bar.baz``. The second argument is the path |
| 297 | entries to use for the module search. For top-level modules, the second |
| 298 | argument is ``None``, but for submodules or subpackages, the second |
| 299 | argument is the value of the parent package's ``__path__`` attribute. If |
| 300 | the appropriate ``__path__`` attribute cannot be accessed, an |
| 301 | :exc:`ImportError` is raised. |
| 302 | |
| 303 | The meta path may be traversed multiple times for a single import request. |
| 304 | For example, assuming none of the modules involved has already been cached, |
| 305 | importing ``foo.bar.baz`` will first perform a top level import, calling |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 306 | ``mpf.find_spec("foo", None)`` on each meta path finder (``mpf``). After |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 307 | ``foo`` has been imported, ``foo.bar`` will be imported by traversing the |
| 308 | meta path a second time, calling |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 309 | ``mpf.find_spec("foo.bar", foo.__path__)``. Once ``foo.bar`` has been |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 310 | imported, the final traversal will call |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 311 | ``mpf.find_spec("foo.bar.baz", foo.bar.__path__)``. |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 312 | |
| 313 | Some meta path finders only support top level imports. These importers will |
| 314 | always return ``None`` when anything other than ``None`` is passed as the |
| 315 | second argument. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 316 | |
| 317 | Python's default :data:`sys.meta_path` has three meta path finders, one that |
| 318 | knows how to import built-in modules, one that knows how to import frozen |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 319 | modules, and one that knows how to import modules from an :term:`import path` |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 320 | (i.e. the :term:`path based finder`). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 321 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 322 | .. versionchanged:: 3.4 |
| 323 | The find_spec() method of meta path finders replaced :meth:`find_module()`. |
| 324 | which is now deprecated. While it will continue to work without change, |
| 325 | the import machinery will try it only if the finder does not implement |
| 326 | find_spec(). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 327 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 328 | |
| 329 | Loading |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 330 | ======= |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 331 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 332 | If and when a module spec is found, the import machinery will use it (and |
| 333 | the loader it contains) when loading the module. Here is an approximation |
| 334 | of what happens during the loading portion of import:: |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 335 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 336 | module = None |
| 337 | if spec.loader is not None and hasattr(spec.loader, 'create_module'): |
| 338 | module = spec.loader.create_module(spec) |
| 339 | if module is None: |
| 340 | module = ModuleType(spec.name) |
| 341 | # The import-related module attributes get set here: |
| 342 | _init_module_attrs(spec, module) |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 343 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 344 | if spec.loader is None: |
| 345 | if spec.submodule_search_locations is not None: |
| 346 | # namespace package |
| 347 | sys.modules[spec.name] = module |
| 348 | else: |
| 349 | # unsupported |
| 350 | raise ImportError |
| 351 | elif not hasattr(spec.loader, 'exec_module'): |
| 352 | module = spec.loader.load_module(spec.name) |
| 353 | else: |
| 354 | sys.modules[spec.name] = module |
| 355 | try: |
| 356 | spec.loader.exec_module(module) |
| 357 | except BaseException: |
| 358 | try: |
| 359 | del sys.modules[spec.name] |
| 360 | except KeyError: |
| 361 | pass |
| 362 | raise |
| 363 | module_to_return = sys.modules[spec.name] |
| 364 | |
| 365 | Note the following details: |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 366 | |
| 367 | * If there is an existing module object with the given name in |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 368 | :data:`sys.modules`, import will have already returned it. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 369 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 370 | * The module will exist in :data:`sys.modules` before the loader |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 371 | executes the module code. This is crucial because the module code may |
| 372 | (directly or indirectly) import itself; adding it to :data:`sys.modules` |
| 373 | beforehand prevents unbounded recursion in the worst case and multiple |
| 374 | loading in the best. |
| 375 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 376 | * If loading fails, the failing module -- and only the failing module -- |
| 377 | gets removed from :data:`sys.modules`. Any module already in the |
| 378 | :data:`sys.modules` cache, and any module that was successfully loaded |
| 379 | as a side-effect, must remain in the cache. This contrasts with |
| 380 | reloading where even the failing module is left in :data:`sys.modules`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 381 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 382 | * After the module is created but before execution, the import machinery |
| 383 | sets the import-related module attributes ("init_module_attrs"), as |
Georg Brandl | 472a65a | 2013-11-24 12:39:56 +0100 | [diff] [blame] | 384 | summarized in a :ref:`later section <import-mod-attrs>`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 385 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 386 | * Module execution is the key moment of loading in which the module's |
| 387 | namespace gets populated. Execution is entirely delegated to the |
| 388 | loader, which gets to decide what gets populated and how. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 389 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 390 | * The module created during loading and passed to exec_module() may |
| 391 | not be the one returned at the end of import [#fnlo]_. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 392 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 393 | .. versionchanged:: 3.4 |
| 394 | The import system has taken over the boilerplate responsibilities of |
| 395 | loaders. These were previously performed by the :meth:`load_module()` |
| 396 | method. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 397 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 398 | Loaders |
| 399 | ------- |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 400 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 401 | Module loaders provide the critical function of loading: module execution. |
| 402 | The import machinery calls the :meth:`~importlib.abc.Loader.exec_module()` |
| 403 | method with a single argument, the module object to execute. Any value |
| 404 | returned from exec_module() is ignored. |
| 405 | |
| 406 | Loaders must satisfy the following requirements: |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 407 | |
| 408 | * If the module is a Python module (as opposed to a built-in module or a |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 409 | dynamically loaded extension), the loader should execute the module's code |
| 410 | in the module's global name space (``module.__dict__``). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 411 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 412 | * If loader cannot execute the module, it should raise an |
| 413 | :exc:`ImportError`, although any other exception raised during |
| 414 | :meth:`exec_module()` will be propagated. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 415 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 416 | In many cases, the finder and loader can be the same object; in such cases the |
| 417 | :meth:`finder.find_spec()` would just return a spec with the loader set |
| 418 | to ``self``. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 419 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 420 | Module loaders may opt in to creating the module object during loading |
| 421 | by implementing a :meth:`create_module()` method. It takes one argument, |
| 422 | the module spec, and returns the new module object to use during loading. |
| 423 | create_module() does not need to set any attributes on the module object. |
| 424 | If the loader does not define create_module(), the import machinery will |
| 425 | create the new module itself. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 426 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 427 | .. versionadded:: 3.4 |
| 428 | The create_module() method of loaders. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 429 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 430 | .. versionchanged:: 3.4 |
| 431 | The load_module() method was replaced by exec_module() and the import |
| 432 | machinery assumed all the boilerplate responsibilities of loading. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 433 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 434 | For compatibility with existing loaders, the import machinery will use |
| 435 | the :meth:`~importlib.abc.Loader.load_module()` method of loaders if it |
| 436 | exists and the loader does not also implement exec_module(). However, |
| 437 | load_module() has been deprecated and loaders should implement |
| 438 | exec_module() instead. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 439 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 440 | The load_module() method must implement all the boilerplate loading |
| 441 | functionality described above in addition to executing the module. All |
| 442 | the same constraints apply, with some additional clarification: |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 443 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 444 | * If there is an existing module object with the given name in |
| 445 | :data:`sys.modules`, the loader must use that existing module. |
| 446 | (Otherwise, :func:`imp.reload` will not work correctly.) If the |
| 447 | named module does not exist in :data:`sys.modules`, the loader |
| 448 | must create a new module object and add it to :data:`sys.modules`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 449 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 450 | * The module *must* exist in :data:`sys.modules` before the loader |
| 451 | executes the module code, to prevent unbounded recursion or multiple |
| 452 | loading. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 453 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 454 | * If loading fails, the loader must remove any modules it has inserted |
| 455 | into :data:`sys.modules`, but it must remove **only** the failing |
| 456 | module, and only if the loader itself has loaded it explicitly. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 457 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 458 | Module spec |
| 459 | ----------- |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 460 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 461 | The import machinery uses a variety of information about each module |
| 462 | during import, especially before loading. Most of the information is |
| 463 | common to all modules. The purpose of a module's spec is to encapsulate |
| 464 | this import-related information on a per-module basis. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 465 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 466 | Using a spec during import allows state to be transferred between import |
| 467 | system components, e.g. between the finder that creates the module spec |
| 468 | and the loader that executes it. Most importantly, it allows the |
| 469 | import machinery to perform the boilerplate operations of loading, |
| 470 | whereas without a module spec the loader had that responsibility. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 471 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 472 | See :class:`~importlib.machinery.ModuleSpec` for more specifics on what |
| 473 | information a module's spec may hold. |
| 474 | |
| 475 | .. versionadded:: 3.4 |
| 476 | |
Georg Brandl | 472a65a | 2013-11-24 12:39:56 +0100 | [diff] [blame] | 477 | .. _import-mod-attrs: |
| 478 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 479 | Import-related module attributes |
| 480 | -------------------------------- |
| 481 | |
| 482 | The import machinery fills in these attributes on each module object |
| 483 | during loading, based on the module's spec, before the loader executes |
| 484 | the module. |
| 485 | |
| 486 | .. attribute:: __name__ |
| 487 | |
| 488 | The ``__name__`` attribute must be set to the fully-qualified name of |
| 489 | the module. This name is used to uniquely identify the module in |
| 490 | the import system. |
| 491 | |
| 492 | .. attribute:: __loader__ |
| 493 | |
| 494 | The ``__loader__`` attribute must be set to the loader object that |
| 495 | the import machinery used when loading the module. This is mostly |
| 496 | for introspection, but can be used for additional loader-specific |
| 497 | functionality, for example getting data associated with a loader. |
| 498 | |
| 499 | .. attribute:: __package__ |
| 500 | |
| 501 | The module's ``__package__`` attribute must be set. Its value must |
| 502 | be a string, but it can be the same value as its ``__name__``. When |
| 503 | the module is a package, its ``__package__`` value should be set to |
| 504 | its ``__name__``. When the module is not a package, ``__package__`` |
| 505 | should be set to the empty string for top-level modules, or for |
| 506 | submodules, to the parent package's name. See :pep:`366` for further |
| 507 | details. |
| 508 | |
| 509 | This attribute is used instead of ``__name__`` to calculate explicit |
| 510 | relative imports for main modules, as defined in :pep:`366`. |
| 511 | |
| 512 | .. attribute:: __spec__ |
| 513 | |
| 514 | The ``__spec__`` attribute must be set to the module spec that was |
| 515 | used when importing the module. This is used primarily for |
| 516 | introspection and during reloading. |
| 517 | |
| 518 | .. attribute:: __path__ |
| 519 | |
| 520 | If the module is a package (either regular or namespace), the module |
| 521 | object's ``__path__`` attribute must be set. The value must be |
| 522 | iterable, but may be empty if ``__path__`` has no further significance. |
| 523 | If ``__path__`` is not empty, it must produce strings when iterated |
| 524 | over. More details on the semantics of ``__path__`` are given |
| 525 | :ref:`below <package-path-rules>`. |
| 526 | |
| 527 | Non-package modules should not have a ``__path__`` attribute. |
| 528 | |
| 529 | .. attribute:: __file__ |
| 530 | .. attribute:: __cached__ |
| 531 | |
| 532 | ``__file__`` is optional. If set, this attribute's value must be a |
| 533 | string. The import system may opt to leave ``__file__`` unset if it |
| 534 | has no semantic meaning (e.g. a module loaded from a database). |
| 535 | |
| 536 | If ``__file__`` is set, it may also be appropriate to set the |
| 537 | ``__cached__`` attribute which is the path to any compiled version of |
| 538 | the code (e.g. byte-compiled file). The file does not need to exist |
| 539 | to set this attribute; the path can simply point to where the |
| 540 | compiled file would exist (see :pep:`3147`). |
| 541 | |
| 542 | It is also appropriate to set ``__cached__`` when ``__file__`` is not |
| 543 | set. However, that scenario is quite atypical. Ultimately, the |
| 544 | loader is what makes use of ``__file__`` and/or ``__cached__``. So |
| 545 | if a loader can load from a cached module but otherwise does not load |
| 546 | from a file, that atypical scenario may be appropriate. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 547 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 548 | .. _package-path-rules: |
| 549 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 550 | module.__path__ |
| 551 | --------------- |
| 552 | |
| 553 | By definition, if a module has an ``__path__`` attribute, it is a package, |
| 554 | regardless of its value. |
| 555 | |
| 556 | A package's ``__path__`` attribute is used during imports of its subpackages. |
| 557 | Within the import machinery, it functions much the same as :data:`sys.path`, |
| 558 | i.e. providing a list of locations to search for modules during import. |
| 559 | However, ``__path__`` is typically much more constrained than |
| 560 | :data:`sys.path`. |
| 561 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 562 | ``__path__`` must be an iterable of strings, but it may be empty. |
| 563 | The same rules used for :data:`sys.path` also apply to a package's |
| 564 | ``__path__``, and :data:`sys.path_hooks` (described below) are |
| 565 | consulted when traversing a package's ``__path__``. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 566 | |
| 567 | A package's ``__init__.py`` file may set or alter the package's ``__path__`` |
| 568 | attribute, and this was typically the way namespace packages were implemented |
| 569 | prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no |
| 570 | longer need to supply ``__init__.py`` files containing only ``__path__`` |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 571 | manipulation code; the import machinery automatically sets ``__path__`` |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 572 | correctly for the namespace package. |
| 573 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 574 | Module reprs |
| 575 | ------------ |
| 576 | |
| 577 | By default, all modules have a usable repr, however depending on the |
| 578 | attributes set above, and in the module's spec, you can more explicitly |
| 579 | control the repr of module objects. |
| 580 | |
| 581 | If the module has a spec (``__spec__``), the import machinery will try |
| 582 | to generate a repr from it. If that fails or there is no spec, the import |
| 583 | system will craft a default repr using whatever information is available |
| 584 | on the module. It will try to use the ``module.__name__``, |
| 585 | ``module.__file__``, and ``module.__loader__`` as input into the repr, |
| 586 | with defaults for whatever information is missing. |
| 587 | |
| 588 | Here are the exact rules used: |
| 589 | |
| 590 | * If the module has a ``__spec__`` attribute, the information in the spec |
| 591 | is used to generate the repr. The "name", "loader", "origin", and |
| 592 | "has_location" attributes are consulted. |
| 593 | |
| 594 | * If the module has a ``__file__`` attribute, this is used as part of the |
| 595 | module's repr. |
| 596 | |
| 597 | * If the module has no ``__file__`` but does have a ``__loader__`` that is not |
| 598 | ``None``, then the loader's repr is used as part of the module's repr. |
| 599 | |
| 600 | * Otherwise, just use the module's ``__name__`` in the repr. |
| 601 | |
| 602 | .. versionchanged:: 3.4 |
| 603 | Use of loader.module_repr() has been deprecated and the module spec |
| 604 | is now used by the import machinery to generate a module repr. |
| 605 | |
| 606 | For backward compatibility with Python 3.3, the module repr will be |
| 607 | generated by calling the loader's :meth:`module_repr()` method, if |
| 608 | defined, before trying either approach described above. However, the |
| 609 | method is deprecated. |
| 610 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 611 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 612 | The Path Based Finder |
| 613 | ===================== |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 614 | |
| 615 | .. index:: |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 616 | single: path based finder |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 617 | |
| 618 | As mentioned previously, Python comes with several default meta path finders. |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 619 | One of these, called the :term:`path based finder`, searches an :term:`import |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 620 | path`, which contains a list of :term:`path entries <path entry>`. Each path |
| 621 | entry names a location to search for modules. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 622 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 623 | The path based finder itself doesn't know how to import anything. Instead, it |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 624 | traverses the individual path entries, associating each of them with a |
| 625 | path entry finder that knows how to handle that particular kind of path. |
| 626 | |
| 627 | The default set of path entry finders implement all the semantics for finding |
| 628 | modules on the file system, handling special file types such as Python source |
| 629 | code (``.py`` files), Python byte code (``.pyc`` and ``.pyo`` files) and |
| 630 | shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport` |
| 631 | module in the standard library, the default path entry finders also handle |
| 632 | loading all of these file types (other than shared libraries) from zipfiles. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 633 | |
| 634 | Path entries need not be limited to file system locations. They can refer to |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 635 | URLs, database queries, or any other location that can be specified as a |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 636 | string. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 637 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 638 | The path based finder provides additional hooks and protocols so that you |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 639 | can extend and customize the types of searchable path entries. For example, |
| 640 | if you wanted to support path entries as network URLs, you could write a hook |
| 641 | that implements HTTP semantics to find modules on the web. This hook (a |
| 642 | callable) would return a :term:`path entry finder` supporting the protocol |
| 643 | described below, which was then used to get a loader for the module from the |
| 644 | web. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 645 | |
| 646 | A word of warning: this section and the previous both use the term *finder*, |
| 647 | distinguishing between them by using the terms :term:`meta path finder` and |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 648 | :term:`path entry finder`. These two types of finders are very similar, |
| 649 | support similar protocols, and function in similar ways during the import |
| 650 | process, but it's important to keep in mind that they are subtly different. |
| 651 | In particular, meta path finders operate at the beginning of the import |
| 652 | process, as keyed off the :data:`sys.meta_path` traversal. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 653 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 654 | By contrast, path entry finders are in a sense an implementation detail |
| 655 | of the path based finder, and in fact, if the path based finder were to be |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 656 | removed from :data:`sys.meta_path`, none of the path entry finder semantics |
| 657 | would be invoked. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 658 | |
| 659 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 660 | Path entry finders |
| 661 | ------------------ |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 662 | |
| 663 | .. index:: |
| 664 | single: sys.path |
| 665 | single: sys.path_hooks |
| 666 | single: sys.path_importer_cache |
| 667 | single: PYTHONPATH |
| 668 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 669 | The :term:`path based finder` is responsible for finding and loading Python |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 670 | modules and packages whose location is specified with a string :term:`path |
| 671 | entry`. Most path entries name locations in the file system, but they need |
| 672 | not be limited to this. |
| 673 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 674 | As a meta path finder, the :term:`path based finder` implements the |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 675 | :meth:`find_spec()` protocol previously described, however it exposes |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 676 | additional hooks that can be used to customize how modules are found and |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 677 | loaded from the :term:`import path`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 678 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 679 | Three variables are used by the :term:`path based finder`, :data:`sys.path`, |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 680 | :data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__`` |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 681 | attributes on package objects are also used. These provide additional ways |
| 682 | that the import machinery can be customized. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 683 | |
| 684 | :data:`sys.path` contains a list of strings providing search locations for |
| 685 | modules and packages. It is initialized from the :data:`PYTHONPATH` |
| 686 | environment variable and various other installation- and |
| 687 | implementation-specific defaults. Entries in :data:`sys.path` can name |
| 688 | directories on the file system, zip files, and potentially other "locations" |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 689 | (see the :mod:`site` module) that should be searched for modules, such as |
Barry Warsaw | 82c1c78 | 2012-11-20 15:22:51 -0500 | [diff] [blame] | 690 | URLs, or database queries. Only strings and bytes should be present on |
| 691 | :data:`sys.path`; all other data types are ignored. The encoding of bytes |
| 692 | entries is determined by the individual :term:`path entry finders <path entry |
| 693 | finder>`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 694 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 695 | The :term:`path based finder` is a :term:`meta path finder`, so the import |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 696 | machinery begins the :term:`import path` search by calling the path |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 697 | based finder's :meth:`find_spec()` method as described previously. When |
| 698 | the ``path`` argument to :meth:`find_spec()` is given, it will be a |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 699 | list of string paths to traverse - typically a package's ``__path__`` |
| 700 | attribute for an import within that package. If the ``path`` argument |
| 701 | is ``None``, this indicates a top level import and :data:`sys.path` is used. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 702 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 703 | The path based finder iterates over every entry in the search path, and |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 704 | for each of these, looks for an appropriate :term:`path entry finder` for the |
| 705 | path entry. Because this can be an expensive operation (e.g. there may be |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 706 | `stat()` call overheads for this search), the path based finder maintains |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 707 | a cache mapping path entries to path entry finders. This cache is maintained |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 708 | in :data:`sys.path_importer_cache` (despite the name, this cache actually |
| 709 | stores finder objects rather than being limited to :term:`importer` objects). |
| 710 | In this way, the expensive search for a particular :term:`path entry` |
| 711 | location's :term:`path entry finder` need only be done once. User code is |
| 712 | free to remove cache entries from :data:`sys.path_importer_cache` forcing |
| 713 | the path based finder to perform the path entry search again [#fnpic]_. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 714 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 715 | If the path entry is not present in the cache, the path based finder iterates |
Barry Warsaw | 82c1c78 | 2012-11-20 15:22:51 -0500 | [diff] [blame] | 716 | over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry |
| 717 | hooks <path entry hook>` in this list is called with a single argument, the |
| 718 | path entry to be searched. This callable may either return a :term:`path |
| 719 | entry finder` that can handle the path entry, or it may raise |
| 720 | :exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to |
| 721 | signal that the hook cannot find a :term:`path entry finder` for that |
| 722 | :term:`path entry`. The exception is ignored and :term:`import path` |
| 723 | iteration continues. The hook should expect either a string or bytes object; |
| 724 | the encoding of bytes objects is up to the hook (e.g. it may be a file system |
| 725 | encoding, UTF-8, or something else), and if the hook cannot decode the |
| 726 | argument, it should raise :exc:`ImportError`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 727 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 728 | If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder` |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 729 | being returned, then the path based finder's :meth:`find_spec()` method |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 730 | will store ``None`` in :data:`sys.path_importer_cache` (to indicate that |
| 731 | there is no finder for this path entry) and return ``None``, indicating that |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 732 | this :term:`meta path finder` could not find the module. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 733 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 734 | If a :term:`path entry finder` *is* returned by one of the :term:`path entry |
| 735 | hook` callables on :data:`sys.path_hooks`, then the following protocol is used |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 736 | to ask the finder for a module spec, which is then used when loading the |
| 737 | module. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 738 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 739 | Path entry finder protocol |
| 740 | -------------------------- |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 741 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 742 | In order to support imports of modules and initialized packages and also to |
| 743 | contribute portions to namespace packages, path entry finders must implement |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 744 | the :meth:`find_spec()` method. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 745 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 746 | :meth:`find_spec()` takes one argument, the fully qualified name of the |
| 747 | module being imported. :meth:`find_spec()` returns a fully populated |
| 748 | spec for the module. This spec will always have "loader" set (with one |
| 749 | exception). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 750 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 751 | To indicate to the import machinery that the spec represents a namespace |
| 752 | :term:`portion`. the path entry finder sets "loader" on the spec to |
| 753 | ``None`` and "submodule_search_locations" to a list containing the |
| 754 | portion. |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 755 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 756 | .. versionchanged:: 3.4 |
| 757 | find_spec() replaced find_loader() and find_module(), but of which |
| 758 | are now deprecated, but will be used if find_spec() is not defined. |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 759 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 760 | Older path entry finders may implement one of these two deprecated methods |
| 761 | instead of :meth:`find_spec()`. The methods are still respected for the |
| 762 | sake of backward compatibility. Howevever, if find_spec() is implemented |
| 763 | on the path entry finder, the legacy methods are ignored. |
| 764 | |
| 765 | :meth:`find_loader()` takes one argument, the fully qualified name of the |
| 766 | module being imported. :meth:`find_loader()` returns a 2-tuple where the |
| 767 | first item is the loader and the second item is a namespace :term:`portion`. |
| 768 | When the first item (i.e. the loader) is ``None``, this means that while the |
| 769 | path entry finder does not have a loader for the named module, it knows that |
| 770 | the path entry contributes to a namespace portion for the named module. |
| 771 | This will almost always be the case where Python is asked to import a |
| 772 | namespace package that has no physical presence on the file system. |
| 773 | When a path entry finder returns ``None`` for the loader, the second |
| 774 | item of the 2-tuple return value must be a sequence, although it can be |
| 775 | empty. |
| 776 | |
| 777 | If :meth:`find_loader()` returns a non-``None`` loader value, the portion is |
| 778 | ignored and the loader is returned from the path based finder, terminating |
| 779 | the search through the path entries. |
| 780 | |
| 781 | For backwards compatibility with other implementations of the import |
| 782 | protocol, many path entry finders also support the same, |
| 783 | traditional :meth:`find_module()` method that meta path finders support. |
| 784 | However path entry finder :meth:`find_module()` methods are never called |
| 785 | with a ``path`` argument (they are expected to record the appropriate |
| 786 | path information from the initial call to the path hook). |
| 787 | |
| 788 | The :meth:`find_module()` method on path entry finders is deprecated, |
| 789 | as it does not allow the path entry finder to contribute portions to |
| 790 | namespace packages. If both :meth:`find_loader()` and :meth:`find_module()` |
| 791 | exist on a path entry finder, the import system will always call |
| 792 | :meth:`find_loader()` in preference to :meth:`find_module()`. |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 793 | |
| 794 | |
| 795 | Replacing the standard import system |
| 796 | ==================================== |
| 797 | |
| 798 | The most reliable mechanism for replacing the entire import system is to |
| 799 | delete the default contents of :data:`sys.meta_path`, replacing them |
| 800 | entirely with a custom meta path hook. |
| 801 | |
| 802 | If it is acceptable to only alter the behaviour of import statements |
| 803 | without affecting other APIs that access the import system, then replacing |
| 804 | the builtin :func:`__import__` function may be sufficient. This technique |
| 805 | may also be employed at the module level to only alter the behaviour of |
| 806 | import statements within that module. |
| 807 | |
| 808 | To selectively prevent import of some modules from a hook early on the |
| 809 | meta path (rather than disabling the standard import system entirely), |
Brett Cannon | 82da888 | 2013-07-04 17:48:16 -0400 | [diff] [blame] | 810 | it is sufficient to raise :exc:`ImportError` directly from |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 811 | :meth:`find_spec` instead of returning ``None``. The latter indicates |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 812 | that the meta path search should continue. while raising an exception |
| 813 | terminates it immediately. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 814 | |
| 815 | |
| 816 | Open issues |
| 817 | =========== |
| 818 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 819 | XXX It would be really nice to have a diagram. |
| 820 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 821 | XXX * (import_machinery.rst) how about a section devoted just to the |
| 822 | attributes of modules and packages, perhaps expanding upon or supplanting the |
| 823 | related entries in the data model reference page? |
| 824 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 825 | XXX runpy, pkgutil, et al in the library manual should all get "See Also" |
| 826 | links at the top pointing to the new import system section. |
| 827 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 828 | |
| 829 | References |
| 830 | ========== |
| 831 | |
| 832 | The import machinery has evolved considerably since Python's early days. The |
| 833 | original `specification for packages |
| 834 | <http://www.python.org/doc/essays/packages.html>`_ is still available to read, |
| 835 | although some details have changed since the writing of that document. |
| 836 | |
| 837 | The original specification for :data:`sys.meta_path` was :pep:`302`, with |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 838 | subsequent extension in :pep:`420`. |
| 839 | |
| 840 | :pep:`420` introduced :term:`namespace packages <namespace package>` for |
| 841 | Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as an |
| 842 | alternative to :meth:`find_module`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 843 | |
| 844 | :pep:`366` describes the addition of the ``__package__`` attribute for |
| 845 | explicit relative imports in main modules. |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 846 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 847 | :pep:`328` introduced absolute and explicit relative imports and initially |
| 848 | proposed ``__name__`` for semantics :pep:`366` would eventually specify for |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 849 | ``__package__``. |
| 850 | |
| 851 | :pep:`338` defines executing modules as scripts. |
| 852 | |
Eric Snow | b523f84 | 2013-11-22 09:05:39 -0700 | [diff] [blame] | 853 | :pep:`451` adds the encapsulation of per-module import state in spec |
| 854 | objects. It also off-loads most of the boilerplate responsibilities of |
| 855 | loaders back onto the import machinery. These changes allow the |
| 856 | deprecation of several APIs in the import system and also addition of new |
| 857 | methods to finders and loaders. |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 858 | |
Georg Brandl | 44ea77b | 2013-03-28 13:28:44 +0100 | [diff] [blame] | 859 | .. rubric:: Footnotes |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 860 | |
| 861 | .. [#fnmo] See :class:`types.ModuleType`. |
| 862 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 863 | .. [#fnlo] The importlib implementation avoids using the return value |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 864 | directly. Instead, it gets the module object by looking the module name up |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 865 | in :data:`sys.modules`. The indirect effect of this is that an imported |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 866 | module may replace itself in :data:`sys.modules`. This is |
| 867 | implementation-specific behavior that is not guaranteed to work in other |
| 868 | Python implementations. |
| 869 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 870 | .. [#fnpic] In legacy code, it is possible to find instances of |
| 871 | :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 872 | is recommended that code be changed to use ``None`` instead. See |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 873 | :ref:`portingpythoncode` for more details. |