diff options
| author | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
|---|---|---|
| committer | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
| commit | 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch) | |
| tree | f1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/reference%2Fimport.html | |
new repository
Diffstat (limited to 'devdocs/python~3.12/reference%2Fimport.html')
| -rw-r--r-- | devdocs/python~3.12/reference%2Fimport.html | 118 |
1 files changed, 118 insertions, 0 deletions
diff --git a/devdocs/python~3.12/reference%2Fimport.html b/devdocs/python~3.12/reference%2Fimport.html new file mode 100644 index 00000000..b2304ca6 --- /dev/null +++ b/devdocs/python~3.12/reference%2Fimport.html @@ -0,0 +1,118 @@ + <span id="importsystem"></span><h1> The import system</h1> <p id="index-0">Python code in one <a class="reference internal" href="../glossary#term-module"><span class="xref std std-term">module</span></a> gains access to the code in another module by the process of <a class="reference internal" href="../glossary#term-importing"><span class="xref std std-term">importing</span></a> it. The <a class="reference internal" href="simple_stmts#import"><code>import</code></a> statement is the most common way of invoking the import machinery, but it is not the only way. Functions such as <a class="reference internal" href="../library/importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a> and built-in <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> can also be used to invoke the import machinery.</p> <p>The <a class="reference internal" href="simple_stmts#import"><code>import</code></a> statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the <code>import</code> statement is defined as a call to the <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> function, with the appropriate arguments. The return value of <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> is used to perform the name binding operation of the <code>import</code> statement. See the <code>import</code> statement for the exact details of that name binding operation.</p> <p>A direct call to <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> performs only the module search and, if found, the module creation operation. While certain side-effects may occur, such as the importing of parent packages, and the updating of various caches (including <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>), only the <a class="reference internal" href="simple_stmts#import"><code>import</code></a> statement performs a name binding operation.</p> <p>When an <a class="reference internal" href="simple_stmts#import"><code>import</code></a> statement is executed, the standard builtin <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> function is called. Other mechanisms for invoking the import system (such as <a class="reference internal" href="../library/importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a>) may choose to bypass <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> and use their own solutions to implement import semantics.</p> <p>When a module is first imported, Python searches for the module and if found, it creates a module object <a class="footnote-reference brackets" href="#fnmo" id="id1">1</a>, initializing it. If the named module cannot be found, a <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> is raised. Python implements various strategies to search for the named module when the import machinery is invoked. These strategies can be modified and extended by using various hooks described in the sections below.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>The import system has been updated to fully implement the second phase of <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a>. There is no longer any implicit import machinery - the full import system is exposed through <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>. In addition, native namespace package support has been implemented (see <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a>).</p> </div> <section id="importlib"> <h2> +<span class="section-number">5.1. </span>importlib</h2> <p>The <a class="reference internal" href="../library/importlib#module-importlib" title="importlib: The implementation of the import machinery."><code>importlib</code></a> module provides a rich API for interacting with the import system. For example <a class="reference internal" href="../library/importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a> provides a recommended, simpler API than built-in <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> for invoking the import machinery. Refer to the <a class="reference internal" href="../library/importlib#module-importlib" title="importlib: The implementation of the import machinery."><code>importlib</code></a> library documentation for additional detail.</p> </section> <section id="packages"> <h2> +<span class="section-number">5.2. </span>Packages</h2> <p id="index-3">Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something else. To help organize modules and provide a naming hierarchy, Python has a concept of <a class="reference internal" href="../glossary#term-package"><span class="xref std std-term">packages</span></a>.</p> <p>You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. For the purposes of this documentation, we’ll use this convenient analogy of directories and files. Like file system directories, packages are organized hierarchically, and packages may themselves contain subpackages, as well as regular modules.</p> <p>It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a <code>__path__</code> attribute is considered a package.</p> <p>All modules have a name. Subpackage names are separated from their parent package name by a dot, akin to Python’s standard attribute access syntax. Thus you might have a package called <a class="reference internal" href="../library/email#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages."><code>email</code></a>, which in turn has a subpackage called <a class="reference internal" href="../library/email.mime#module-email.mime" title="email.mime: Build MIME messages."><code>email.mime</code></a> and a module within that subpackage called <code>email.mime.text</code>.</p> <section id="regular-packages"> <h3> +<span class="section-number">5.2.1. </span>Regular packages</h3> <p id="index-4">Python defines two types of packages, <a class="reference internal" href="../glossary#term-regular-package"><span class="xref std std-term">regular packages</span></a> and <a class="reference internal" href="../glossary#term-namespace-package"><span class="xref std std-term">namespace packages</span></a>. Regular packages are traditional packages as they existed in Python 3.2 and earlier. A regular package is typically implemented as a directory containing an <code>__init__.py</code> file. When a regular package is imported, this <code>__init__.py</code> file is implicitly executed, and the objects it defines are bound to names in the package’s namespace. The <code>__init__.py</code> file can contain the same Python code that any other module can contain, and Python will add some additional attributes to the module when it is imported.</p> <p>For example, the following file system layout defines a top level <code>parent</code> package with three subpackages:</p> <pre data-language="python">parent/ + __init__.py + one/ + __init__.py + two/ + __init__.py + three/ + __init__.py +</pre> <p>Importing <code>parent.one</code> will implicitly execute <code>parent/__init__.py</code> and <code>parent/one/__init__.py</code>. Subsequent imports of <code>parent.two</code> or <code>parent.three</code> will execute <code>parent/two/__init__.py</code> and <code>parent/three/__init__.py</code> respectively.</p> </section> <section id="namespace-packages"> <h3> +<span class="section-number">5.2.2. </span>Namespace packages</h3> <p id="index-5">A namespace package is a composite of various <a class="reference internal" href="../glossary#term-portion"><span class="xref std std-term">portions</span></a>, where each portion contributes a subpackage to the parent package. Portions may reside in different locations on the file system. Portions may also be found in zip files, on the network, or anywhere else that Python searches during import. Namespace packages may or may not correspond directly to objects on the file system; they may be virtual modules that have no concrete representation.</p> <p>Namespace packages do not use an ordinary list for their <code>__path__</code> attribute. They instead use a custom iterable type which will automatically perform a new search for package portions on the next import attempt within that package if the path of their parent package (or <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> for a top level package) changes.</p> <p>With namespace packages, there is no <code>parent/__init__.py</code> file. In fact, there may be multiple <code>parent</code> directories found during import search, where each one is provided by a different portion. Thus <code>parent/one</code> may not be physically located next to <code>parent/two</code>. In this case, Python will create a namespace package for the top-level <code>parent</code> package whenever it or one of its subpackages is imported.</p> <p>See also <span class="target" id="index-6"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a> for the namespace package specification.</p> </section> </section> <section id="searching"> <h2> +<span class="section-number">5.3. </span>Searching</h2> <p>To begin the search, Python needs the <a class="reference internal" href="../glossary#term-qualified-name"><span class="xref std std-term">fully qualified</span></a> name of the module (or package, but for the purposes of this discussion, the difference is immaterial) being imported. This name may come from various arguments to the <a class="reference internal" href="simple_stmts#import"><code>import</code></a> statement, or from the parameters to the <a class="reference internal" href="../library/importlib#importlib.import_module" title="importlib.import_module"><code>importlib.import_module()</code></a> or <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> functions.</p> <p>This name will be used in various phases of the import search, and it may be the dotted path to a submodule, e.g. <code>foo.bar.baz</code>. In this case, Python first tries to import <code>foo</code>, then <code>foo.bar</code>, and finally <code>foo.bar.baz</code>. If any of the intermediate imports fail, a <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> is raised.</p> <section id="the-module-cache"> <h3> +<span class="section-number">5.3.1. </span>The module cache</h3> <p id="index-7">The first place checked during import search is <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>. This mapping serves as a cache of all modules that have been previously imported, including the intermediate paths. So if <code>foo.bar.baz</code> was previously imported, <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> will contain entries for <code>foo</code>, <code>foo.bar</code>, and <code>foo.bar.baz</code>. Each key will have as its value the corresponding module object.</p> <p>During import, the module name is looked up in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> and if present, the associated value is the module satisfying the import, and the process completes. However, if the value is <code>None</code>, then a <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> is raised. If the module name is missing, Python will continue searching for the module.</p> <p><a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> is writable. Deleting a key may not destroy the associated module (as other modules may hold references to it), but it will invalidate the cache entry for the named module, causing Python to search anew for the named module upon its next import. The key can also be assigned to <code>None</code>, forcing the next import of the module to result in a <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a>.</p> <p>Beware though, as if you keep a reference to the module object, invalidate its cache entry in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, and then re-import the named module, the two module objects will <em>not</em> be the same. By contrast, <a class="reference internal" href="../library/importlib#importlib.reload" title="importlib.reload"><code>importlib.reload()</code></a> will reuse the <em>same</em> module object, and simply reinitialise the module contents by rerunning the module’s code.</p> </section> <section id="finders-and-loaders"> <span id="id2"></span><h3> +<span class="section-number">5.3.2. </span>Finders and loaders</h3> <p id="index-8">If the named module is not found in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, then Python’s import protocol is invoked to find and load the module. This protocol consists of two conceptual objects, <a class="reference internal" href="../glossary#term-finder"><span class="xref std std-term">finders</span></a> and <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loaders</span></a>. A finder’s job is to determine whether it can find the named module using whatever strategy it knows about. Objects that implement both of these interfaces are referred to as <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importers</span></a> - they return themselves when they find that they can load the requested module.</p> <p>Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate frozen modules. A third default finder searches an <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a> for modules. The <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a> is a list of locations that may name file system paths or zip files. It can also be extended to search for any locatable resource, such as those identified by URLs.</p> <p>The import machinery is extensible, so new finders can be added to extend the range and scope of module searching.</p> <p>Finders do not actually load modules. If they can find the named module, they return a <em class="dfn">module spec</em>, an encapsulation of the module’s import-related information, which the import machinery then uses when loading the module.</p> <p>The following sections describe the protocol for finders and loaders in more detail, including how you can create and register new ones to extend the import machinery.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>In previous versions of Python, finders returned <a class="reference internal" href="../glossary#term-loader"><span class="xref std std-term">loaders</span></a> directly, whereas now they return module specs which <em>contain</em> loaders. Loaders are still used during import but have fewer responsibilities.</p> </div> </section> <section id="import-hooks"> <h3> +<span class="section-number">5.3.3. </span>Import hooks</h3> <p id="index-9">The import machinery is designed to be extensible; the primary mechanism for this are the <em>import hooks</em>. There are two types of import hooks: <em>meta hooks</em> and <em>import path hooks</em>.</p> <p>Meta hooks are called at the start of import processing, before any other import processing has occurred, other than <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> cache look up. This allows meta hooks to override <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> processing, frozen modules, or even built-in modules. Meta hooks are registered by adding new finder objects to <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>, as described below.</p> <p>Import path hooks are called as part of <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> (or <code>package.__path__</code>) processing, at the point where their associated path item is encountered. Import path hooks are registered by adding new callables to <a class="reference internal" href="../library/sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> as described below.</p> </section> <section id="the-meta-path"> <h3> +<span class="section-number">5.3.4. </span>The meta path</h3> <p id="index-10">When the named module is not found in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, Python next searches <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>, which contains a list of meta path finder objects. These finders are queried in order to see if they know how to handle the named module. Meta path finders must implement a method called <a class="reference internal" href="../library/importlib#importlib.abc.MetaPathFinder.find_spec" title="importlib.abc.MetaPathFinder.find_spec"><code>find_spec()</code></a> which takes three arguments: a name, an import path, and (optionally) a target module. The meta path finder can use any strategy it wants to determine whether it can handle the named module or not.</p> <p>If the meta path finder knows how to handle the named module, it returns a spec object. If it cannot handle the named module, it returns <code>None</code>. If <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a> processing reaches the end of its list without returning a spec, then a <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> is raised. Any other exceptions raised are simply propagated up, aborting the import process.</p> <p>The <a class="reference internal" href="../library/importlib#importlib.abc.MetaPathFinder.find_spec" title="importlib.abc.MetaPathFinder.find_spec"><code>find_spec()</code></a> method of meta path finders is called with two or three arguments. The first is the fully qualified name of the module being imported, for example <code>foo.bar.baz</code>. The second argument is the path entries to use for the module search. For top-level modules, the second argument is <code>None</code>, but for submodules or subpackages, the second argument is the value of the parent package’s <code>__path__</code> attribute. If the appropriate <code>__path__</code> attribute cannot be accessed, a <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> is raised. The third argument is an existing module object that will be the target of loading later. The import system passes in a target module only during reload.</p> <p>The meta path may be traversed multiple times for a single import request. For example, assuming none of the modules involved has already been cached, importing <code>foo.bar.baz</code> will first perform a top level import, calling <code>mpf.find_spec("foo", None, None)</code> on each meta path finder (<code>mpf</code>). After <code>foo</code> has been imported, <code>foo.bar</code> will be imported by traversing the meta path a second time, calling <code>mpf.find_spec("foo.bar", foo.__path__, None)</code>. Once <code>foo.bar</code> has been imported, the final traversal will call <code>mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)</code>.</p> <p>Some meta path finders only support top level imports. These importers will always return <code>None</code> when anything other than <code>None</code> is passed as the second argument.</p> <p>Python’s default <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a> has three meta path finders, one that knows how to import built-in modules, one that knows how to import frozen modules, and one that knows how to import modules from an <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a> (i.e. the <a class="reference internal" href="../glossary#term-path-based-finder"><span class="xref std std-term">path based finder</span></a>).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The <a class="reference internal" href="../library/importlib#importlib.abc.MetaPathFinder.find_spec" title="importlib.abc.MetaPathFinder.find_spec"><code>find_spec()</code></a> method of meta path finders replaced <code>find_module()</code>, which is now deprecated. While it will continue to work without change, the import machinery will try it only if the finder does not implement <code>find_spec()</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Use of <code>find_module()</code> by the import system now raises <a class="reference internal" href="../library/exceptions#ImportWarning" title="ImportWarning"><code>ImportWarning</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span><code>find_module()</code> has been removed. Use <code>find_spec()</code> instead.</p> </div> </section> </section> <section id="loading"> <h2> +<span class="section-number">5.4. </span>Loading</h2> <p>If and when a module spec is found, the import machinery will use it (and the loader it contains) when loading the module. Here is an approximation of what happens during the loading portion of import:</p> <pre data-language="python">module = None +if spec.loader is not None and hasattr(spec.loader, 'create_module'): + # It is assumed 'exec_module' will also be defined on the loader. + module = spec.loader.create_module(spec) +if module is None: + module = ModuleType(spec.name) +# The import-related module attributes get set here: +_init_module_attrs(spec, module) + +if spec.loader is None: + # unsupported + raise ImportError +if spec.origin is None and spec.submodule_search_locations is not None: + # namespace package + sys.modules[spec.name] = module +elif not hasattr(spec.loader, 'exec_module'): + module = spec.loader.load_module(spec.name) +else: + sys.modules[spec.name] = module + try: + spec.loader.exec_module(module) + except BaseException: + try: + del sys.modules[spec.name] + except KeyError: + pass + raise +return sys.modules[spec.name] +</pre> <p>Note the following details:</p> <ul class="simple"> <li>If there is an existing module object with the given name in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, import will have already returned it.</li> <li>The module will exist in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> before the loader executes the module code. This is crucial because the module code may (directly or indirectly) import itself; adding it to <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> beforehand prevents unbounded recursion in the worst case and multiple loading in the best.</li> <li>If loading fails, the failing module – and only the failing module – gets removed from <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>. Any module already in the <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> cache, and any module that was successfully loaded as a side-effect, must remain in the cache. This contrasts with reloading where even the failing module is left in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>.</li> <li>After the module is created but before execution, the import machinery sets the import-related module attributes (“_init_module_attrs” in the pseudo-code example above), as summarized in a <a class="reference internal" href="#import-mod-attrs"><span class="std std-ref">later section</span></a>.</li> <li>Module execution is the key moment of loading in which the module’s namespace gets populated. Execution is entirely delegated to the loader, which gets to decide what gets populated and how.</li> <li>The module created during loading and passed to exec_module() may not be the one returned at the end of import <a class="footnote-reference brackets" href="#fnlo" id="id3">2</a>.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The import system has taken over the boilerplate responsibilities of loaders. These were previously performed by the <a class="reference internal" href="../library/importlib#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>importlib.abc.Loader.load_module()</code></a> method.</p> </div> <section id="loaders"> <h3> +<span class="section-number">5.4.1. </span>Loaders</h3> <p>Module loaders provide the critical function of loading: module execution. The import machinery calls the <a class="reference internal" href="../library/importlib#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>importlib.abc.Loader.exec_module()</code></a> method with a single argument, the module object to execute. Any value returned from <a class="reference internal" href="../library/importlib#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> is ignored.</p> <p>Loaders must satisfy the following requirements:</p> <ul class="simple"> <li>If the module is a Python module (as opposed to a built-in module or a dynamically loaded extension), the loader should execute the module’s code in the module’s global name space (<code>module.__dict__</code>).</li> <li>If the loader cannot execute the module, it should raise an <a class="reference internal" href="../library/exceptions#ImportError" title="ImportError"><code>ImportError</code></a>, although any other exception raised during <a class="reference internal" href="../library/importlib#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> will be propagated.</li> </ul> <p>In many cases, the finder and loader can be the same object; in such cases the <a class="reference internal" href="../library/importlib#importlib.abc.MetaPathFinder.find_spec" title="importlib.abc.MetaPathFinder.find_spec"><code>find_spec()</code></a> method would just return a spec with the loader set to <code>self</code>.</p> <p>Module loaders may opt in to creating the module object during loading by implementing a <a class="reference internal" href="../library/importlib#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a> method. It takes one argument, the module spec, and returns the new module object to use during loading. <code>create_module()</code> does not need to set any attributes on the module object. If the method returns <code>None</code>, the import machinery will create the new module itself.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4: </span>The <a class="reference internal" href="../library/importlib#importlib.abc.Loader.create_module" title="importlib.abc.Loader.create_module"><code>create_module()</code></a> method of loaders.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The <a class="reference internal" href="../library/importlib#importlib.abc.Loader.load_module" title="importlib.abc.Loader.load_module"><code>load_module()</code></a> method was replaced by <a class="reference internal" href="../library/importlib#importlib.abc.Loader.exec_module" title="importlib.abc.Loader.exec_module"><code>exec_module()</code></a> and the import machinery assumed all the boilerplate responsibilities of loading.</p> <p>For compatibility with existing loaders, the import machinery will use the <code>load_module()</code> method of loaders if it exists and the loader does not also implement <code>exec_module()</code>. However, <code>load_module()</code> has been deprecated and loaders should implement <code>exec_module()</code> instead.</p> <p>The <code>load_module()</code> method must implement all the boilerplate loading functionality described above in addition to executing the module. All the same constraints apply, with some additional clarification:</p> <ul class="simple"> <li>If there is an existing module object with the given name in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, the loader must use that existing module. (Otherwise, <a class="reference internal" href="../library/importlib#importlib.reload" title="importlib.reload"><code>importlib.reload()</code></a> will not work correctly.) If the named module does not exist in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, the loader must create a new module object and add it to <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>.</li> <li>The module <em>must</em> exist in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a> before the loader executes the module code, to prevent unbounded recursion or multiple loading.</li> <li>If loading fails, the loader must remove any modules it has inserted into <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>, but it must remove <strong>only</strong> the failing module(s), and only if the loader itself has loaded the module(s) explicitly.</li> </ul> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>A <a class="reference internal" href="../library/exceptions#DeprecationWarning" title="DeprecationWarning"><code>DeprecationWarning</code></a> is raised when <code>exec_module()</code> is defined but <code>create_module()</code> is not.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>An <a class="reference internal" href="../library/exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is raised when <code>exec_module()</code> is defined but <code>create_module()</code> is not.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Use of <code>load_module()</code> will raise <a class="reference internal" href="../library/exceptions#ImportWarning" title="ImportWarning"><code>ImportWarning</code></a>.</p> </div> </section> <section id="submodules"> <h3> +<span class="section-number">5.4.2. </span>Submodules</h3> <p>When a submodule is loaded using any mechanism (e.g. <code>importlib</code> APIs, the <code>import</code> or <code>import-from</code> statements, or built-in <code>__import__()</code>) a binding is placed in the parent module’s namespace to the submodule object. For example, if package <code>spam</code> has a submodule <code>foo</code>, after importing <code>spam.foo</code>, <code>spam</code> will have an attribute <code>foo</code> which is bound to the submodule. Let’s say you have the following directory structure:</p> <pre data-language="python">spam/ + __init__.py + foo.py +</pre> <p>and <code>spam/__init__.py</code> has the following line in it:</p> <pre data-language="python">from .foo import Foo +</pre> <p>then executing the following puts name bindings for <code>foo</code> and <code>Foo</code> in the <code>spam</code> module:</p> <pre data-language="python">>>> import spam +>>> spam.foo +<module 'spam.foo' from '/tmp/imports/spam/foo.py'> +>>> spam.Foo +<class 'spam.foo.Foo'> +</pre> <p>Given Python’s familiar name binding rules this might seem surprising, but it’s actually a fundamental feature of the import system. The invariant holding is that if you have <code>sys.modules['spam']</code> and <code>sys.modules['spam.foo']</code> (as you would after the above import), the latter must appear as the <code>foo</code> attribute of the former.</p> </section> <section id="module-spec"> <h3> +<span class="section-number">5.4.3. </span>Module spec</h3> <p>The import machinery uses a variety of information about each module during import, especially before loading. Most of the information is common to all modules. The purpose of a module’s spec is to encapsulate this import-related information on a per-module basis.</p> <p>Using a spec during import allows state to be transferred between import system components, e.g. between the finder that creates the module spec and the loader that executes it. Most importantly, it allows the import machinery to perform the boilerplate operations of loading, whereas without a module spec the loader had that responsibility.</p> <p>The module’s spec is exposed as the <code>__spec__</code> attribute on a module object. See <a class="reference internal" href="../library/importlib#importlib.machinery.ModuleSpec" title="importlib.machinery.ModuleSpec"><code>ModuleSpec</code></a> for details on the contents of the module spec.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> </section> <section id="import-related-module-attributes"> <span id="import-mod-attrs"></span><h3> +<span class="section-number">5.4.4. </span>Import-related module attributes</h3> <p>The import machinery fills in these attributes on each module object during loading, based on the module’s spec, before the loader executes the module.</p> <p>It is <strong>strongly</strong> recommended that you rely on <a class="reference internal" href="#spec__" title="__spec__"><code>__spec__</code></a> and its attributes instead of any of the other individual attributes listed below.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="name__"> +<code>__name__</code> </dt> <dd> +<p>The <code>__name__</code> attribute must be set to the fully qualified name of the module. This name is used to uniquely identify the module in the import system.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="loader__"> +<code>__loader__</code> </dt> <dd> +<p>The <code>__loader__</code> attribute must be set to the loader object that the import machinery used when loading the module. This is mostly for introspection, but can be used for additional loader-specific functionality, for example getting data associated with a loader.</p> <p>It is <strong>strongly</strong> recommended that you rely on <a class="reference internal" href="#spec__" title="__spec__"><code>__spec__</code></a> instead of this attribute.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The value of <code>__loader__</code> is expected to be the same as <code>__spec__.loader</code>. The use of <code>__loader__</code> is deprecated and slated for removal in Python 3.14.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="package__"> +<code>__package__</code> </dt> <dd> +<p>The module’s <code>__package__</code> attribute may be set. Its value must be a string, but it can be the same value as its <code>__name__</code>. When the module is a package, its <code>__package__</code> value should be set to its <code>__name__</code>. When the module is not a package, <code>__package__</code> should be set to the empty string for top-level modules, or for submodules, to the parent package’s name. See <span class="target" id="index-11"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a> for further details.</p> <p>This attribute is used instead of <code>__name__</code> to calculate explicit relative imports for main modules, as defined in <span class="target" id="index-12"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a>.</p> <p>It is <strong>strongly</strong> recommended that you rely on <a class="reference internal" href="#spec__" title="__spec__"><code>__spec__</code></a> instead of this attribute.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The value of <code>__package__</code> is expected to be the same as <code>__spec__.parent</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><a class="reference internal" href="../library/exceptions#ImportWarning" title="ImportWarning"><code>ImportWarning</code></a> is raised if import falls back to <code>__package__</code> instead of <a class="reference internal" href="../library/importlib#importlib.machinery.ModuleSpec.parent" title="importlib.machinery.ModuleSpec.parent"><code>parent</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Raise <a class="reference internal" href="../library/exceptions#DeprecationWarning" title="DeprecationWarning"><code>DeprecationWarning</code></a> instead of <a class="reference internal" href="../library/exceptions#ImportWarning" title="ImportWarning"><code>ImportWarning</code></a> when falling back to <code>__package__</code>.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="spec__"> +<code>__spec__</code> </dt> <dd> +<p>The <code>__spec__</code> attribute must be set to the module spec that was used when importing the module. Setting <code>__spec__</code> appropriately applies equally to <a class="reference internal" href="toplevel_components#programs"><span class="std std-ref">modules initialized during interpreter startup</span></a>. The one exception is <code>__main__</code>, where <code>__spec__</code> is <a class="reference internal" href="#main-spec"><span class="std std-ref">set to None in some cases</span></a>.</p> <p>When <code>__spec__.parent</code> is not set, <code>__package__</code> is used as a fallback.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span><code>__spec__.parent</code> is used as a fallback when <code>__package__</code> is not defined.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="path__"> +<code>__path__</code> </dt> <dd> +<p>If the module is a package (either regular or namespace), the module object’s <code>__path__</code> attribute must be set. The value must be iterable, but may be empty if <code>__path__</code> has no further significance. If <code>__path__</code> is not empty, it must produce strings when iterated over. More details on the semantics of <code>__path__</code> are given <a class="reference internal" href="#package-path-rules"><span class="std std-ref">below</span></a>.</p> <p>Non-package modules should not have a <code>__path__</code> attribute.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="file__"> +<code>__file__</code> </dt> <dd></dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="cached__"> +<code>__cached__</code> </dt> <dd> +<p><code>__file__</code> is optional (if set, value must be a string). It indicates the pathname of the file from which the module was loaded (if loaded from a file), or the pathname of the shared library file for extension modules loaded dynamically from a shared library. It might be missing for certain types of modules, such as C modules that are statically linked into the interpreter, and the import system may opt to leave it unset if it has no semantic meaning (e.g. a module loaded from a database).</p> <p>If <code>__file__</code> is set then the <code>__cached__</code> attribute might also be set, which is the path to any compiled version of the code (e.g. byte-compiled file). The file does not need to exist to set this attribute; the path can simply point to where the compiled file would exist (see <span class="target" id="index-13"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a>).</p> <p>Note that <code>__cached__</code> may be set even if <code>__file__</code> is not set. However, that scenario is quite atypical. Ultimately, the loader is what makes use of the module spec provided by the finder (from which <code>__file__</code> and <code>__cached__</code> are derived). So if a loader can load from a cached module but otherwise does not load from a file, that atypical scenario may be appropriate.</p> <p>It is <strong>strongly</strong> recommended that you rely on <a class="reference internal" href="#spec__" title="__spec__"><code>__spec__</code></a> instead of <code>__cached__</code>.</p> </dd> +</dl> </section> <section id="module-path"> <span id="package-path-rules"></span><h3> +<span class="section-number">5.4.5. </span>module.__path__</h3> <p>By definition, if a module has a <code>__path__</code> attribute, it is a package.</p> <p>A package’s <code>__path__</code> attribute is used during imports of its subpackages. Within the import machinery, it functions much the same as <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a>, i.e. providing a list of locations to search for modules during import. However, <code>__path__</code> is typically much more constrained than <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a>.</p> <p><code>__path__</code> must be an iterable of strings, but it may be empty. The same rules used for <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> also apply to a package’s <code>__path__</code>, and <a class="reference internal" href="../library/sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> (described below) are consulted when traversing a package’s <code>__path__</code>.</p> <p>A package’s <code>__init__.py</code> file may set or alter the package’s <code>__path__</code> attribute, and this was typically the way namespace packages were implemented prior to <span class="target" id="index-14"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a>. With the adoption of <span class="target" id="index-15"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a>, namespace packages no longer need to supply <code>__init__.py</code> files containing only <code>__path__</code> manipulation code; the import machinery automatically sets <code>__path__</code> correctly for the namespace package.</p> </section> <section id="module-reprs"> <h3> +<span class="section-number">5.4.6. </span>Module reprs</h3> <p>By default, all modules have a usable repr, however depending on the attributes set above, and in the module’s spec, you can more explicitly control the repr of module objects.</p> <p>If the module has a spec (<code>__spec__</code>), the import machinery will try to generate a repr from it. If that fails or there is no spec, the import system will craft a default repr using whatever information is available on the module. It will try to use the <code>module.__name__</code>, <code>module.__file__</code>, and <code>module.__loader__</code> as input into the repr, with defaults for whatever information is missing.</p> <p>Here are the exact rules used:</p> <ul class="simple"> <li>If the module has a <code>__spec__</code> attribute, the information in the spec is used to generate the repr. The “name”, “loader”, “origin”, and “has_location” attributes are consulted.</li> <li>If the module has a <code>__file__</code> attribute, this is used as part of the module’s repr.</li> <li>If the module has no <code>__file__</code> but does have a <code>__loader__</code> that is not <code>None</code>, then the loader’s repr is used as part of the module’s repr.</li> <li>Otherwise, just use the module’s <code>__name__</code> in the repr.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Use of <code>module_repr()</code>, having been deprecated since Python 3.4, was removed in Python 3.12 and is no longer called during the resolution of a module’s repr.</p> </div> </section> <section id="cached-bytecode-invalidation"> <span id="pyc-invalidation"></span><h3> +<span class="section-number">5.4.7. </span>Cached bytecode invalidation</h3> <p>Before Python loads cached bytecode from a <code>.pyc</code> file, it checks whether the cache is up-to-date with the source <code>.py</code> file. By default, Python does this by storing the source’s last-modified timestamp and size in the cache file when writing it. At runtime, the import system then validates the cache file by checking the stored metadata in the cache file against the source’s metadata.</p> <p>Python also supports “hash-based” cache files, which store a hash of the source file’s contents rather than its metadata. There are two variants of hash-based <code>.pyc</code> files: checked and unchecked. For checked hash-based <code>.pyc</code> files, Python validates the cache file by hashing the source file and comparing the resulting hash with the hash in the cache file. If a checked hash-based cache file is found to be invalid, Python regenerates it and writes a new checked hash-based cache file. For unchecked hash-based <code>.pyc</code> files, Python simply assumes the cache file is valid if it exists. Hash-based <code>.pyc</code> files validation behavior may be overridden with the <a class="reference internal" href="../using/cmdline#cmdoption-check-hash-based-pycs"><code>--check-hash-based-pycs</code></a> flag.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Added hash-based <code>.pyc</code> files. Previously, Python only supported timestamp-based invalidation of bytecode caches.</p> </div> </section> </section> <section id="the-path-based-finder"> <h2> +<span class="section-number">5.5. </span>The Path Based Finder</h2> <p id="index-16">As mentioned previously, Python comes with several default meta path finders. One of these, called the <a class="reference internal" href="../glossary#term-path-based-finder"><span class="xref std std-term">path based finder</span></a> (<a class="reference internal" href="../library/importlib#importlib.machinery.PathFinder" title="importlib.machinery.PathFinder"><code>PathFinder</code></a>), searches an <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a>, which contains a list of <a class="reference internal" href="../glossary#term-path-entry"><span class="xref std std-term">path entries</span></a>. Each path entry names a location to search for modules.</p> <p>The path based finder itself doesn’t know how to import anything. Instead, it traverses the individual path entries, associating each of them with a path entry finder that knows how to handle that particular kind of path.</p> <p>The default set of path entry finders implement all the semantics for finding modules on the file system, handling special file types such as Python source code (<code>.py</code> files), Python byte code (<code>.pyc</code> files) and shared libraries (e.g. <code>.so</code> files). When supported by the <a class="reference internal" href="../library/zipimport#module-zipimport" title="zipimport: Support for importing Python modules from ZIP archives."><code>zipimport</code></a> module in the standard library, the default path entry finders also handle loading all of these file types (other than shared libraries) from zipfiles.</p> <p>Path entries need not be limited to file system locations. They can refer to URLs, database queries, or any other location that can be specified as a string.</p> <p>The path based finder provides additional hooks and protocols so that you can extend and customize the types of searchable path entries. For example, if you wanted to support path entries as network URLs, you could write a hook that implements HTTP semantics to find modules on the web. This hook (a callable) would return a <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> supporting the protocol described below, which was then used to get a loader for the module from the web.</p> <p>A word of warning: this section and the previous both use the term <em>finder</em>, distinguishing between them by using the terms <a class="reference internal" href="../glossary#term-meta-path-finder"><span class="xref std std-term">meta path finder</span></a> and <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a>. These two types of finders are very similar, support similar protocols, and function in similar ways during the import process, but it’s important to keep in mind that they are subtly different. In particular, meta path finders operate at the beginning of the import process, as keyed off the <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a> traversal.</p> <p>By contrast, path entry finders are in a sense an implementation detail of the path based finder, and in fact, if the path based finder were to be removed from <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>, none of the path entry finder semantics would be invoked.</p> <section id="path-entry-finders"> <h3> +<span class="section-number">5.5.1. </span>Path entry finders</h3> <p id="index-17">The <a class="reference internal" href="../glossary#term-path-based-finder"><span class="xref std std-term">path based finder</span></a> is responsible for finding and loading Python modules and packages whose location is specified with a string <a class="reference internal" href="../glossary#term-path-entry"><span class="xref std std-term">path entry</span></a>. Most path entries name locations in the file system, but they need not be limited to this.</p> <p>As a meta path finder, the <a class="reference internal" href="../glossary#term-path-based-finder"><span class="xref std std-term">path based finder</span></a> implements the <a class="reference internal" href="../library/importlib#importlib.abc.MetaPathFinder.find_spec" title="importlib.abc.MetaPathFinder.find_spec"><code>find_spec()</code></a> protocol previously described, however it exposes additional hooks that can be used to customize how modules are found and loaded from the <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a>.</p> <p>Three variables are used by the <a class="reference internal" href="../glossary#term-path-based-finder"><span class="xref std std-term">path based finder</span></a>, <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a>, <a class="reference internal" href="../library/sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> and <a class="reference internal" href="../library/sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a>. The <code>__path__</code> attributes on package objects are also used. These provide additional ways that the import machinery can be customized.</p> <p><a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> contains a list of strings providing search locations for modules and packages. It is initialized from the <code>PYTHONPATH</code> environment variable and various other installation- and implementation-specific defaults. Entries in <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> can name directories on the file system, zip files, and potentially other “locations” (see the <a class="reference internal" href="../library/site#module-site" title="site: Module responsible for site-specific configuration."><code>site</code></a> module) that should be searched for modules, such as URLs, or database queries. Only strings should be present on <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a>; all other data types are ignored.</p> <p>The <a class="reference internal" href="../glossary#term-path-based-finder"><span class="xref std std-term">path based finder</span></a> is a <a class="reference internal" href="../glossary#term-meta-path-finder"><span class="xref std std-term">meta path finder</span></a>, so the import machinery begins the <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a> search by calling the path based finder’s <a class="reference internal" href="../library/importlib#importlib.machinery.PathFinder.find_spec" title="importlib.machinery.PathFinder.find_spec"><code>find_spec()</code></a> method as described previously. When the <code>path</code> argument to <a class="reference internal" href="../library/importlib#importlib.machinery.PathFinder.find_spec" title="importlib.machinery.PathFinder.find_spec"><code>find_spec()</code></a> is given, it will be a list of string paths to traverse - typically a package’s <code>__path__</code> attribute for an import within that package. If the <code>path</code> argument is <code>None</code>, this indicates a top level import and <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> is used.</p> <p>The path based finder iterates over every entry in the search path, and for each of these, looks for an appropriate <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> (<a class="reference internal" href="../library/importlib#importlib.abc.PathEntryFinder" title="importlib.abc.PathEntryFinder"><code>PathEntryFinder</code></a>) for the path entry. Because this can be an expensive operation (e.g. there may be <code>stat()</code> call overheads for this search), the path based finder maintains a cache mapping path entries to path entry finders. This cache is maintained in <a class="reference internal" href="../library/sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> (despite the name, this cache actually stores finder objects rather than being limited to <a class="reference internal" href="../glossary#term-importer"><span class="xref std std-term">importer</span></a> objects). In this way, the expensive search for a particular <a class="reference internal" href="../glossary#term-path-entry"><span class="xref std std-term">path entry</span></a> location’s <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> need only be done once. User code is free to remove cache entries from <a class="reference internal" href="../library/sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> forcing the path based finder to perform the path entry search again.</p> <p>If the path entry is not present in the cache, the path based finder iterates over every callable in <a class="reference internal" href="../library/sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a>. Each of the <a class="reference internal" href="../glossary#term-path-entry-hook"><span class="xref std std-term">path entry hooks</span></a> in this list is called with a single argument, the path entry to be searched. This callable may either return a <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> that can handle the path entry, or it may raise <a class="reference internal" href="../library/exceptions#ImportError" title="ImportError"><code>ImportError</code></a>. An <a class="reference internal" href="../library/exceptions#ImportError" title="ImportError"><code>ImportError</code></a> is used by the path based finder to signal that the hook cannot find a <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> for that <a class="reference internal" href="../glossary#term-path-entry"><span class="xref std std-term">path entry</span></a>. The exception is ignored and <a class="reference internal" href="../glossary#term-import-path"><span class="xref std std-term">import path</span></a> iteration continues. The hook should expect either a string or bytes object; the encoding of bytes objects is up to the hook (e.g. it may be a file system encoding, UTF-8, or something else), and if the hook cannot decode the argument, it should raise <a class="reference internal" href="../library/exceptions#ImportError" title="ImportError"><code>ImportError</code></a>.</p> <p>If <a class="reference internal" href="../library/sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a> iteration ends with no <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> being returned, then the path based finder’s <a class="reference internal" href="../library/importlib#importlib.machinery.PathFinder.find_spec" title="importlib.machinery.PathFinder.find_spec"><code>find_spec()</code></a> method will store <code>None</code> in <a class="reference internal" href="../library/sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> (to indicate that there is no finder for this path entry) and return <code>None</code>, indicating that this <a class="reference internal" href="../glossary#term-meta-path-finder"><span class="xref std std-term">meta path finder</span></a> could not find the module.</p> <p>If a <a class="reference internal" href="../glossary#term-path-entry-finder"><span class="xref std std-term">path entry finder</span></a> <em>is</em> returned by one of the <a class="reference internal" href="../glossary#term-path-entry-hook"><span class="xref std std-term">path entry hook</span></a> callables on <a class="reference internal" href="../library/sys#sys.path_hooks" title="sys.path_hooks"><code>sys.path_hooks</code></a>, then the following protocol is used to ask the finder for a module spec, which is then used when loading the module.</p> <p>The current working directory – denoted by an empty string – is handled slightly differently from other entries on <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a>. First, if the current working directory is found to not exist, no value is stored in <a class="reference internal" href="../library/sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a>. Second, the value for the current working directory is looked up fresh for each module lookup. Third, the path used for <a class="reference internal" href="../library/sys#sys.path_importer_cache" title="sys.path_importer_cache"><code>sys.path_importer_cache</code></a> and returned by <a class="reference internal" href="../library/importlib#importlib.machinery.PathFinder.find_spec" title="importlib.machinery.PathFinder.find_spec"><code>importlib.machinery.PathFinder.find_spec()</code></a> will be the actual current working directory and not the empty string.</p> </section> <section id="path-entry-finder-protocol"> <h3> +<span class="section-number">5.5.2. </span>Path entry finder protocol</h3> <p>In order to support imports of modules and initialized packages and also to contribute portions to namespace packages, path entry finders must implement the <a class="reference internal" href="../library/importlib#importlib.abc.PathEntryFinder.find_spec" title="importlib.abc.PathEntryFinder.find_spec"><code>find_spec()</code></a> method.</p> <p><a class="reference internal" href="../library/importlib#importlib.abc.PathEntryFinder.find_spec" title="importlib.abc.PathEntryFinder.find_spec"><code>find_spec()</code></a> takes two arguments: the fully qualified name of the module being imported, and the (optional) target module. <code>find_spec()</code> returns a fully populated spec for the module. This spec will always have “loader” set (with one exception).</p> <p>To indicate to the import machinery that the spec represents a namespace <a class="reference internal" href="../glossary#term-portion"><span class="xref std std-term">portion</span></a>, the path entry finder sets <code>submodule_search_locations</code> to a list containing the portion.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span><a class="reference internal" href="../library/importlib#importlib.abc.PathEntryFinder.find_spec" title="importlib.abc.PathEntryFinder.find_spec"><code>find_spec()</code></a> replaced <code>find_loader()</code> and <code>find_module()</code>, both of which are now deprecated, but will be used if <code>find_spec()</code> is not defined.</p> <p>Older path entry finders may implement one of these two deprecated methods instead of <code>find_spec()</code>. The methods are still respected for the sake of backward compatibility. However, if <code>find_spec()</code> is implemented on the path entry finder, the legacy methods are ignored.</p> <p><code>find_loader()</code> takes one argument, the fully qualified name of the module being imported. <code>find_loader()</code> returns a 2-tuple where the first item is the loader and the second item is a namespace <a class="reference internal" href="../glossary#term-portion"><span class="xref std std-term">portion</span></a>.</p> <p>For backwards compatibility with other implementations of the import protocol, many path entry finders also support the same, traditional <code>find_module()</code> method that meta path finders support. However path entry finder <code>find_module()</code> methods are never called with a <code>path</code> argument (they are expected to record the appropriate path information from the initial call to the path hook).</p> <p>The <code>find_module()</code> method on path entry finders is deprecated, as it does not allow the path entry finder to contribute portions to namespace packages. If both <code>find_loader()</code> and <code>find_module()</code> exist on a path entry finder, the import system will always call <code>find_loader()</code> in preference to <code>find_module()</code>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span>Calls to <code>find_module()</code> and <code>find_loader()</code> by the import system will raise <a class="reference internal" href="../library/exceptions#ImportWarning" title="ImportWarning"><code>ImportWarning</code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span><code>find_module()</code> and <code>find_loader()</code> have been removed.</p> </div> </section> </section> <section id="replacing-the-standard-import-system"> <h2> +<span class="section-number">5.6. </span>Replacing the standard import system</h2> <p>The most reliable mechanism for replacing the entire import system is to delete the default contents of <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a>, replacing them entirely with a custom meta path hook.</p> <p>If it is acceptable to only alter the behaviour of import statements without affecting other APIs that access the import system, then replacing the builtin <a class="reference internal" href="../library/functions#import__" title="__import__"><code>__import__()</code></a> function may be sufficient. This technique may also be employed at the module level to only alter the behaviour of import statements within that module.</p> <p>To selectively prevent the import of some modules from a hook early on the meta path (rather than disabling the standard import system entirely), it is sufficient to raise <a class="reference internal" href="../library/exceptions#ModuleNotFoundError" title="ModuleNotFoundError"><code>ModuleNotFoundError</code></a> directly from <a class="reference internal" href="../library/importlib#importlib.abc.MetaPathFinder.find_spec" title="importlib.abc.MetaPathFinder.find_spec"><code>find_spec()</code></a> instead of returning <code>None</code>. The latter indicates that the meta path search should continue, while raising an exception terminates it immediately.</p> </section> <section id="package-relative-imports"> <span id="relativeimports"></span><h2> +<span class="section-number">5.7. </span>Package Relative Imports</h2> <p>Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. For example, given the following package layout:</p> <pre data-language="python">package/ + __init__.py + subpackage1/ + __init__.py + moduleX.py + moduleY.py + subpackage2/ + __init__.py + moduleZ.py + moduleA.py +</pre> <p>In either <code>subpackage1/moduleX.py</code> or <code>subpackage1/__init__.py</code>, the following are valid relative imports:</p> <pre data-language="python">from .moduleY import spam +from .moduleY import spam as ham +from . import moduleY +from ..subpackage1 import moduleY +from ..subpackage2.moduleZ import eggs +from ..moduleA import foo +</pre> <p>Absolute imports may use either the <code>import <></code> or <code>from <> import <></code> syntax, but relative imports may only use the second form; the reason for this is that:</p> <pre data-language="python">import XXX.YYY.ZZZ +</pre> <p>should expose <code>XXX.YYY.ZZZ</code> as a usable expression, but .moduleY is not a valid expression.</p> </section> <section id="special-considerations-for-main"> <span id="import-dunder-main"></span><h2> +<span class="section-number">5.8. </span>Special considerations for __main__</h2> <p>The <a class="reference internal" href="../library/__main__#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code>__main__</code></a> module is a special case relative to Python’s import system. As noted <a class="reference internal" href="toplevel_components#programs"><span class="std std-ref">elsewhere</span></a>, the <code>__main__</code> module is directly initialized at interpreter startup, much like <a class="reference internal" href="../library/sys#module-sys" title="sys: Access system-specific parameters and functions."><code>sys</code></a> and <a class="reference internal" href="../library/builtins#module-builtins" title="builtins: The module that provides the built-in namespace."><code>builtins</code></a>. However, unlike those two, it doesn’t strictly qualify as a built-in module. This is because the manner in which <code>__main__</code> is initialized depends on the flags and other options with which the interpreter is invoked.</p> <section id="main-spec"> <span id="id4"></span><h3> +<span class="section-number">5.8.1. </span>__main__.__spec__</h3> <p>Depending on how <a class="reference internal" href="../library/__main__#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code>__main__</code></a> is initialized, <code>__main__.__spec__</code> gets set appropriately or to <code>None</code>.</p> <p>When Python is started with the <a class="reference internal" href="../using/cmdline#cmdoption-m"><code>-m</code></a> option, <code>__spec__</code> is set to the module spec of the corresponding module or package. <code>__spec__</code> is also populated when the <code>__main__</code> module is loaded as part of executing a directory, zipfile or other <a class="reference internal" href="../library/sys#sys.path" title="sys.path"><code>sys.path</code></a> entry.</p> <p>In <a class="reference internal" href="../using/cmdline#using-on-interface-options"><span class="std std-ref">the remaining cases</span></a> <code>__main__.__spec__</code> is set to <code>None</code>, as the code used to populate the <a class="reference internal" href="../library/__main__#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code>__main__</code></a> does not correspond directly with an importable module:</p> <ul class="simple"> <li>interactive prompt</li> <li> +<a class="reference internal" href="../using/cmdline#cmdoption-c"><code>-c</code></a> option</li> <li>running from stdin</li> <li>running directly from a source or bytecode file</li> </ul> <p>Note that <code>__main__.__spec__</code> is always <code>None</code> in the last case, <em>even if</em> the file could technically be imported directly as a module instead. Use the <a class="reference internal" href="../using/cmdline#cmdoption-m"><code>-m</code></a> switch if valid module metadata is desired in <a class="reference internal" href="../library/__main__#module-__main__" title="__main__: The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and ``__name__ == '__main__'``."><code>__main__</code></a>.</p> <p>Note also that even when <code>__main__</code> corresponds with an importable module and <code>__main__.__spec__</code> is set accordingly, they’re still considered <em>distinct</em> modules. This is due to the fact that blocks guarded by <code>if __name__ == "__main__":</code> checks only execute when the module is used to populate the <code>__main__</code> namespace, and not during normal import.</p> </section> </section> <section id="references"> <h2> +<span class="section-number">5.9. </span>References</h2> <p>The import machinery has evolved considerably since Python’s early days. The original <a class="reference external" href="https://www.python.org/doc/essays/packages/">specification for packages</a> is still available to read, although some details have changed since the writing of that document.</p> <p>The original specification for <a class="reference internal" href="../library/sys#sys.meta_path" title="sys.meta_path"><code>sys.meta_path</code></a> was <span class="target" id="index-18"></span><a class="pep reference external" href="https://peps.python.org/pep-0302/"><strong>PEP 302</strong></a>, with subsequent extension in <span class="target" id="index-19"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a>.</p> <p><span class="target" id="index-20"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a> introduced <a class="reference internal" href="../glossary#term-namespace-package"><span class="xref std std-term">namespace packages</span></a> for Python 3.3. <span class="target" id="index-21"></span><a class="pep reference external" href="https://peps.python.org/pep-0420/"><strong>PEP 420</strong></a> also introduced the <code>find_loader()</code> protocol as an alternative to <code>find_module()</code>.</p> <p><span class="target" id="index-22"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a> describes the addition of the <code>__package__</code> attribute for explicit relative imports in main modules.</p> <p><span class="target" id="index-23"></span><a class="pep reference external" href="https://peps.python.org/pep-0328/"><strong>PEP 328</strong></a> introduced absolute and explicit relative imports and initially proposed <code>__name__</code> for semantics <span class="target" id="index-24"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a> would eventually specify for <code>__package__</code>.</p> <p><span class="target" id="index-25"></span><a class="pep reference external" href="https://peps.python.org/pep-0338/"><strong>PEP 338</strong></a> defines executing modules as scripts.</p> <p><span class="target" id="index-26"></span><a class="pep reference external" href="https://peps.python.org/pep-0451/"><strong>PEP 451</strong></a> adds the encapsulation of per-module import state in spec objects. It also off-loads most of the boilerplate responsibilities of loaders back onto the import machinery. These changes allow the deprecation of several APIs in the import system and also addition of new methods to finders and loaders.</p> <h4 class="rubric">Footnotes</h4> <dl class="footnote brackets"> <dt class="label" id="fnmo"> +<code>1</code> </dt> <dd> +<p>See <a class="reference internal" href="../library/types#types.ModuleType" title="types.ModuleType"><code>types.ModuleType</code></a>.</p> </dd> <dt class="label" id="fnlo"> +<code>2</code> </dt> <dd> +<p>The importlib implementation avoids using the return value directly. Instead, it gets the module object by looking the module name up in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>. The indirect effect of this is that an imported module may replace itself in <a class="reference internal" href="../library/sys#sys.modules" title="sys.modules"><code>sys.modules</code></a>. This is implementation-specific behavior that is not guaranteed to work in other Python implementations.</p> </dd> </dl> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/reference/import.html" class="_attribution-link">https://docs.python.org/3.12/reference/import.html</a> + </p> +</div> |
