You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

708 lines
32 KiB

  1. .. _importsystem:
  2. *****************
  3. The import system
  4. *****************
  5. .. index:: single: import machinery
  6. Python code in one :term:`module` gains access to the code in another module
  7. by the process of :term:`importing` it. The :keyword:`import` statement is
  8. the most common way of invoking the import machinery, but it is not the only
  9. way. Functions such as :func:`importlib.import_module` and built-in
  10. :func:`__import__` can also be used to invoke the import machinery.
  11. The :keyword:`import` statement combines two operations; it searches for the
  12. named module, then it binds the results of that search to a name in the local
  13. scope. The search operation of the :keyword:`import` statement is defined as
  14. a call to the :func:`__import__` function, with the appropriate arguments.
  15. The return value of :func:`__import__` is used to perform the name
  16. binding operation of the :keyword:`import` statement. See the
  17. :keyword:`import` statement for the exact details of that name binding
  18. operation.
  19. A direct call to :func:`__import__` performs only the module search and, if
  20. found, the module creation operation. While certain side-effects may occur,
  21. such as the importing of parent packages, and the updating of various caches
  22. (including :data:`sys.modules`), only the :keyword:`import` statement performs
  23. a name binding operation.
  24. When calling :func:`__import__` as part of an import statement, the
  25. import system first checks the module global namespace for a function by
  26. that name. If it is not found, then the standard builtin :func:`__import__`
  27. is called. Other mechanisms for invoking the import system (such as
  28. :func:`importlib.import_module`) do not perform this check and will always
  29. use the standard import system.
  30. When a module is first imported, Python searches for the module and if found,
  31. it creates a module object [#fnmo]_, initializing it. If the named module
  32. cannot be found, an :exc:`ImportError` is raised. Python implements various
  33. strategies to search for the named module when the import machinery is
  34. invoked. These strategies can be modified and extended by using various hooks
  35. described in the sections below.
  36. .. versionchanged:: 3.3
  37. The import system has been updated to fully implement the second phase
  38. of :pep:`302`. There is no longer any implicit import machinery - the full
  39. import system is exposed through :data:`sys.meta_path`. In addition,
  40. native namespace package support has been implemented (see :pep:`420`).
  41. :mod:`importlib`
  42. ================
  43. The :mod:`importlib` module provides a rich API for interacting with the
  44. import system. For example :func:`importlib.import_module` provides a
  45. recommended, simpler API than built-in :func:`__import__` for invoking the
  46. import machinery. Refer to the :mod:`importlib` library documentation for
  47. additional detail.
  48. Packages
  49. ========
  50. .. index::
  51. single: package
  52. Python has only one type of module object, and all modules are of this type,
  53. regardless of whether the module is implemented in Python, C, or something
  54. else. To help organize modules and provide a naming hierarchy, Python has a
  55. concept of :term:`packages <package>`.
  56. You can think of packages as the directories on a file system and modules as
  57. files within directories, but don't take this analogy too literally since
  58. packages and modules need not originate from the file system. For the
  59. purposes of this documentation, we'll use this convenient analogy of
  60. directories and files. Like file system directories, packages are organized
  61. hierarchically, and packages may themselves contain subpackages, as well as
  62. regular modules.
  63. It's important to keep in mind that all packages are modules, but not all
  64. modules are packages. Or put another way, packages are just a special kind of
  65. module. Specifically, any module that contains a ``__path__`` attribute is
  66. considered a package.
  67. All modules have a name. Subpackage names are separated from their parent
  68. package name by dots, akin to Python's standard attribute access syntax. Thus
  69. you might have a module called :mod:`sys` and a package called :mod:`email`,
  70. which in turn has a subpackage called :mod:`email.mime` and a module within
  71. that subpackage called :mod:`email.mime.text`.
  72. Regular packages
  73. ----------------
  74. .. index::
  75. pair: package; regular
  76. Python defines two types of packages, :term:`regular packages <regular
  77. package>` and :term:`namespace packages <namespace package>`. Regular
  78. packages are traditional packages as they existed in Python 3.2 and earlier.
  79. A regular package is typically implemented as a directory containing an
  80. ``__init__.py`` file. When a regular package is imported, this
  81. ``__init__.py`` file is implicitly executed, and the objects it defines are
  82. bound to names in the package's namespace. The ``__init__.py`` file can
  83. contain the same Python code that any other module can contain, and Python
  84. will add some additional attributes to the module when it is imported.
  85. For example, the following file system layout defines a top level ``parent``
  86. package with three subpackages::
  87. parent/
  88. __init__.py
  89. one/
  90. __init__.py
  91. two/
  92. __init__.py
  93. three/
  94. __init__.py
  95. Importing ``parent.one`` will implicitly execute ``parent/__init__.py`` and
  96. ``parent/one/__init__.py``. Subsequent imports of ``parent.two`` or
  97. ``parent.three`` will execute ``parent/two/__init__.py`` and
  98. ``parent/three/__init__.py`` respectively.
  99. Namespace packages
  100. ------------------
  101. .. index::
  102. pair:: package; namespace
  103. pair:: package; portion
  104. A namespace package is a composite of various :term:`portions <portion>`,
  105. where each portion contributes a subpackage to the parent package. Portions
  106. may reside in different locations on the file system. Portions may also be
  107. found in zip files, on the network, or anywhere else that Python searches
  108. during import. Namespace packages may or may not correspond directly to
  109. objects on the file system; they may be virtual modules that have no concrete
  110. representation.
  111. Namespace packages do not use an ordinary list for their ``__path__``
  112. attribute. They instead use a custom iterable type which will automatically
  113. perform a new search for package portions on the next import attempt within
  114. that package if the path of their parent package (or :data:`sys.path` for a
  115. top level package) changes.
  116. With namespace packages, there is no ``parent/__init__.py`` file. In fact,
  117. there may be multiple ``parent`` directories found during import search, where
  118. each one is provided by a different portion. Thus ``parent/one`` may not be
  119. physically located next to ``parent/two``. In this case, Python will create a
  120. namespace package for the top-level ``parent`` package whenever it or one of
  121. its subpackages is imported.
  122. See also :pep:`420` for the namespace package specification.
  123. Searching
  124. =========
  125. To begin the search, Python needs the :term:`fully qualified <qualified name>`
  126. name of the module (or package, but for the purposes of this discussion, the
  127. difference is immaterial) being imported. This name may come from various
  128. arguments to the :keyword:`import` statement, or from the parameters to the
  129. :func:`importlib.import_module` or :func:`__import__` functions.
  130. This name will be used in various phases of the import search, and it may be
  131. the dotted path to a submodule, e.g. ``foo.bar.baz``. In this case, Python
  132. first tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``.
  133. If any of the intermediate imports fail, an :exc:`ImportError` is raised.
  134. The module cache
  135. ----------------
  136. .. index::
  137. single: sys.modules
  138. The first place checked during import search is :data:`sys.modules`. This
  139. mapping serves as a cache of all modules that have been previously imported,
  140. including the intermediate paths. So if ``foo.bar.baz`` was previously
  141. imported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``,
  142. and ``foo.bar.baz``. Each key will have as its value the corresponding module
  143. object.
  144. During import, the module name is looked up in :data:`sys.modules` and if
  145. present, the associated value is the module satisfying the import, and the
  146. process completes. However, if the value is ``None``, then an
  147. :exc:`ImportError` is raised. If the module name is missing, Python will
  148. continue searching for the module.
  149. :data:`sys.modules` is writable. Deleting a key may not destroy the
  150. associated module (as other modules may hold references to it),
  151. but it will invalidate the cache entry for the named module, causing
  152. Python to search anew for the named module upon its next
  153. import. The key can also be assigned to ``None``, forcing the next import
  154. of the module to result in an :exc:`ImportError`.
  155. Beware though, as if you keep a reference to the module object,
  156. invalidate its cache entry in :data:`sys.modules`, and then re-import the
  157. named module, the two module objects will *not* be the same. By contrast,
  158. :func:`imp.reload` will reuse the *same* module object, and simply
  159. reinitialise the module contents by rerunning the module's code.
  160. Finders and loaders
  161. -------------------
  162. .. index::
  163. single: finder
  164. single: loader
  165. If the named module is not found in :data:`sys.modules`, then Python's import
  166. protocol is invoked to find and load the module. This protocol consists of
  167. two conceptual objects, :term:`finders <finder>` and :term:`loaders <loader>`.
  168. A finder's job is to determine whether it can find the named module using
  169. whatever strategy it knows about. Objects that implement both of these
  170. interfaces are referred to as :term:`importers <importer>` - they return
  171. themselves when they find that they can load the requested module.
  172. Python includes a number of default finders and importers. The first one
  173. knows how to locate built-in modules, and the second knows how to locate
  174. frozen modules. A third default finder searches an :term:`import path`
  175. for modules. The :term:`import path` is a list of locations that may
  176. name file system paths or zip files. It can also be extended to search
  177. for any locatable resource, such as those identified by URLs.
  178. The import machinery is extensible, so new finders can be added to extend the
  179. range and scope of module searching.
  180. Finders do not actually load modules. If they can find the named module, they
  181. return a :term:`loader`, which the import machinery then invokes to load the
  182. module and create the corresponding module object.
  183. The following sections describe the protocol for finders and loaders in more
  184. detail, including how you can create and register new ones to extend the
  185. import machinery.
  186. Import hooks
  187. ------------
  188. .. index::
  189. single: import hooks
  190. single: meta hooks
  191. single: path hooks
  192. pair: hooks; import
  193. pair: hooks; meta
  194. pair: hooks; path
  195. The import machinery is designed to be extensible; the primary mechanism for
  196. this are the *import hooks*. There are two types of import hooks: *meta
  197. hooks* and *import path hooks*.
  198. Meta hooks are called at the start of import processing, before any other
  199. import processing has occurred, other than :data:`sys.modules` cache look up.
  200. This allows meta hooks to override :data:`sys.path` processing, frozen
  201. modules, or even built-in modules. Meta hooks are registered by adding new
  202. finder objects to :data:`sys.meta_path`, as described below.
  203. Import path hooks are called as part of :data:`sys.path` (or
  204. ``package.__path__``) processing, at the point where their associated path
  205. item is encountered. Import path hooks are registered by adding new callables
  206. to :data:`sys.path_hooks` as described below.
  207. The meta path
  208. -------------
  209. .. index::
  210. single: sys.meta_path
  211. pair: finder; find_module
  212. pair: finder; find_loader
  213. When the named module is not found in :data:`sys.modules`, Python next
  214. searches :data:`sys.meta_path`, which contains a list of meta path finder
  215. objects. These finders are queried in order to see if they know how to handle
  216. the named module. Meta path finders must implement a method called
  217. :meth:`find_module()` which takes two arguments, a name and an import path.
  218. The meta path finder can use any strategy it wants to determine whether it can
  219. handle the named module or not.
  220. If the meta path finder knows how to handle the named module, it returns a
  221. loader object. If it cannot handle the named module, it returns ``None``. If
  222. :data:`sys.meta_path` processing reaches the end of its list without returning
  223. a loader, then an :exc:`ImportError` is raised. Any other exceptions raised
  224. are simply propagated up, aborting the import process.
  225. The :meth:`find_module()` method of meta path finders is called with two
  226. arguments. The first is the fully qualified name of the module being
  227. imported, for example ``foo.bar.baz``. The second argument is the path
  228. entries to use for the module search. For top-level modules, the second
  229. argument is ``None``, but for submodules or subpackages, the second
  230. argument is the value of the parent package's ``__path__`` attribute. If
  231. the appropriate ``__path__`` attribute cannot be accessed, an
  232. :exc:`ImportError` is raised.
  233. The meta path may be traversed multiple times for a single import request.
  234. For example, assuming none of the modules involved has already been cached,
  235. importing ``foo.bar.baz`` will first perform a top level import, calling
  236. ``mpf.find_module("foo", None)`` on each meta path finder (``mpf``). After
  237. ``foo`` has been imported, ``foo.bar`` will be imported by traversing the
  238. meta path a second time, calling
  239. ``mpf.find_module("foo.bar", foo.__path__)``. Once ``foo.bar`` has been
  240. imported, the final traversal will call
  241. ``mpf.find_module("foo.bar.baz", foo.bar.__path__)``.
  242. Some meta path finders only support top level imports. These importers will
  243. always return ``None`` when anything other than ``None`` is passed as the
  244. second argument.
  245. Python's default :data:`sys.meta_path` has three meta path finders, one that
  246. knows how to import built-in modules, one that knows how to import frozen
  247. modules, and one that knows how to import modules from an :term:`import path`
  248. (i.e. the :term:`path based finder`).
  249. Loaders
  250. =======
  251. If and when a module loader is found its
  252. :meth:`~importlib.abc.Loader.load_module` method is called, with a single
  253. argument, the fully qualified name of the module being imported. This method
  254. has several responsibilities, and should return the module object it has
  255. loaded [#fnlo]_. If it cannot load the module, it should raise an
  256. :exc:`ImportError`, although any other exception raised during
  257. :meth:`load_module()` will be propagated.
  258. In many cases, the finder and loader can be the same object; in such cases the
  259. :meth:`finder.find_module()` would just return ``self``.
  260. Loaders must satisfy the following requirements:
  261. * If there is an existing module object with the given name in
  262. :data:`sys.modules`, the loader must use that existing module. (Otherwise,
  263. :func:`imp.reload` will not work correctly.) If the named module does
  264. not exist in :data:`sys.modules`, the loader must create a new module
  265. object and add it to :data:`sys.modules`.
  266. Note that the module *must* exist in :data:`sys.modules` before the loader
  267. executes the module code. This is crucial because the module code may
  268. (directly or indirectly) import itself; adding it to :data:`sys.modules`
  269. beforehand prevents unbounded recursion in the worst case and multiple
  270. loading in the best.
  271. If loading fails, the loader must remove any modules it has inserted into
  272. :data:`sys.modules`, but it must remove **only** the failing module, and
  273. only if the loader itself has loaded it explicitly. Any module already in
  274. the :data:`sys.modules` cache, and any module that was successfully loaded
  275. as a side-effect, must remain in the cache.
  276. * The loader may set the ``__file__`` attribute of the module. If set, this
  277. attribute's value must be a string. The loader may opt to leave
  278. ``__file__`` unset if it has no semantic meaning (e.g. a module loaded from
  279. a database). If ``__file__`` is set, it may also be appropriate to set the
  280. ``__cached__`` attribute which is the path to any compiled version of the
  281. code (e.g. byte-compiled file). The file does not need to exist to set this
  282. attribute; the path can simply point to whether the compiled file would
  283. exist (see :pep:`3147`).
  284. * The loader may set the ``__name__`` attribute of the module. While not
  285. required, setting this attribute is highly recommended so that the
  286. :meth:`repr()` of the module is more informative.
  287. * If the module is a package (either regular or namespace), the loader must
  288. set the module object's ``__path__`` attribute. The value must be
  289. iterable, but may be empty if ``__path__`` has no further significance
  290. to the loader. If ``__path__`` is not empty, it must produce strings
  291. when iterated over. More details on the semantics of ``__path__`` are
  292. given :ref:`below <package-path-rules>`.
  293. * The ``__loader__`` attribute must be set to the loader object that loaded
  294. the module. This is mostly for introspection and reloading, but can be
  295. used for additional loader-specific functionality, for example getting
  296. data associated with a loader. If the attribute is missing or set to ``None``
  297. then the import machinery will automatically set it **after** the module has
  298. been imported.
  299. * The module's ``__package__`` attribute must be set. Its value must be a
  300. string, but it can be the same value as its ``__name__``. If the attribute
  301. is set to ``None`` or is missing, the import system will fill it in with a
  302. more appropriate value **after** the module has been imported.
  303. When the module is a package, its ``__package__`` value should be set to its
  304. ``__name__``. When the module is not a package, ``__package__`` should be
  305. set to the empty string for top-level modules, or for submodules, to the
  306. parent package's name. See :pep:`366` for further details.
  307. This attribute is used instead of ``__name__`` to calculate explicit
  308. relative imports for main modules, as defined in :pep:`366`.
  309. * If the module is a Python module (as opposed to a built-in module or a
  310. dynamically loaded extension), the loader should execute the module's code
  311. in the module's global name space (``module.__dict__``).
  312. Module reprs
  313. ------------
  314. By default, all modules have a usable repr, however depending on the
  315. attributes set above, and hooks in the loader, you can more explicitly control
  316. the repr of module objects.
  317. Loaders may implement a :meth:`module_repr()` method which takes a single
  318. argument, the module object. When ``repr(module)`` is called for a module
  319. with a loader supporting this protocol, whatever is returned from
  320. ``module.__loader__.module_repr(module)`` is returned as the module's repr
  321. without further processing. This return value must be a string.
  322. If the module has no ``__loader__`` attribute, or the loader has no
  323. :meth:`module_repr()` method, then the module object implementation itself
  324. will craft a default repr using whatever information is available. It will
  325. try to use the ``module.__name__``, ``module.__file__``, and
  326. ``module.__loader__`` as input into the repr, with defaults for whatever
  327. information is missing.
  328. Here are the exact rules used:
  329. * If the module has a ``__loader__`` and that loader has a
  330. :meth:`module_repr()` method, call it with a single argument, which is the
  331. module object. The value returned is used as the module's repr.
  332. * If an exception occurs in :meth:`module_repr()`, the exception is caught
  333. and discarded, and the calculation of the module's repr continues as if
  334. :meth:`module_repr()` did not exist.
  335. * If the module has a ``__file__`` attribute, this is used as part of the
  336. module's repr.
  337. * If the module has no ``__file__`` but does have a ``__loader__`` that is not
  338. ``None``, then the loader's repr is used as part of the module's repr.
  339. * Otherwise, just use the module's ``__name__`` in the repr.
  340. This example, from :pep:`420` shows how a loader can craft its own module
  341. repr::
  342. class NamespaceLoader:
  343. @classmethod
  344. def module_repr(cls, module):
  345. return "<module '{}' (namespace)>".format(module.__name__)
  346. .. _package-path-rules:
  347. module.__path__
  348. ---------------
  349. By definition, if a module has an ``__path__`` attribute, it is a package,
  350. regardless of its value.
  351. A package's ``__path__`` attribute is used during imports of its subpackages.
  352. Within the import machinery, it functions much the same as :data:`sys.path`,
  353. i.e. providing a list of locations to search for modules during import.
  354. However, ``__path__`` is typically much more constrained than
  355. :data:`sys.path`.
  356. ``__path__`` must be an iterable of strings, but it may be empty.
  357. The same rules used for :data:`sys.path` also apply to a package's
  358. ``__path__``, and :data:`sys.path_hooks` (described below) are
  359. consulted when traversing a package's ``__path__``.
  360. A package's ``__init__.py`` file may set or alter the package's ``__path__``
  361. attribute, and this was typically the way namespace packages were implemented
  362. prior to :pep:`420`. With the adoption of :pep:`420`, namespace packages no
  363. longer need to supply ``__init__.py`` files containing only ``__path__``
  364. manipulation code; the namespace loader automatically sets ``__path__``
  365. correctly for the namespace package.
  366. The Path Based Finder
  367. =====================
  368. .. index::
  369. single: path based finder
  370. As mentioned previously, Python comes with several default meta path finders.
  371. One of these, called the :term:`path based finder`, searches an :term:`import
  372. path`, which contains a list of :term:`path entries <path entry>`. Each path
  373. entry names a location to search for modules.
  374. The path based finder itself doesn't know how to import anything. Instead, it
  375. traverses the individual path entries, associating each of them with a
  376. path entry finder that knows how to handle that particular kind of path.
  377. The default set of path entry finders implement all the semantics for finding
  378. modules on the file system, handling special file types such as Python source
  379. code (``.py`` files), Python byte code (``.pyc`` and ``.pyo`` files) and
  380. shared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport`
  381. module in the standard library, the default path entry finders also handle
  382. loading all of these file types (other than shared libraries) from zipfiles.
  383. Path entries need not be limited to file system locations. They can refer to
  384. URLs, database queries, or any other location that can be specified as a
  385. string.
  386. The path based finder provides additional hooks and protocols so that you
  387. can extend and customize the types of searchable path entries. For example,
  388. if you wanted to support path entries as network URLs, you could write a hook
  389. that implements HTTP semantics to find modules on the web. This hook (a
  390. callable) would return a :term:`path entry finder` supporting the protocol
  391. described below, which was then used to get a loader for the module from the
  392. web.
  393. A word of warning: this section and the previous both use the term *finder*,
  394. distinguishing between them by using the terms :term:`meta path finder` and
  395. :term:`path entry finder`. These two types of finders are very similar,
  396. support similar protocols, and function in similar ways during the import
  397. process, but it's important to keep in mind that they are subtly different.
  398. In particular, meta path finders operate at the beginning of the import
  399. process, as keyed off the :data:`sys.meta_path` traversal.
  400. By contrast, path entry finders are in a sense an implementation detail
  401. of the path based finder, and in fact, if the path based finder were to be
  402. removed from :data:`sys.meta_path`, none of the path entry finder semantics
  403. would be invoked.
  404. Path entry finders
  405. ------------------
  406. .. index::
  407. single: sys.path
  408. single: sys.path_hooks
  409. single: sys.path_importer_cache
  410. single: PYTHONPATH
  411. The :term:`path based finder` is responsible for finding and loading Python
  412. modules and packages whose location is specified with a string :term:`path
  413. entry`. Most path entries name locations in the file system, but they need
  414. not be limited to this.
  415. As a meta path finder, the :term:`path based finder` implements the
  416. :meth:`find_module()` protocol previously described, however it exposes
  417. additional hooks that can be used to customize how modules are found and
  418. loaded from the :term:`import path`.
  419. Three variables are used by the :term:`path based finder`, :data:`sys.path`,
  420. :data:`sys.path_hooks` and :data:`sys.path_importer_cache`. The ``__path__``
  421. attributes on package objects are also used. These provide additional ways
  422. that the import machinery can be customized.
  423. :data:`sys.path` contains a list of strings providing search locations for
  424. modules and packages. It is initialized from the :data:`PYTHONPATH`
  425. environment variable and various other installation- and
  426. implementation-specific defaults. Entries in :data:`sys.path` can name
  427. directories on the file system, zip files, and potentially other "locations"
  428. (see the :mod:`site` module) that should be searched for modules, such as
  429. URLs, or database queries. Only strings and bytes should be present on
  430. :data:`sys.path`; all other data types are ignored. The encoding of bytes
  431. entries is determined by the individual :term:`path entry finders <path entry
  432. finder>`.
  433. The :term:`path based finder` is a :term:`meta path finder`, so the import
  434. machinery begins the :term:`import path` search by calling the path
  435. based finder's :meth:`find_module()` method as described previously. When
  436. the ``path`` argument to :meth:`find_module()` is given, it will be a
  437. list of string paths to traverse - typically a package's ``__path__``
  438. attribute for an import within that package. If the ``path`` argument
  439. is ``None``, this indicates a top level import and :data:`sys.path` is used.
  440. The path based finder iterates over every entry in the search path, and
  441. for each of these, looks for an appropriate :term:`path entry finder` for the
  442. path entry. Because this can be an expensive operation (e.g. there may be
  443. `stat()` call overheads for this search), the path based finder maintains
  444. a cache mapping path entries to path entry finders. This cache is maintained
  445. in :data:`sys.path_importer_cache` (despite the name, this cache actually
  446. stores finder objects rather than being limited to :term:`importer` objects).
  447. In this way, the expensive search for a particular :term:`path entry`
  448. location's :term:`path entry finder` need only be done once. User code is
  449. free to remove cache entries from :data:`sys.path_importer_cache` forcing
  450. the path based finder to perform the path entry search again [#fnpic]_.
  451. If the path entry is not present in the cache, the path based finder iterates
  452. over every callable in :data:`sys.path_hooks`. Each of the :term:`path entry
  453. hooks <path entry hook>` in this list is called with a single argument, the
  454. path entry to be searched. This callable may either return a :term:`path
  455. entry finder` that can handle the path entry, or it may raise
  456. :exc:`ImportError`. An :exc:`ImportError` is used by the path based finder to
  457. signal that the hook cannot find a :term:`path entry finder` for that
  458. :term:`path entry`. The exception is ignored and :term:`import path`
  459. iteration continues. The hook should expect either a string or bytes object;
  460. the encoding of bytes objects is up to the hook (e.g. it may be a file system
  461. encoding, UTF-8, or something else), and if the hook cannot decode the
  462. argument, it should raise :exc:`ImportError`.
  463. If :data:`sys.path_hooks` iteration ends with no :term:`path entry finder`
  464. being returned, then the path based finder's :meth:`find_module()` method
  465. will store ``None`` in :data:`sys.path_importer_cache` (to indicate that
  466. there is no finder for this path entry) and return ``None``, indicating that
  467. this :term:`meta path finder` could not find the module.
  468. If a :term:`path entry finder` *is* returned by one of the :term:`path entry
  469. hook` callables on :data:`sys.path_hooks`, then the following protocol is used
  470. to ask the finder for a module loader, which is then used to load the module.
  471. Path entry finder protocol
  472. --------------------------
  473. In order to support imports of modules and initialized packages and also to
  474. contribute portions to namespace packages, path entry finders must implement
  475. the :meth:`find_loader()` method.
  476. :meth:`find_loader()` takes one argument, the fully qualified name of the
  477. module being imported. :meth:`find_loader()` returns a 2-tuple where the
  478. first item is the loader and the second item is a namespace :term:`portion`.
  479. When the first item (i.e. the loader) is ``None``, this means that while the
  480. path entry finder does not have a loader for the named module, it knows that the
  481. path entry contributes to a namespace portion for the named module. This will
  482. almost always be the case where Python is asked to import a namespace package
  483. that has no physical presence on the file system. When a path entry finder
  484. returns ``None`` for the loader, the second item of the 2-tuple return value
  485. must be a sequence, although it can be empty.
  486. If :meth:`find_loader()` returns a non-``None`` loader value, the portion is
  487. ignored and the loader is returned from the path based finder, terminating
  488. the search through the path entries.
  489. For backwards compatibility with other implementations of the import
  490. protocol, many path entry finders also support the same,
  491. traditional :meth:`find_module()` method that meta path finders support.
  492. However path entry finder :meth:`find_module()` methods are never called
  493. with a ``path`` argument (they are expected to record the appropriate
  494. path information from the initial call to the path hook).
  495. The :meth:`find_module()` method on path entry finders is deprecated,
  496. as it does not allow the path entry finder to contribute portions to
  497. namespace packages. Instead path entry finders should implement the
  498. :meth:`find_loader()` method as described above. If it exists on the path
  499. entry finder, the import system will always call :meth:`find_loader()`
  500. in preference to :meth:`find_module()`.
  501. Replacing the standard import system
  502. ====================================
  503. The most reliable mechanism for replacing the entire import system is to
  504. delete the default contents of :data:`sys.meta_path`, replacing them
  505. entirely with a custom meta path hook.
  506. If it is acceptable to only alter the behaviour of import statements
  507. without affecting other APIs that access the import system, then replacing
  508. the builtin :func:`__import__` function may be sufficient. This technique
  509. may also be employed at the module level to only alter the behaviour of
  510. import statements within that module.
  511. To selectively prevent import of some modules from a hook early on the
  512. meta path (rather than disabling the standard import system entirely),
  513. it is sufficient to raise :exc:`ImportError` directly from
  514. :meth:`find_module` instead of returning ``None``. The latter indicates
  515. that the meta path search should continue. while raising an exception
  516. terminates it immediately.
  517. Open issues
  518. ===========
  519. XXX It would be really nice to have a diagram.
  520. XXX * (import_machinery.rst) how about a section devoted just to the
  521. attributes of modules and packages, perhaps expanding upon or supplanting the
  522. related entries in the data model reference page?
  523. XXX runpy, pkgutil, et al in the library manual should all get "See Also"
  524. links at the top pointing to the new import system section.
  525. References
  526. ==========
  527. The import machinery has evolved considerably since Python's early days. The
  528. original `specification for packages
  529. <http://www.python.org/doc/essays/packages.html>`_ is still available to read,
  530. although some details have changed since the writing of that document.
  531. The original specification for :data:`sys.meta_path` was :pep:`302`, with
  532. subsequent extension in :pep:`420`.
  533. :pep:`420` introduced :term:`namespace packages <namespace package>` for
  534. Python 3.3. :pep:`420` also introduced the :meth:`find_loader` protocol as an
  535. alternative to :meth:`find_module`.
  536. :pep:`366` describes the addition of the ``__package__`` attribute for
  537. explicit relative imports in main modules.
  538. :pep:`328` introduced absolute and explicit relative imports and initially
  539. proposed ``__name__`` for semantics :pep:`366` would eventually specify for
  540. ``__package__``.
  541. :pep:`338` defines executing modules as scripts.
  542. .. rubric:: Footnotes
  543. .. [#fnmo] See :class:`types.ModuleType`.
  544. .. [#fnlo] The importlib implementation avoids using the return value
  545. directly. Instead, it gets the module object by looking the module name up
  546. in :data:`sys.modules`. The indirect effect of this is that an imported
  547. module may replace itself in :data:`sys.modules`. This is
  548. implementation-specific behavior that is not guaranteed to work in other
  549. Python implementations.
  550. .. [#fnpic] In legacy code, it is possible to find instances of
  551. :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`. It
  552. is recommended that code be changed to use ``None`` instead. See
  553. :ref:`portingpythoncode` for more details.