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 |
| 40 | cannot be found, an :exc:`ImportError` is raised. Python implements various |
| 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``. |
| 171 | If any of the intermediate imports fail, an :exc:`ImportError` is raised. |
| 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 |
| 190 | :exc:`ImportError` is raised. If the module name is missing, Python will |
| 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 |
| 198 | of the module to result in an :exc:`ImportError`. |
| 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 |
| 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 |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 233 | return a :term:`loader`, which the import machinery then invokes to load the |
| 234 | module and create the corresponding module object. |
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 | |
| 240 | |
| 241 | Import hooks |
| 242 | ------------ |
| 243 | |
| 244 | .. index:: |
| 245 | single: import hooks |
| 246 | single: meta hooks |
| 247 | single: path hooks |
| 248 | pair: hooks; import |
| 249 | pair: hooks; meta |
| 250 | pair: hooks; path |
| 251 | |
| 252 | The import machinery is designed to be extensible; the primary mechanism for |
| 253 | 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] | 254 | hooks* and *import path hooks*. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 255 | |
| 256 | 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] | 257 | import processing has occurred, other than :data:`sys.modules` cache look up. |
| 258 | This allows meta hooks to override :data:`sys.path` processing, frozen |
| 259 | modules, or even built-in modules. Meta hooks are registered by adding new |
| 260 | finder objects to :data:`sys.meta_path`, as described below. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 261 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 262 | Import path hooks are called as part of :data:`sys.path` (or |
| 263 | ``package.__path__``) processing, at the point where their associated path |
| 264 | item is encountered. Import path hooks are registered by adding new callables |
| 265 | to :data:`sys.path_hooks` as described below. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 266 | |
| 267 | |
| 268 | The meta path |
| 269 | ------------- |
| 270 | |
| 271 | .. index:: |
| 272 | single: sys.meta_path |
| 273 | pair: finder; find_module |
| 274 | pair: finder; find_loader |
| 275 | |
| 276 | When the named module is not found in :data:`sys.modules`, Python next |
| 277 | searches :data:`sys.meta_path`, which contains a list of meta path finder |
| 278 | objects. These finders are queried in order to see if they know how to handle |
| 279 | the named module. Meta path finders must implement a method called |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 280 | :meth:`find_module()` which takes two arguments, a name and an import path. |
| 281 | The meta path finder can use any strategy it wants to determine whether it can |
| 282 | handle the named module or not. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 283 | |
| 284 | If the meta path finder knows how to handle the named module, it returns a |
| 285 | loader object. If it cannot handle the named module, it returns ``None``. If |
| 286 | :data:`sys.meta_path` processing reaches the end of its list without returning |
| 287 | a loader, then an :exc:`ImportError` is raised. Any other exceptions raised |
| 288 | are simply propagated up, aborting the import process. |
| 289 | |
| 290 | The :meth:`find_module()` method of meta path finders is called with two |
| 291 | arguments. The first is the fully qualified name of the module being |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 292 | imported, for example ``foo.bar.baz``. The second argument is the path |
| 293 | entries to use for the module search. For top-level modules, the second |
| 294 | argument is ``None``, but for submodules or subpackages, the second |
| 295 | argument is the value of the parent package's ``__path__`` attribute. If |
| 296 | the appropriate ``__path__`` attribute cannot be accessed, an |
| 297 | :exc:`ImportError` is raised. |
| 298 | |
| 299 | The meta path may be traversed multiple times for a single import request. |
| 300 | For example, assuming none of the modules involved has already been cached, |
| 301 | importing ``foo.bar.baz`` will first perform a top level import, calling |
| 302 | ``mpf.find_module("foo", None)`` on each meta path finder (``mpf``). After |
| 303 | ``foo`` has been imported, ``foo.bar`` will be imported by traversing the |
| 304 | meta path a second time, calling |
| 305 | ``mpf.find_module("foo.bar", foo.__path__)``. Once ``foo.bar`` has been |
| 306 | imported, the final traversal will call |
| 307 | ``mpf.find_module("foo.bar.baz", foo.bar.__path__)``. |
| 308 | |
| 309 | Some meta path finders only support top level imports. These importers will |
| 310 | always return ``None`` when anything other than ``None`` is passed as the |
| 311 | second argument. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 312 | |
| 313 | Python's default :data:`sys.meta_path` has three meta path finders, one that |
| 314 | 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] | 315 | 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] | 316 | (i.e. the :term:`path based finder`). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 317 | |
| 318 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 319 | Loaders |
| 320 | ======= |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 321 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 322 | If and when a module loader is found its |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 323 | :meth:`~importlib.abc.Loader.load_module` method is called, with a single |
| 324 | argument, the fully qualified name of the module being imported. This method |
| 325 | has several responsibilities, and should return the module object it has |
| 326 | loaded [#fnlo]_. If it cannot load the module, it should raise an |
| 327 | :exc:`ImportError`, although any other exception raised during |
| 328 | :meth:`load_module()` will be propagated. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 329 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 330 | In many cases, the finder and loader can be the same object; in such cases the |
| 331 | :meth:`finder.find_module()` would just return ``self``. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 332 | |
| 333 | Loaders must satisfy the following requirements: |
| 334 | |
| 335 | * If there is an existing module object with the given name in |
| 336 | :data:`sys.modules`, the loader must use that existing module. (Otherwise, |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 337 | :func:`imp.reload` will not work correctly.) If the named module does |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 338 | not exist in :data:`sys.modules`, the loader must create a new module |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 339 | object and add it to :data:`sys.modules`. |
| 340 | |
| 341 | Note that the module *must* exist in :data:`sys.modules` before the loader |
| 342 | executes the module code. This is crucial because the module code may |
| 343 | (directly or indirectly) import itself; adding it to :data:`sys.modules` |
| 344 | beforehand prevents unbounded recursion in the worst case and multiple |
| 345 | loading in the best. |
| 346 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 347 | If loading fails, the loader must remove any modules it has inserted into |
| 348 | :data:`sys.modules`, but it must remove **only** the failing module, and |
| 349 | only if the loader itself has loaded it explicitly. Any module already in |
| 350 | the :data:`sys.modules` cache, and any module that was successfully loaded |
| 351 | as a side-effect, must remain in the cache. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 352 | |
| 353 | * The loader may set the ``__file__`` attribute of the module. If set, this |
| 354 | attribute's value must be a string. The loader may opt to leave |
| 355 | ``__file__`` unset if it has no semantic meaning (e.g. a module loaded from |
Brett Cannon | 4b4e38e | 2013-05-25 11:32:50 -0400 | [diff] [blame] | 356 | a database). If ``__file__`` is set, it may also be appropriate to set the |
| 357 | ``__cached__`` attribute which is the path to any compiled version of the |
| 358 | code (e.g. byte-compiled file). The file does not need to exist to set this |
| 359 | attribute; the path can simply point to whether the compiled file would |
| 360 | exist (see :pep:`3147`). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 361 | |
| 362 | * The loader may set the ``__name__`` attribute of the module. While not |
| 363 | required, setting this attribute is highly recommended so that the |
| 364 | :meth:`repr()` of the module is more informative. |
| 365 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 366 | * If the module is a package (either regular or namespace), the loader must |
| 367 | set the module object's ``__path__`` attribute. The value must be |
| 368 | iterable, but may be empty if ``__path__`` has no further significance |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 369 | to the loader. If ``__path__`` is not empty, it must produce strings |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 370 | when iterated over. More details on the semantics of ``__path__`` are |
Georg Brandl | a81b481 | 2012-08-11 08:43:59 +0200 | [diff] [blame] | 371 | given :ref:`below <package-path-rules>`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 372 | |
| 373 | * The ``__loader__`` attribute must be set to the loader object that loaded |
| 374 | the module. This is mostly for introspection and reloading, but can be |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 375 | used for additional loader-specific functionality, for example getting |
| 376 | data associated with a loader. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 377 | |
| 378 | * The module's ``__package__`` attribute should be set. Its value must be a |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 379 | string, but it can be the same value as its ``__name__``. If the attribute |
| 380 | is set to ``None`` or is missing, the import system will fill it in with a |
| 381 | more appropriate value. When the module is a package, its ``__package__`` |
| 382 | value should be set to its ``__name__``. When the module is not a package, |
| 383 | ``__package__`` should be set to the empty string for top-level modules, or |
| 384 | for submodules, to the parent package's name. See :pep:`366` for further |
| 385 | details. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 386 | |
| 387 | This attribute is used instead of ``__name__`` to calculate explicit |
| 388 | relative imports for main modules, as defined in :pep:`366`. |
| 389 | |
| 390 | * 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] | 391 | dynamically loaded extension), the loader should execute the module's code |
| 392 | in the module's global name space (``module.__dict__``). |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 393 | |
| 394 | |
| 395 | Module reprs |
| 396 | ------------ |
| 397 | |
| 398 | By default, all modules have a usable repr, however depending on the |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 399 | attributes set above, and hooks in the loader, you can more explicitly control |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 400 | the repr of module objects. |
| 401 | |
| 402 | Loaders may implement a :meth:`module_repr()` method which takes a single |
| 403 | argument, the module object. When ``repr(module)`` is called for a module |
| 404 | with a loader supporting this protocol, whatever is returned from |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 405 | ``module.__loader__.module_repr(module)`` is returned as the module's repr |
| 406 | without further processing. This return value must be a string. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 407 | |
| 408 | If the module has no ``__loader__`` attribute, or the loader has no |
| 409 | :meth:`module_repr()` method, then the module object implementation itself |
| 410 | will craft a default repr using whatever information is available. It will |
| 411 | try to use the ``module.__name__``, ``module.__file__``, and |
| 412 | ``module.__loader__`` as input into the repr, with defaults for whatever |
| 413 | information is missing. |
| 414 | |
| 415 | Here are the exact rules used: |
| 416 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 417 | * If the module has a ``__loader__`` and that loader has a |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 418 | :meth:`module_repr()` method, call it with a single argument, which is the |
| 419 | module object. The value returned is used as the module's repr. |
| 420 | |
| 421 | * If an exception occurs in :meth:`module_repr()`, the exception is caught |
| 422 | and discarded, and the calculation of the module's repr continues as if |
| 423 | :meth:`module_repr()` did not exist. |
| 424 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 425 | * If the module has a ``__file__`` attribute, this is used as part of the |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 426 | module's repr. |
| 427 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 428 | * If the module has no ``__file__`` but does have a ``__loader__``, then the |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 429 | loader's repr is used as part of the module's repr. |
| 430 | |
| 431 | * Otherwise, just use the module's ``__name__`` in the repr. |
| 432 | |
| 433 | This example, from :pep:`420` shows how a loader can craft its own module |
| 434 | repr:: |
| 435 | |
| 436 | class NamespaceLoader: |
| 437 | @classmethod |
| 438 | def module_repr(cls, module): |
| 439 | return "<module '{}' (namespace)>".format(module.__name__) |
| 440 | |
| 441 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 442 | .. _package-path-rules: |
| 443 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 444 | module.__path__ |
| 445 | --------------- |
| 446 | |
| 447 | By definition, if a module has an ``__path__`` attribute, it is a package, |
| 448 | regardless of its value. |
| 449 | |
| 450 | A package's ``__path__`` attribute is used during imports of its subpackages. |
| 451 | Within the import machinery, it functions much the same as :data:`sys.path`, |
| 452 | i.e. providing a list of locations to search for modules during import. |
| 453 | However, ``__path__`` is typically much more constrained than |
| 454 | :data:`sys.path`. |
| 455 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 456 | ``__path__`` must be an iterable of strings, but it may be empty. |
| 457 | The same rules used for :data:`sys.path` also apply to a package's |
| 458 | ``__path__``, and :data:`sys.path_hooks` (described below) are |
| 459 | consulted when traversing a package's ``__path__``. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 460 | |
| 461 | A package's ``__init__.py`` file may set or alter the package's ``__path__`` |
| 462 | attribute, and this was typically the way namespace packages were implemented |
| 463 | prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no |
| 464 | longer need to supply ``__init__.py`` files containing only ``__path__`` |
| 465 | manipulation code; the namespace loader automatically sets ``__path__`` |
| 466 | correctly for the namespace package. |
| 467 | |
| 468 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 469 | The Path Based Finder |
| 470 | ===================== |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 471 | |
| 472 | .. index:: |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 473 | single: path based finder |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 474 | |
| 475 | As mentioned previously, Python comes with several default meta path finders. |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 476 | 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] | 477 | path`, which contains a list of :term:`path entries <path entry>`. Each path |
| 478 | entry names a location to search for modules. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 479 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 480 | 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] | 481 | traverses the individual path entries, associating each of them with a |
| 482 | path entry finder that knows how to handle that particular kind of path. |
| 483 | |
| 484 | The default set of path entry finders implement all the semantics for finding |
| 485 | modules on the file system, handling special file types such as Python source |
| 486 | code (``.py`` files), Python byte code (``.pyc`` and ``.pyo`` files) and |
| 487 | shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport` |
| 488 | module in the standard library, the default path entry finders also handle |
| 489 | loading all of these file types (other than shared libraries) from zipfiles. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 490 | |
| 491 | 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] | 492 | 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] | 493 | string. |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 494 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 495 | The path based finder provides additional hooks and protocols so that you |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 496 | can extend and customize the types of searchable path entries. For example, |
| 497 | if you wanted to support path entries as network URLs, you could write a hook |
| 498 | that implements HTTP semantics to find modules on the web. This hook (a |
| 499 | callable) would return a :term:`path entry finder` supporting the protocol |
| 500 | described below, which was then used to get a loader for the module from the |
| 501 | web. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 502 | |
| 503 | A word of warning: this section and the previous both use the term *finder*, |
| 504 | distinguishing between them by using the terms :term:`meta path finder` and |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 505 | :term:`path entry finder`. These two types of finders are very similar, |
| 506 | support similar protocols, and function in similar ways during the import |
| 507 | process, but it's important to keep in mind that they are subtly different. |
| 508 | In particular, meta path finders operate at the beginning of the import |
| 509 | process, as keyed off the :data:`sys.meta_path` traversal. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 510 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 511 | By contrast, path entry finders are in a sense an implementation detail |
| 512 | 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] | 513 | removed from :data:`sys.meta_path`, none of the path entry finder semantics |
| 514 | would be invoked. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 515 | |
| 516 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 517 | Path entry finders |
| 518 | ------------------ |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 519 | |
| 520 | .. index:: |
| 521 | single: sys.path |
| 522 | single: sys.path_hooks |
| 523 | single: sys.path_importer_cache |
| 524 | single: PYTHONPATH |
| 525 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 526 | The :term:`path based finder` is responsible for finding and loading Python |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 527 | modules and packages whose location is specified with a string :term:`path |
| 528 | entry`. Most path entries name locations in the file system, but they need |
| 529 | not be limited to this. |
| 530 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 531 | As a meta path finder, the :term:`path based finder` implements the |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 532 | :meth:`find_module()` protocol previously described, however it exposes |
| 533 | 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] | 534 | loaded from the :term:`import path`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 535 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 536 | 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] | 537 | :data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__`` |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 538 | attributes on package objects are also used. These provide additional ways |
| 539 | that the import machinery can be customized. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 540 | |
| 541 | :data:`sys.path` contains a list of strings providing search locations for |
| 542 | modules and packages. It is initialized from the :data:`PYTHONPATH` |
| 543 | environment variable and various other installation- and |
| 544 | implementation-specific defaults. Entries in :data:`sys.path` can name |
| 545 | directories on the file system, zip files, and potentially other "locations" |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 546 | (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] | 547 | URLs, or database queries. Only strings and bytes should be present on |
| 548 | :data:`sys.path`; all other data types are ignored. The encoding of bytes |
| 549 | entries is determined by the individual :term:`path entry finders <path entry |
| 550 | finder>`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 551 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 552 | 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] | 553 | machinery begins the :term:`import path` search by calling the path |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 554 | based finder's :meth:`find_module()` method as described previously. When |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 555 | the ``path`` argument to :meth:`find_module()` is given, it will be a |
| 556 | list of string paths to traverse - typically a package's ``__path__`` |
| 557 | attribute for an import within that package. If the ``path`` argument |
| 558 | 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] | 559 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 560 | 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] | 561 | for each of these, looks for an appropriate :term:`path entry finder` for the |
| 562 | 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] | 563 | `stat()` call overheads for this search), the path based finder maintains |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 564 | 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] | 565 | in :data:`sys.path_importer_cache` (despite the name, this cache actually |
| 566 | stores finder objects rather than being limited to :term:`importer` objects). |
| 567 | In this way, the expensive search for a particular :term:`path entry` |
| 568 | location's :term:`path entry finder` need only be done once. User code is |
| 569 | free to remove cache entries from :data:`sys.path_importer_cache` forcing |
| 570 | the path based finder to perform the path entry search again [#fnpic]_. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 571 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 572 | 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] | 573 | over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry |
| 574 | hooks <path entry hook>` in this list is called with a single argument, the |
| 575 | path entry to be searched. This callable may either return a :term:`path |
| 576 | entry finder` that can handle the path entry, or it may raise |
| 577 | :exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to |
| 578 | signal that the hook cannot find a :term:`path entry finder` for that |
| 579 | :term:`path entry`. The exception is ignored and :term:`import path` |
| 580 | iteration continues. The hook should expect either a string or bytes object; |
| 581 | the encoding of bytes objects is up to the hook (e.g. it may be a file system |
| 582 | encoding, UTF-8, or something else), and if the hook cannot decode the |
| 583 | argument, it should raise :exc:`ImportError`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 584 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 585 | If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder` |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 586 | being returned, then the path based finder's :meth:`find_module()` method |
| 587 | will store ``None`` in :data:`sys.path_importer_cache` (to indicate that |
| 588 | 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] | 589 | this :term:`meta path finder` could not find the module. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 590 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 591 | If a :term:`path entry finder` *is* returned by one of the :term:`path entry |
| 592 | hook` callables on :data:`sys.path_hooks`, then the following protocol is used |
| 593 | to ask the finder for a module loader, which is then used to load the module. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 594 | |
| 595 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 596 | Path entry finder protocol |
| 597 | -------------------------- |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 598 | |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 599 | In order to support imports of modules and initialized packages and also to |
| 600 | contribute portions to namespace packages, path entry finders must implement |
| 601 | the :meth:`find_loader()` method. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 602 | |
| 603 | :meth:`find_loader()` takes one argument, the fully qualified name of the |
| 604 | module being imported. :meth:`find_loader()` returns a 2-tuple where the |
| 605 | first item is the loader and the second item is a namespace :term:`portion`. |
| 606 | When the first item (i.e. the loader) is ``None``, this means that while the |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 607 | path entry finder does not have a loader for the named module, it knows that the |
| 608 | path entry contributes to a namespace portion for the named module. This will |
| 609 | almost always be the case where Python is asked to import a namespace package |
| 610 | that has no physical presence on the file system. When a path entry finder |
| 611 | returns ``None`` for the loader, the second item of the 2-tuple return value |
| 612 | must be a sequence, although it can be empty. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 613 | |
| 614 | If :meth:`find_loader()` returns a non-``None`` loader value, the portion is |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 615 | ignored and the loader is returned from the path based finder, terminating |
| 616 | the search through the path entries. |
Nick Coghlan | 4941774 | 2012-08-02 23:03:58 +1000 | [diff] [blame] | 617 | |
| 618 | For backwards compatibility with other implementations of the import |
| 619 | protocol, many path entry finders also support the same, |
| 620 | traditional :meth:`find_module()` method that meta path finders support. |
| 621 | However path entry finder :meth:`find_module()` methods are never called |
| 622 | with a ``path`` argument (they are expected to record the appropriate |
| 623 | path information from the initial call to the path hook). |
| 624 | |
| 625 | The :meth:`find_module()` method on path entry finders is deprecated, |
| 626 | as it does not allow the path entry finder to contribute portions to |
| 627 | namespace packages. Instead path entry finders should implement the |
| 628 | :meth:`find_loader()` method as described above. If it exists on the path |
| 629 | entry finder, the import system will always call :meth:`find_loader()` |
| 630 | in preference to :meth:`find_module()`. |
| 631 | |
| 632 | |
| 633 | Replacing the standard import system |
| 634 | ==================================== |
| 635 | |
| 636 | The most reliable mechanism for replacing the entire import system is to |
| 637 | delete the default contents of :data:`sys.meta_path`, replacing them |
| 638 | entirely with a custom meta path hook. |
| 639 | |
| 640 | If it is acceptable to only alter the behaviour of import statements |
| 641 | without affecting other APIs that access the import system, then replacing |
| 642 | the builtin :func:`__import__` function may be sufficient. This technique |
| 643 | may also be employed at the module level to only alter the behaviour of |
| 644 | import statements within that module. |
| 645 | |
| 646 | To selectively prevent import of some modules from a hook early on the |
| 647 | meta path (rather than disabling the standard import system entirely), |
| 648 | it is sufficient to raise :exc:`ImportError` directly from |
| 649 | :meth:`find_module` instead of returning ``None``. The latter indicates |
| 650 | that the meta path search should continue. while raising an exception |
| 651 | terminates it immediately. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 652 | |
| 653 | |
| 654 | Open issues |
| 655 | =========== |
| 656 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 657 | XXX It would be really nice to have a diagram. |
| 658 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 659 | XXX * (import_machinery.rst) how about a section devoted just to the |
| 660 | attributes of modules and packages, perhaps expanding upon or supplanting the |
| 661 | related entries in the data model reference page? |
| 662 | |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 663 | XXX runpy, pkgutil, et al in the library manual should all get "See Also" |
| 664 | links at the top pointing to the new import system section. |
| 665 | |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 666 | |
| 667 | References |
| 668 | ========== |
| 669 | |
| 670 | The import machinery has evolved considerably since Python's early days. The |
| 671 | original `specification for packages |
| 672 | <http://www.python.org/doc/essays/packages.html>`_ is still available to read, |
| 673 | although some details have changed since the writing of that document. |
| 674 | |
| 675 | The original specification for :data:`sys.meta_path` was :pep:`302`, with |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 676 | subsequent extension in :pep:`420`. |
| 677 | |
| 678 | :pep:`420` introduced :term:`namespace packages <namespace package>` for |
| 679 | Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as an |
| 680 | alternative to :meth:`find_module`. |
Barry Warsaw | d7d2194 | 2012-07-29 16:36:17 -0400 | [diff] [blame] | 681 | |
| 682 | :pep:`366` describes the addition of the ``__package__`` attribute for |
| 683 | explicit relative imports in main modules. |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 684 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 685 | :pep:`328` introduced absolute and explicit relative imports and initially |
| 686 | proposed ``__name__`` for semantics :pep:`366` would eventually specify for |
Barry Warsaw | dadebab | 2012-07-31 16:03:09 -0400 | [diff] [blame] | 687 | ``__package__``. |
| 688 | |
| 689 | :pep:`338` defines executing modules as scripts. |
| 690 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 691 | |
Georg Brandl | 44ea77b | 2013-03-28 13:28:44 +0100 | [diff] [blame] | 692 | .. rubric:: Footnotes |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 693 | |
| 694 | .. [#fnmo] See :class:`types.ModuleType`. |
| 695 | |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 696 | .. [#fnlo] The importlib implementation avoids using the return value |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 697 | 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] | 698 | 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] | 699 | module may replace itself in :data:`sys.modules`. This is |
| 700 | implementation-specific behavior that is not guaranteed to work in other |
| 701 | Python implementations. |
| 702 | |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 703 | .. [#fnpic] In legacy code, it is possible to find instances of |
| 704 | :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It |
Nick Coghlan | 1685db0 | 2012-08-20 13:49:08 +1000 | [diff] [blame] | 705 | is recommended that code be changed to use ``None`` instead. See |
Barry Warsaw | c1e721b | 2012-07-30 16:24:12 -0400 | [diff] [blame] | 706 | :ref:`portingpythoncode` for more details. |