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