17db96d56Sopenharmony_ci
27db96d56Sopenharmony_ci.. _importsystem:
37db96d56Sopenharmony_ci
47db96d56Sopenharmony_ci*****************
57db96d56Sopenharmony_ciThe import system
67db96d56Sopenharmony_ci*****************
77db96d56Sopenharmony_ci
87db96d56Sopenharmony_ci.. index:: single: import machinery
97db96d56Sopenharmony_ci
107db96d56Sopenharmony_ciPython code in one :term:`module` gains access to the code in another module
117db96d56Sopenharmony_ciby the process of :term:`importing` it.  The :keyword:`import` statement is
127db96d56Sopenharmony_cithe most common way of invoking the import machinery, but it is not the only
137db96d56Sopenharmony_ciway.  Functions such as :func:`importlib.import_module` and built-in
147db96d56Sopenharmony_ci:func:`__import__` can also be used to invoke the import machinery.
157db96d56Sopenharmony_ci
167db96d56Sopenharmony_ciThe :keyword:`import` statement combines two operations; it searches for the
177db96d56Sopenharmony_cinamed module, then it binds the results of that search to a name in the local
187db96d56Sopenharmony_ciscope.  The search operation of the :keyword:`!import` statement is defined as
197db96d56Sopenharmony_cia call to the :func:`__import__` function, with the appropriate arguments.
207db96d56Sopenharmony_ciThe return value of :func:`__import__` is used to perform the name
217db96d56Sopenharmony_cibinding operation of the :keyword:`!import` statement.  See the
227db96d56Sopenharmony_ci:keyword:`!import` statement for the exact details of that name binding
237db96d56Sopenharmony_cioperation.
247db96d56Sopenharmony_ci
257db96d56Sopenharmony_ciA direct call to :func:`__import__` performs only the module search and, if
267db96d56Sopenharmony_cifound, the module creation operation.  While certain side-effects may occur,
277db96d56Sopenharmony_cisuch as the importing of parent packages, and the updating of various caches
287db96d56Sopenharmony_ci(including :data:`sys.modules`), only the :keyword:`import` statement performs
297db96d56Sopenharmony_cia name binding operation.
307db96d56Sopenharmony_ci
317db96d56Sopenharmony_ciWhen an :keyword:`import` statement is executed, the standard builtin
327db96d56Sopenharmony_ci:func:`__import__` function is called. Other mechanisms for invoking the
337db96d56Sopenharmony_ciimport system (such as :func:`importlib.import_module`) may choose to bypass
347db96d56Sopenharmony_ci:func:`__import__` and use their own solutions to implement import semantics.
357db96d56Sopenharmony_ci
367db96d56Sopenharmony_ciWhen a module is first imported, Python searches for the module and if found,
377db96d56Sopenharmony_ciit creates a module object [#fnmo]_, initializing it.  If the named module
387db96d56Sopenharmony_cicannot be found, a :exc:`ModuleNotFoundError` is raised.  Python implements various
397db96d56Sopenharmony_cistrategies to search for the named module when the import machinery is
407db96d56Sopenharmony_ciinvoked.  These strategies can be modified and extended by using various hooks
417db96d56Sopenharmony_cidescribed in the sections below.
427db96d56Sopenharmony_ci
437db96d56Sopenharmony_ci.. versionchanged:: 3.3
447db96d56Sopenharmony_ci   The import system has been updated to fully implement the second phase
457db96d56Sopenharmony_ci   of :pep:`302`. There is no longer any implicit import machinery - the full
467db96d56Sopenharmony_ci   import system is exposed through :data:`sys.meta_path`. In addition,
477db96d56Sopenharmony_ci   native namespace package support has been implemented (see :pep:`420`).
487db96d56Sopenharmony_ci
497db96d56Sopenharmony_ci
507db96d56Sopenharmony_ci:mod:`importlib`
517db96d56Sopenharmony_ci================
527db96d56Sopenharmony_ci
537db96d56Sopenharmony_ciThe :mod:`importlib` module provides a rich API for interacting with the
547db96d56Sopenharmony_ciimport system.  For example :func:`importlib.import_module` provides a
557db96d56Sopenharmony_cirecommended, simpler API than built-in :func:`__import__` for invoking the
567db96d56Sopenharmony_ciimport machinery.  Refer to the :mod:`importlib` library documentation for
577db96d56Sopenharmony_ciadditional detail.
587db96d56Sopenharmony_ci
597db96d56Sopenharmony_ci
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ciPackages
627db96d56Sopenharmony_ci========
637db96d56Sopenharmony_ci
647db96d56Sopenharmony_ci.. index::
657db96d56Sopenharmony_ci    single: package
667db96d56Sopenharmony_ci
677db96d56Sopenharmony_ciPython has only one type of module object, and all modules are of this type,
687db96d56Sopenharmony_ciregardless of whether the module is implemented in Python, C, or something
697db96d56Sopenharmony_cielse.  To help organize modules and provide a naming hierarchy, Python has a
707db96d56Sopenharmony_ciconcept of :term:`packages <package>`.
717db96d56Sopenharmony_ci
727db96d56Sopenharmony_ciYou can think of packages as the directories on a file system and modules as
737db96d56Sopenharmony_cifiles within directories, but don't take this analogy too literally since
747db96d56Sopenharmony_cipackages and modules need not originate from the file system.  For the
757db96d56Sopenharmony_cipurposes of this documentation, we'll use this convenient analogy of
767db96d56Sopenharmony_cidirectories and files.  Like file system directories, packages are organized
777db96d56Sopenharmony_cihierarchically, and packages may themselves contain subpackages, as well as
787db96d56Sopenharmony_ciregular modules.
797db96d56Sopenharmony_ci
807db96d56Sopenharmony_ciIt's important to keep in mind that all packages are modules, but not all
817db96d56Sopenharmony_cimodules are packages.  Or put another way, packages are just a special kind of
827db96d56Sopenharmony_cimodule.  Specifically, any module that contains a ``__path__`` attribute is
837db96d56Sopenharmony_ciconsidered a package.
847db96d56Sopenharmony_ci
857db96d56Sopenharmony_ciAll modules have a name.  Subpackage names are separated from their parent
867db96d56Sopenharmony_cipackage name by a dot, akin to Python's standard attribute access syntax.  Thus
877db96d56Sopenharmony_ciyou might have a package called :mod:`email`, which in turn has a subpackage
887db96d56Sopenharmony_cicalled :mod:`email.mime` and a module within that subpackage called
897db96d56Sopenharmony_ci:mod:`email.mime.text`.
907db96d56Sopenharmony_ci
917db96d56Sopenharmony_ci
927db96d56Sopenharmony_ciRegular packages
937db96d56Sopenharmony_ci----------------
947db96d56Sopenharmony_ci
957db96d56Sopenharmony_ci.. index::
967db96d56Sopenharmony_ci    pair: package; regular
977db96d56Sopenharmony_ci
987db96d56Sopenharmony_ciPython defines two types of packages, :term:`regular packages <regular
997db96d56Sopenharmony_cipackage>` and :term:`namespace packages <namespace package>`.  Regular
1007db96d56Sopenharmony_cipackages are traditional packages as they existed in Python 3.2 and earlier.
1017db96d56Sopenharmony_ciA regular package is typically implemented as a directory containing an
1027db96d56Sopenharmony_ci``__init__.py`` file.  When a regular package is imported, this
1037db96d56Sopenharmony_ci``__init__.py`` file is implicitly executed, and the objects it defines are
1047db96d56Sopenharmony_cibound to names in the package's namespace.  The ``__init__.py`` file can
1057db96d56Sopenharmony_cicontain the same Python code that any other module can contain, and Python
1067db96d56Sopenharmony_ciwill add some additional attributes to the module when it is imported.
1077db96d56Sopenharmony_ci
1087db96d56Sopenharmony_ciFor example, the following file system layout defines a top level ``parent``
1097db96d56Sopenharmony_cipackage with three subpackages::
1107db96d56Sopenharmony_ci
1117db96d56Sopenharmony_ci    parent/
1127db96d56Sopenharmony_ci        __init__.py
1137db96d56Sopenharmony_ci        one/
1147db96d56Sopenharmony_ci            __init__.py
1157db96d56Sopenharmony_ci        two/
1167db96d56Sopenharmony_ci            __init__.py
1177db96d56Sopenharmony_ci        three/
1187db96d56Sopenharmony_ci            __init__.py
1197db96d56Sopenharmony_ci
1207db96d56Sopenharmony_ciImporting ``parent.one`` will implicitly execute ``parent/__init__.py`` and
1217db96d56Sopenharmony_ci``parent/one/__init__.py``.  Subsequent imports of ``parent.two`` or
1227db96d56Sopenharmony_ci``parent.three`` will execute ``parent/two/__init__.py`` and
1237db96d56Sopenharmony_ci``parent/three/__init__.py`` respectively.
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ci
1267db96d56Sopenharmony_ciNamespace packages
1277db96d56Sopenharmony_ci------------------
1287db96d56Sopenharmony_ci
1297db96d56Sopenharmony_ci.. index::
1307db96d56Sopenharmony_ci    pair: package; namespace
1317db96d56Sopenharmony_ci    pair: package; portion
1327db96d56Sopenharmony_ci
1337db96d56Sopenharmony_ciA namespace package is a composite of various :term:`portions <portion>`,
1347db96d56Sopenharmony_ciwhere each portion contributes a subpackage to the parent package.  Portions
1357db96d56Sopenharmony_cimay reside in different locations on the file system.  Portions may also be
1367db96d56Sopenharmony_cifound in zip files, on the network, or anywhere else that Python searches
1377db96d56Sopenharmony_ciduring import.  Namespace packages may or may not correspond directly to
1387db96d56Sopenharmony_ciobjects on the file system; they may be virtual modules that have no concrete
1397db96d56Sopenharmony_cirepresentation.
1407db96d56Sopenharmony_ci
1417db96d56Sopenharmony_ciNamespace packages do not use an ordinary list for their ``__path__``
1427db96d56Sopenharmony_ciattribute. They instead use a custom iterable type which will automatically
1437db96d56Sopenharmony_ciperform a new search for package portions on the next import attempt within
1447db96d56Sopenharmony_cithat package if the path of their parent package (or :data:`sys.path` for a
1457db96d56Sopenharmony_citop level package) changes.
1467db96d56Sopenharmony_ci
1477db96d56Sopenharmony_ciWith namespace packages, there is no ``parent/__init__.py`` file.  In fact,
1487db96d56Sopenharmony_cithere may be multiple ``parent`` directories found during import search, where
1497db96d56Sopenharmony_cieach one is provided by a different portion.  Thus ``parent/one`` may not be
1507db96d56Sopenharmony_ciphysically located next to ``parent/two``.  In this case, Python will create a
1517db96d56Sopenharmony_cinamespace package for the top-level ``parent`` package whenever it or one of
1527db96d56Sopenharmony_ciits subpackages is imported.
1537db96d56Sopenharmony_ci
1547db96d56Sopenharmony_ciSee also :pep:`420` for the namespace package specification.
1557db96d56Sopenharmony_ci
1567db96d56Sopenharmony_ci
1577db96d56Sopenharmony_ciSearching
1587db96d56Sopenharmony_ci=========
1597db96d56Sopenharmony_ci
1607db96d56Sopenharmony_ciTo begin the search, Python needs the :term:`fully qualified <qualified name>`
1617db96d56Sopenharmony_ciname of the module (or package, but for the purposes of this discussion, the
1627db96d56Sopenharmony_cidifference is immaterial) being imported.  This name may come from various
1637db96d56Sopenharmony_ciarguments to the :keyword:`import` statement, or from the parameters to the
1647db96d56Sopenharmony_ci:func:`importlib.import_module` or :func:`__import__` functions.
1657db96d56Sopenharmony_ci
1667db96d56Sopenharmony_ciThis name will be used in various phases of the import search, and it may be
1677db96d56Sopenharmony_cithe dotted path to a submodule, e.g. ``foo.bar.baz``.  In this case, Python
1687db96d56Sopenharmony_cifirst tries to import ``foo``, then ``foo.bar``, and finally ``foo.bar.baz``.
1697db96d56Sopenharmony_ciIf any of the intermediate imports fail, a :exc:`ModuleNotFoundError` is raised.
1707db96d56Sopenharmony_ci
1717db96d56Sopenharmony_ci
1727db96d56Sopenharmony_ciThe module cache
1737db96d56Sopenharmony_ci----------------
1747db96d56Sopenharmony_ci
1757db96d56Sopenharmony_ci.. index::
1767db96d56Sopenharmony_ci    single: sys.modules
1777db96d56Sopenharmony_ci
1787db96d56Sopenharmony_ciThe first place checked during import search is :data:`sys.modules`.  This
1797db96d56Sopenharmony_cimapping serves as a cache of all modules that have been previously imported,
1807db96d56Sopenharmony_ciincluding the intermediate paths.  So if ``foo.bar.baz`` was previously
1817db96d56Sopenharmony_ciimported, :data:`sys.modules` will contain entries for ``foo``, ``foo.bar``,
1827db96d56Sopenharmony_ciand ``foo.bar.baz``.  Each key will have as its value the corresponding module
1837db96d56Sopenharmony_ciobject.
1847db96d56Sopenharmony_ci
1857db96d56Sopenharmony_ciDuring import, the module name is looked up in :data:`sys.modules` and if
1867db96d56Sopenharmony_cipresent, the associated value is the module satisfying the import, and the
1877db96d56Sopenharmony_ciprocess completes.  However, if the value is ``None``, then a
1887db96d56Sopenharmony_ci:exc:`ModuleNotFoundError` is raised.  If the module name is missing, Python will
1897db96d56Sopenharmony_cicontinue searching for the module.
1907db96d56Sopenharmony_ci
1917db96d56Sopenharmony_ci:data:`sys.modules` is writable.  Deleting a key may not destroy the
1927db96d56Sopenharmony_ciassociated module (as other modules may hold references to it),
1937db96d56Sopenharmony_cibut it will invalidate the cache entry for the named module, causing
1947db96d56Sopenharmony_ciPython to search anew for the named module upon its next
1957db96d56Sopenharmony_ciimport. The key can also be assigned to ``None``, forcing the next import
1967db96d56Sopenharmony_ciof the module to result in a :exc:`ModuleNotFoundError`.
1977db96d56Sopenharmony_ci
1987db96d56Sopenharmony_ciBeware though, as if you keep a reference to the module object,
1997db96d56Sopenharmony_ciinvalidate its cache entry in :data:`sys.modules`, and then re-import the
2007db96d56Sopenharmony_cinamed module, the two module objects will *not* be the same. By contrast,
2017db96d56Sopenharmony_ci:func:`importlib.reload` will reuse the *same* module object, and simply
2027db96d56Sopenharmony_cireinitialise the module contents by rerunning the module's code.
2037db96d56Sopenharmony_ci
2047db96d56Sopenharmony_ci
2057db96d56Sopenharmony_ci.. _finders-and-loaders:
2067db96d56Sopenharmony_ci
2077db96d56Sopenharmony_ciFinders and loaders
2087db96d56Sopenharmony_ci-------------------
2097db96d56Sopenharmony_ci
2107db96d56Sopenharmony_ci.. index::
2117db96d56Sopenharmony_ci    single: finder
2127db96d56Sopenharmony_ci    single: loader
2137db96d56Sopenharmony_ci    single: module spec
2147db96d56Sopenharmony_ci
2157db96d56Sopenharmony_ciIf the named module is not found in :data:`sys.modules`, then Python's import
2167db96d56Sopenharmony_ciprotocol is invoked to find and load the module.  This protocol consists of
2177db96d56Sopenharmony_citwo conceptual objects, :term:`finders <finder>` and :term:`loaders <loader>`.
2187db96d56Sopenharmony_ciA finder's job is to determine whether it can find the named module using
2197db96d56Sopenharmony_ciwhatever strategy it knows about. Objects that implement both of these
2207db96d56Sopenharmony_ciinterfaces are referred to as :term:`importers <importer>` - they return
2217db96d56Sopenharmony_cithemselves when they find that they can load the requested module.
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ciPython includes a number of default finders and importers.  The first one
2247db96d56Sopenharmony_ciknows how to locate built-in modules, and the second knows how to locate
2257db96d56Sopenharmony_cifrozen modules.  A third default finder searches an :term:`import path`
2267db96d56Sopenharmony_cifor modules.  The :term:`import path` is a list of locations that may
2277db96d56Sopenharmony_ciname file system paths or zip files.  It can also be extended to search
2287db96d56Sopenharmony_cifor any locatable resource, such as those identified by URLs.
2297db96d56Sopenharmony_ci
2307db96d56Sopenharmony_ciThe import machinery is extensible, so new finders can be added to extend the
2317db96d56Sopenharmony_cirange and scope of module searching.
2327db96d56Sopenharmony_ci
2337db96d56Sopenharmony_ciFinders do not actually load modules.  If they can find the named module, they
2347db96d56Sopenharmony_cireturn a :dfn:`module spec`, an encapsulation of the module's import-related
2357db96d56Sopenharmony_ciinformation, which the import machinery then uses when loading the module.
2367db96d56Sopenharmony_ci
2377db96d56Sopenharmony_ciThe following sections describe the protocol for finders and loaders in more
2387db96d56Sopenharmony_cidetail, including how you can create and register new ones to extend the
2397db96d56Sopenharmony_ciimport machinery.
2407db96d56Sopenharmony_ci
2417db96d56Sopenharmony_ci.. versionchanged:: 3.4
2427db96d56Sopenharmony_ci   In previous versions of Python, finders returned :term:`loaders <loader>`
2437db96d56Sopenharmony_ci   directly, whereas now they return module specs which *contain* loaders.
2447db96d56Sopenharmony_ci   Loaders are still used during import but have fewer responsibilities.
2457db96d56Sopenharmony_ci
2467db96d56Sopenharmony_ciImport hooks
2477db96d56Sopenharmony_ci------------
2487db96d56Sopenharmony_ci
2497db96d56Sopenharmony_ci.. index::
2507db96d56Sopenharmony_ci   single: import hooks
2517db96d56Sopenharmony_ci   single: meta hooks
2527db96d56Sopenharmony_ci   single: path hooks
2537db96d56Sopenharmony_ci   pair: hooks; import
2547db96d56Sopenharmony_ci   pair: hooks; meta
2557db96d56Sopenharmony_ci   pair: hooks; path
2567db96d56Sopenharmony_ci
2577db96d56Sopenharmony_ciThe import machinery is designed to be extensible; the primary mechanism for
2587db96d56Sopenharmony_cithis are the *import hooks*.  There are two types of import hooks: *meta
2597db96d56Sopenharmony_cihooks* and *import path hooks*.
2607db96d56Sopenharmony_ci
2617db96d56Sopenharmony_ciMeta hooks are called at the start of import processing, before any other
2627db96d56Sopenharmony_ciimport processing has occurred, other than :data:`sys.modules` cache look up.
2637db96d56Sopenharmony_ciThis allows meta hooks to override :data:`sys.path` processing, frozen
2647db96d56Sopenharmony_cimodules, or even built-in modules.  Meta hooks are registered by adding new
2657db96d56Sopenharmony_cifinder objects to :data:`sys.meta_path`, as described below.
2667db96d56Sopenharmony_ci
2677db96d56Sopenharmony_ciImport path hooks are called as part of :data:`sys.path` (or
2687db96d56Sopenharmony_ci``package.__path__``) processing, at the point where their associated path
2697db96d56Sopenharmony_ciitem is encountered.  Import path hooks are registered by adding new callables
2707db96d56Sopenharmony_cito :data:`sys.path_hooks` as described below.
2717db96d56Sopenharmony_ci
2727db96d56Sopenharmony_ci
2737db96d56Sopenharmony_ciThe meta path
2747db96d56Sopenharmony_ci-------------
2757db96d56Sopenharmony_ci
2767db96d56Sopenharmony_ci.. index::
2777db96d56Sopenharmony_ci    single: sys.meta_path
2787db96d56Sopenharmony_ci    pair: finder; find_spec
2797db96d56Sopenharmony_ci
2807db96d56Sopenharmony_ciWhen the named module is not found in :data:`sys.modules`, Python next
2817db96d56Sopenharmony_cisearches :data:`sys.meta_path`, which contains a list of meta path finder
2827db96d56Sopenharmony_ciobjects.  These finders are queried in order to see if they know how to handle
2837db96d56Sopenharmony_cithe named module.  Meta path finders must implement a method called
2847db96d56Sopenharmony_ci:meth:`~importlib.abc.MetaPathFinder.find_spec()` which takes three arguments:
2857db96d56Sopenharmony_cia name, an import path, and (optionally) a target module.  The meta path
2867db96d56Sopenharmony_cifinder can use any strategy it wants to determine whether it can handle
2877db96d56Sopenharmony_cithe named module or not.
2887db96d56Sopenharmony_ci
2897db96d56Sopenharmony_ciIf the meta path finder knows how to handle the named module, it returns a
2907db96d56Sopenharmony_cispec object.  If it cannot handle the named module, it returns ``None``.  If
2917db96d56Sopenharmony_ci:data:`sys.meta_path` processing reaches the end of its list without returning
2927db96d56Sopenharmony_cia spec, then a :exc:`ModuleNotFoundError` is raised.  Any other exceptions
2937db96d56Sopenharmony_ciraised are simply propagated up, aborting the import process.
2947db96d56Sopenharmony_ci
2957db96d56Sopenharmony_ciThe :meth:`~importlib.abc.MetaPathFinder.find_spec()` method of meta path
2967db96d56Sopenharmony_cifinders is called with two or three arguments.  The first is the fully
2977db96d56Sopenharmony_ciqualified name of the module being imported, for example ``foo.bar.baz``.
2987db96d56Sopenharmony_ciThe second argument is the path entries to use for the module search.  For
2997db96d56Sopenharmony_citop-level modules, the second argument is ``None``, but for submodules or
3007db96d56Sopenharmony_cisubpackages, the second argument is the value of the parent package's
3017db96d56Sopenharmony_ci``__path__`` attribute. If the appropriate ``__path__`` attribute cannot
3027db96d56Sopenharmony_cibe accessed, a :exc:`ModuleNotFoundError` is raised.  The third argument
3037db96d56Sopenharmony_ciis an existing module object that will be the target of loading later.
3047db96d56Sopenharmony_ciThe import system passes in a target module only during reload.
3057db96d56Sopenharmony_ci
3067db96d56Sopenharmony_ciThe meta path may be traversed multiple times for a single import request.
3077db96d56Sopenharmony_ciFor example, assuming none of the modules involved has already been cached,
3087db96d56Sopenharmony_ciimporting ``foo.bar.baz`` will first perform a top level import, calling
3097db96d56Sopenharmony_ci``mpf.find_spec("foo", None, None)`` on each meta path finder (``mpf``). After
3107db96d56Sopenharmony_ci``foo`` has been imported, ``foo.bar`` will be imported by traversing the
3117db96d56Sopenharmony_cimeta path a second time, calling
3127db96d56Sopenharmony_ci``mpf.find_spec("foo.bar", foo.__path__, None)``. Once ``foo.bar`` has been
3137db96d56Sopenharmony_ciimported, the final traversal will call
3147db96d56Sopenharmony_ci``mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)``.
3157db96d56Sopenharmony_ci
3167db96d56Sopenharmony_ciSome meta path finders only support top level imports. These importers will
3177db96d56Sopenharmony_cialways return ``None`` when anything other than ``None`` is passed as the
3187db96d56Sopenharmony_cisecond argument.
3197db96d56Sopenharmony_ci
3207db96d56Sopenharmony_ciPython's default :data:`sys.meta_path` has three meta path finders, one that
3217db96d56Sopenharmony_ciknows how to import built-in modules, one that knows how to import frozen
3227db96d56Sopenharmony_cimodules, and one that knows how to import modules from an :term:`import path`
3237db96d56Sopenharmony_ci(i.e. the :term:`path based finder`).
3247db96d56Sopenharmony_ci
3257db96d56Sopenharmony_ci.. versionchanged:: 3.4
3267db96d56Sopenharmony_ci   The :meth:`~importlib.abc.MetaPathFinder.find_spec` method of meta path
3277db96d56Sopenharmony_ci   finders replaced :meth:`~importlib.abc.MetaPathFinder.find_module`, which
3287db96d56Sopenharmony_ci   is now deprecated.  While it will continue to work without change, the
3297db96d56Sopenharmony_ci   import machinery will try it only if the finder does not implement
3307db96d56Sopenharmony_ci   ``find_spec()``.
3317db96d56Sopenharmony_ci
3327db96d56Sopenharmony_ci.. versionchanged:: 3.10
3337db96d56Sopenharmony_ci   Use of :meth:`~importlib.abc.MetaPathFinder.find_module` by the import system
3347db96d56Sopenharmony_ci   now raises :exc:`ImportWarning`.
3357db96d56Sopenharmony_ci
3367db96d56Sopenharmony_ci
3377db96d56Sopenharmony_ciLoading
3387db96d56Sopenharmony_ci=======
3397db96d56Sopenharmony_ci
3407db96d56Sopenharmony_ciIf and when a module spec is found, the import machinery will use it (and
3417db96d56Sopenharmony_cithe loader it contains) when loading the module.  Here is an approximation
3427db96d56Sopenharmony_ciof what happens during the loading portion of import::
3437db96d56Sopenharmony_ci
3447db96d56Sopenharmony_ci    module = None
3457db96d56Sopenharmony_ci    if spec.loader is not None and hasattr(spec.loader, 'create_module'):
3467db96d56Sopenharmony_ci        # It is assumed 'exec_module' will also be defined on the loader.
3477db96d56Sopenharmony_ci        module = spec.loader.create_module(spec)
3487db96d56Sopenharmony_ci    if module is None:
3497db96d56Sopenharmony_ci        module = ModuleType(spec.name)
3507db96d56Sopenharmony_ci    # The import-related module attributes get set here:
3517db96d56Sopenharmony_ci    _init_module_attrs(spec, module)
3527db96d56Sopenharmony_ci
3537db96d56Sopenharmony_ci    if spec.loader is None:
3547db96d56Sopenharmony_ci        # unsupported
3557db96d56Sopenharmony_ci        raise ImportError
3567db96d56Sopenharmony_ci    if spec.origin is None and spec.submodule_search_locations is not None:
3577db96d56Sopenharmony_ci        # namespace package
3587db96d56Sopenharmony_ci        sys.modules[spec.name] = module
3597db96d56Sopenharmony_ci    elif not hasattr(spec.loader, 'exec_module'):
3607db96d56Sopenharmony_ci        module = spec.loader.load_module(spec.name)
3617db96d56Sopenharmony_ci        # Set __loader__ and __package__ if missing.
3627db96d56Sopenharmony_ci    else:
3637db96d56Sopenharmony_ci        sys.modules[spec.name] = module
3647db96d56Sopenharmony_ci        try:
3657db96d56Sopenharmony_ci            spec.loader.exec_module(module)
3667db96d56Sopenharmony_ci        except BaseException:
3677db96d56Sopenharmony_ci            try:
3687db96d56Sopenharmony_ci                del sys.modules[spec.name]
3697db96d56Sopenharmony_ci            except KeyError:
3707db96d56Sopenharmony_ci                pass
3717db96d56Sopenharmony_ci            raise
3727db96d56Sopenharmony_ci    return sys.modules[spec.name]
3737db96d56Sopenharmony_ci
3747db96d56Sopenharmony_ciNote the following details:
3757db96d56Sopenharmony_ci
3767db96d56Sopenharmony_ci * If there is an existing module object with the given name in
3777db96d56Sopenharmony_ci   :data:`sys.modules`, import will have already returned it.
3787db96d56Sopenharmony_ci
3797db96d56Sopenharmony_ci * The module will exist in :data:`sys.modules` before the loader
3807db96d56Sopenharmony_ci   executes the module code.  This is crucial because the module code may
3817db96d56Sopenharmony_ci   (directly or indirectly) import itself; adding it to :data:`sys.modules`
3827db96d56Sopenharmony_ci   beforehand prevents unbounded recursion in the worst case and multiple
3837db96d56Sopenharmony_ci   loading in the best.
3847db96d56Sopenharmony_ci
3857db96d56Sopenharmony_ci * If loading fails, the failing module -- and only the failing module --
3867db96d56Sopenharmony_ci   gets removed from :data:`sys.modules`.  Any module already in the
3877db96d56Sopenharmony_ci   :data:`sys.modules` cache, and any module that was successfully loaded
3887db96d56Sopenharmony_ci   as a side-effect, must remain in the cache.  This contrasts with
3897db96d56Sopenharmony_ci   reloading where even the failing module is left in :data:`sys.modules`.
3907db96d56Sopenharmony_ci
3917db96d56Sopenharmony_ci * After the module is created but before execution, the import machinery
3927db96d56Sopenharmony_ci   sets the import-related module attributes ("_init_module_attrs" in
3937db96d56Sopenharmony_ci   the pseudo-code example above), as summarized in a
3947db96d56Sopenharmony_ci   :ref:`later section <import-mod-attrs>`.
3957db96d56Sopenharmony_ci
3967db96d56Sopenharmony_ci * Module execution is the key moment of loading in which the module's
3977db96d56Sopenharmony_ci   namespace gets populated.  Execution is entirely delegated to the
3987db96d56Sopenharmony_ci   loader, which gets to decide what gets populated and how.
3997db96d56Sopenharmony_ci
4007db96d56Sopenharmony_ci * The module created during loading and passed to exec_module() may
4017db96d56Sopenharmony_ci   not be the one returned at the end of import [#fnlo]_.
4027db96d56Sopenharmony_ci
4037db96d56Sopenharmony_ci.. versionchanged:: 3.4
4047db96d56Sopenharmony_ci   The import system has taken over the boilerplate responsibilities of
4057db96d56Sopenharmony_ci   loaders.  These were previously performed by the
4067db96d56Sopenharmony_ci   :meth:`importlib.abc.Loader.load_module` method.
4077db96d56Sopenharmony_ci
4087db96d56Sopenharmony_ciLoaders
4097db96d56Sopenharmony_ci-------
4107db96d56Sopenharmony_ci
4117db96d56Sopenharmony_ciModule loaders provide the critical function of loading: module execution.
4127db96d56Sopenharmony_ciThe import machinery calls the :meth:`importlib.abc.Loader.exec_module`
4137db96d56Sopenharmony_cimethod with a single argument, the module object to execute.  Any value
4147db96d56Sopenharmony_cireturned from :meth:`~importlib.abc.Loader.exec_module` is ignored.
4157db96d56Sopenharmony_ci
4167db96d56Sopenharmony_ciLoaders must satisfy the following requirements:
4177db96d56Sopenharmony_ci
4187db96d56Sopenharmony_ci * If the module is a Python module (as opposed to a built-in module or a
4197db96d56Sopenharmony_ci   dynamically loaded extension), the loader should execute the module's code
4207db96d56Sopenharmony_ci   in the module's global name space (``module.__dict__``).
4217db96d56Sopenharmony_ci
4227db96d56Sopenharmony_ci * If the loader cannot execute the module, it should raise an
4237db96d56Sopenharmony_ci   :exc:`ImportError`, although any other exception raised during
4247db96d56Sopenharmony_ci   :meth:`~importlib.abc.Loader.exec_module` will be propagated.
4257db96d56Sopenharmony_ci
4267db96d56Sopenharmony_ciIn many cases, the finder and loader can be the same object; in such cases the
4277db96d56Sopenharmony_ci:meth:`~importlib.abc.MetaPathFinder.find_spec` method would just return a
4287db96d56Sopenharmony_cispec with the loader set to ``self``.
4297db96d56Sopenharmony_ci
4307db96d56Sopenharmony_ciModule loaders may opt in to creating the module object during loading
4317db96d56Sopenharmony_ciby implementing a :meth:`~importlib.abc.Loader.create_module` method.
4327db96d56Sopenharmony_ciIt takes one argument, the module spec, and returns the new module object
4337db96d56Sopenharmony_cito use during loading.  ``create_module()`` does not need to set any attributes
4347db96d56Sopenharmony_cion the module object.  If the method returns ``None``, the
4357db96d56Sopenharmony_ciimport machinery will create the new module itself.
4367db96d56Sopenharmony_ci
4377db96d56Sopenharmony_ci.. versionadded:: 3.4
4387db96d56Sopenharmony_ci   The :meth:`~importlib.abc.Loader.create_module` method of loaders.
4397db96d56Sopenharmony_ci
4407db96d56Sopenharmony_ci.. versionchanged:: 3.4
4417db96d56Sopenharmony_ci   The :meth:`~importlib.abc.Loader.load_module` method was replaced by
4427db96d56Sopenharmony_ci   :meth:`~importlib.abc.Loader.exec_module` and the import
4437db96d56Sopenharmony_ci   machinery assumed all the boilerplate responsibilities of loading.
4447db96d56Sopenharmony_ci
4457db96d56Sopenharmony_ci   For compatibility with existing loaders, the import machinery will use
4467db96d56Sopenharmony_ci   the ``load_module()`` method of loaders if it exists and the loader does
4477db96d56Sopenharmony_ci   not also implement ``exec_module()``.  However, ``load_module()`` has been
4487db96d56Sopenharmony_ci   deprecated and loaders should implement ``exec_module()`` instead.
4497db96d56Sopenharmony_ci
4507db96d56Sopenharmony_ci   The ``load_module()`` method must implement all the boilerplate loading
4517db96d56Sopenharmony_ci   functionality described above in addition to executing the module.  All
4527db96d56Sopenharmony_ci   the same constraints apply, with some additional clarification:
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci    * If there is an existing module object with the given name in
4557db96d56Sopenharmony_ci      :data:`sys.modules`, the loader must use that existing module.
4567db96d56Sopenharmony_ci      (Otherwise, :func:`importlib.reload` will not work correctly.)  If the
4577db96d56Sopenharmony_ci      named module does not exist in :data:`sys.modules`, the loader
4587db96d56Sopenharmony_ci      must create a new module object and add it to :data:`sys.modules`.
4597db96d56Sopenharmony_ci
4607db96d56Sopenharmony_ci    * The module *must* exist in :data:`sys.modules` before the loader
4617db96d56Sopenharmony_ci      executes the module code, to prevent unbounded recursion or multiple
4627db96d56Sopenharmony_ci      loading.
4637db96d56Sopenharmony_ci
4647db96d56Sopenharmony_ci    * If loading fails, the loader must remove any modules it has inserted
4657db96d56Sopenharmony_ci      into :data:`sys.modules`, but it must remove **only** the failing
4667db96d56Sopenharmony_ci      module(s), and only if the loader itself has loaded the module(s)
4677db96d56Sopenharmony_ci      explicitly.
4687db96d56Sopenharmony_ci
4697db96d56Sopenharmony_ci.. versionchanged:: 3.5
4707db96d56Sopenharmony_ci   A :exc:`DeprecationWarning` is raised when ``exec_module()`` is defined but
4717db96d56Sopenharmony_ci   ``create_module()`` is not.
4727db96d56Sopenharmony_ci
4737db96d56Sopenharmony_ci.. versionchanged:: 3.6
4747db96d56Sopenharmony_ci   An :exc:`ImportError` is raised when ``exec_module()`` is defined but
4757db96d56Sopenharmony_ci   ``create_module()`` is not.
4767db96d56Sopenharmony_ci
4777db96d56Sopenharmony_ci.. versionchanged:: 3.10
4787db96d56Sopenharmony_ci   Use of ``load_module()`` will raise :exc:`ImportWarning`.
4797db96d56Sopenharmony_ci
4807db96d56Sopenharmony_ciSubmodules
4817db96d56Sopenharmony_ci----------
4827db96d56Sopenharmony_ci
4837db96d56Sopenharmony_ciWhen a submodule is loaded using any mechanism (e.g. ``importlib`` APIs, the
4847db96d56Sopenharmony_ci``import`` or ``import-from`` statements, or built-in ``__import__()``) a
4857db96d56Sopenharmony_cibinding is placed in the parent module's namespace to the submodule object.
4867db96d56Sopenharmony_ciFor example, if package ``spam`` has a submodule ``foo``, after importing
4877db96d56Sopenharmony_ci``spam.foo``, ``spam`` will have an attribute ``foo`` which is bound to the
4887db96d56Sopenharmony_cisubmodule.  Let's say you have the following directory structure::
4897db96d56Sopenharmony_ci
4907db96d56Sopenharmony_ci    spam/
4917db96d56Sopenharmony_ci        __init__.py
4927db96d56Sopenharmony_ci        foo.py
4937db96d56Sopenharmony_ci
4947db96d56Sopenharmony_ciand ``spam/__init__.py`` has the following line in it::
4957db96d56Sopenharmony_ci
4967db96d56Sopenharmony_ci    from .foo import Foo
4977db96d56Sopenharmony_ci
4987db96d56Sopenharmony_cithen executing the following puts name bindings for ``foo`` and ``Foo`` in the
4997db96d56Sopenharmony_ci``spam`` module::
5007db96d56Sopenharmony_ci
5017db96d56Sopenharmony_ci    >>> import spam
5027db96d56Sopenharmony_ci    >>> spam.foo
5037db96d56Sopenharmony_ci    <module 'spam.foo' from '/tmp/imports/spam/foo.py'>
5047db96d56Sopenharmony_ci    >>> spam.Foo
5057db96d56Sopenharmony_ci    <class 'spam.foo.Foo'>
5067db96d56Sopenharmony_ci
5077db96d56Sopenharmony_ciGiven Python's familiar name binding rules this might seem surprising, but
5087db96d56Sopenharmony_ciit's actually a fundamental feature of the import system.  The invariant
5097db96d56Sopenharmony_ciholding is that if you have ``sys.modules['spam']`` and
5107db96d56Sopenharmony_ci``sys.modules['spam.foo']`` (as you would after the above import), the latter
5117db96d56Sopenharmony_cimust appear as the ``foo`` attribute of the former.
5127db96d56Sopenharmony_ci
5137db96d56Sopenharmony_ciModule spec
5147db96d56Sopenharmony_ci-----------
5157db96d56Sopenharmony_ci
5167db96d56Sopenharmony_ciThe import machinery uses a variety of information about each module
5177db96d56Sopenharmony_ciduring import, especially before loading.  Most of the information is
5187db96d56Sopenharmony_cicommon to all modules.  The purpose of a module's spec is to encapsulate
5197db96d56Sopenharmony_cithis import-related information on a per-module basis.
5207db96d56Sopenharmony_ci
5217db96d56Sopenharmony_ciUsing a spec during import allows state to be transferred between import
5227db96d56Sopenharmony_cisystem components, e.g. between the finder that creates the module spec
5237db96d56Sopenharmony_ciand the loader that executes it.  Most importantly, it allows the
5247db96d56Sopenharmony_ciimport machinery to perform the boilerplate operations of loading,
5257db96d56Sopenharmony_ciwhereas without a module spec the loader had that responsibility.
5267db96d56Sopenharmony_ci
5277db96d56Sopenharmony_ciThe module's spec is exposed as the ``__spec__`` attribute on a module object.
5287db96d56Sopenharmony_ciSee :class:`~importlib.machinery.ModuleSpec` for details on the contents of
5297db96d56Sopenharmony_cithe module spec.
5307db96d56Sopenharmony_ci
5317db96d56Sopenharmony_ci.. versionadded:: 3.4
5327db96d56Sopenharmony_ci
5337db96d56Sopenharmony_ci.. _import-mod-attrs:
5347db96d56Sopenharmony_ci
5357db96d56Sopenharmony_ciImport-related module attributes
5367db96d56Sopenharmony_ci--------------------------------
5377db96d56Sopenharmony_ci
5387db96d56Sopenharmony_ciThe import machinery fills in these attributes on each module object
5397db96d56Sopenharmony_ciduring loading, based on the module's spec, before the loader executes
5407db96d56Sopenharmony_cithe module.
5417db96d56Sopenharmony_ci
5427db96d56Sopenharmony_ci.. attribute:: __name__
5437db96d56Sopenharmony_ci
5447db96d56Sopenharmony_ci   The ``__name__`` attribute must be set to the fully qualified name of
5457db96d56Sopenharmony_ci   the module.  This name is used to uniquely identify the module in
5467db96d56Sopenharmony_ci   the import system.
5477db96d56Sopenharmony_ci
5487db96d56Sopenharmony_ci.. attribute:: __loader__
5497db96d56Sopenharmony_ci
5507db96d56Sopenharmony_ci   The ``__loader__`` attribute must be set to the loader object that
5517db96d56Sopenharmony_ci   the import machinery used when loading the module.  This is mostly
5527db96d56Sopenharmony_ci   for introspection, but can be used for additional loader-specific
5537db96d56Sopenharmony_ci   functionality, for example getting data associated with a loader.
5547db96d56Sopenharmony_ci
5557db96d56Sopenharmony_ci.. attribute:: __package__
5567db96d56Sopenharmony_ci
5577db96d56Sopenharmony_ci   The module's ``__package__`` attribute must be set.  Its value must
5587db96d56Sopenharmony_ci   be a string, but it can be the same value as its ``__name__``.  When
5597db96d56Sopenharmony_ci   the module is a package, its ``__package__`` value should be set to
5607db96d56Sopenharmony_ci   its ``__name__``.  When the module is not a package, ``__package__``
5617db96d56Sopenharmony_ci   should be set to the empty string for top-level modules, or for
5627db96d56Sopenharmony_ci   submodules, to the parent package's name.  See :pep:`366` for further
5637db96d56Sopenharmony_ci   details.
5647db96d56Sopenharmony_ci
5657db96d56Sopenharmony_ci   This attribute is used instead of ``__name__`` to calculate explicit
5667db96d56Sopenharmony_ci   relative imports for main modules, as defined in :pep:`366`. It is
5677db96d56Sopenharmony_ci   expected to have the same value as ``__spec__.parent``.
5687db96d56Sopenharmony_ci
5697db96d56Sopenharmony_ci   .. versionchanged:: 3.6
5707db96d56Sopenharmony_ci      The value of ``__package__`` is expected to be the same as
5717db96d56Sopenharmony_ci      ``__spec__.parent``.
5727db96d56Sopenharmony_ci
5737db96d56Sopenharmony_ci.. attribute:: __spec__
5747db96d56Sopenharmony_ci
5757db96d56Sopenharmony_ci   The ``__spec__`` attribute must be set to the module spec that was
5767db96d56Sopenharmony_ci   used when importing the module. Setting ``__spec__``
5777db96d56Sopenharmony_ci   appropriately applies equally to :ref:`modules initialized during
5787db96d56Sopenharmony_ci   interpreter startup <programs>`.  The one exception is ``__main__``,
5797db96d56Sopenharmony_ci   where ``__spec__`` is :ref:`set to None in some cases <main_spec>`.
5807db96d56Sopenharmony_ci
5817db96d56Sopenharmony_ci   When ``__package__`` is not defined, ``__spec__.parent`` is used as
5827db96d56Sopenharmony_ci   a fallback.
5837db96d56Sopenharmony_ci
5847db96d56Sopenharmony_ci   .. versionadded:: 3.4
5857db96d56Sopenharmony_ci
5867db96d56Sopenharmony_ci   .. versionchanged:: 3.6
5877db96d56Sopenharmony_ci      ``__spec__.parent`` is used as a fallback when ``__package__`` is
5887db96d56Sopenharmony_ci      not defined.
5897db96d56Sopenharmony_ci
5907db96d56Sopenharmony_ci.. attribute:: __path__
5917db96d56Sopenharmony_ci
5927db96d56Sopenharmony_ci   If the module is a package (either regular or namespace), the module
5937db96d56Sopenharmony_ci   object's ``__path__`` attribute must be set.  The value must be
5947db96d56Sopenharmony_ci   iterable, but may be empty if ``__path__`` has no further significance.
5957db96d56Sopenharmony_ci   If ``__path__`` is not empty, it must produce strings when iterated
5967db96d56Sopenharmony_ci   over. More details on the semantics of ``__path__`` are given
5977db96d56Sopenharmony_ci   :ref:`below <package-path-rules>`.
5987db96d56Sopenharmony_ci
5997db96d56Sopenharmony_ci   Non-package modules should not have a ``__path__`` attribute.
6007db96d56Sopenharmony_ci
6017db96d56Sopenharmony_ci.. attribute:: __file__
6027db96d56Sopenharmony_ci.. attribute:: __cached__
6037db96d56Sopenharmony_ci
6047db96d56Sopenharmony_ci   ``__file__`` is optional (if set, value must be a string). It indicates
6057db96d56Sopenharmony_ci   the pathname of the file from which the module was loaded (if
6067db96d56Sopenharmony_ci   loaded from a file), or the pathname of the shared library file
6077db96d56Sopenharmony_ci   for extension modules loaded dynamically from a shared library.
6087db96d56Sopenharmony_ci   It might be missing for certain types of modules, such as C
6097db96d56Sopenharmony_ci   modules that are statically linked into the interpreter, and the
6107db96d56Sopenharmony_ci   import system may opt to leave it unset if it has no semantic
6117db96d56Sopenharmony_ci   meaning (e.g. a module loaded from a database).
6127db96d56Sopenharmony_ci
6137db96d56Sopenharmony_ci   If ``__file__`` is set then the ``__cached__`` attribute might also
6147db96d56Sopenharmony_ci   be set,  which is the path to any compiled version of
6157db96d56Sopenharmony_ci   the code (e.g. byte-compiled file). The file does not need to exist
6167db96d56Sopenharmony_ci   to set this attribute; the path can simply point to where the
6177db96d56Sopenharmony_ci   compiled file would exist (see :pep:`3147`).
6187db96d56Sopenharmony_ci
6197db96d56Sopenharmony_ci   Note that ``__cached__`` may be set even if ``__file__`` is not
6207db96d56Sopenharmony_ci   set.  However, that scenario is quite atypical.  Ultimately, the
6217db96d56Sopenharmony_ci   loader is what makes use of the module spec provided by the finder
6227db96d56Sopenharmony_ci   (from which ``__file__`` and ``__cached__`` are derived).  So
6237db96d56Sopenharmony_ci   if a loader can load from a cached module but otherwise does not load
6247db96d56Sopenharmony_ci   from a file, that atypical scenario may be appropriate.
6257db96d56Sopenharmony_ci
6267db96d56Sopenharmony_ci.. _package-path-rules:
6277db96d56Sopenharmony_ci
6287db96d56Sopenharmony_cimodule.__path__
6297db96d56Sopenharmony_ci---------------
6307db96d56Sopenharmony_ci
6317db96d56Sopenharmony_ciBy definition, if a module has a ``__path__`` attribute, it is a package.
6327db96d56Sopenharmony_ci
6337db96d56Sopenharmony_ciA package's ``__path__`` attribute is used during imports of its subpackages.
6347db96d56Sopenharmony_ciWithin the import machinery, it functions much the same as :data:`sys.path`,
6357db96d56Sopenharmony_cii.e. providing a list of locations to search for modules during import.
6367db96d56Sopenharmony_ciHowever, ``__path__`` is typically much more constrained than
6377db96d56Sopenharmony_ci:data:`sys.path`.
6387db96d56Sopenharmony_ci
6397db96d56Sopenharmony_ci``__path__`` must be an iterable of strings, but it may be empty.
6407db96d56Sopenharmony_ciThe same rules used for :data:`sys.path` also apply to a package's
6417db96d56Sopenharmony_ci``__path__``, and :data:`sys.path_hooks` (described below) are
6427db96d56Sopenharmony_ciconsulted when traversing a package's ``__path__``.
6437db96d56Sopenharmony_ci
6447db96d56Sopenharmony_ciA package's ``__init__.py`` file may set or alter the package's ``__path__``
6457db96d56Sopenharmony_ciattribute, and this was typically the way namespace packages were implemented
6467db96d56Sopenharmony_ciprior to :pep:`420`.  With the adoption of :pep:`420`, namespace packages no
6477db96d56Sopenharmony_cilonger need to supply ``__init__.py`` files containing only ``__path__``
6487db96d56Sopenharmony_cimanipulation code; the import machinery automatically sets ``__path__``
6497db96d56Sopenharmony_cicorrectly for the namespace package.
6507db96d56Sopenharmony_ci
6517db96d56Sopenharmony_ciModule reprs
6527db96d56Sopenharmony_ci------------
6537db96d56Sopenharmony_ci
6547db96d56Sopenharmony_ciBy default, all modules have a usable repr, however depending on the
6557db96d56Sopenharmony_ciattributes set above, and in the module's spec, you can more explicitly
6567db96d56Sopenharmony_cicontrol the repr of module objects.
6577db96d56Sopenharmony_ci
6587db96d56Sopenharmony_ciIf the module has a spec (``__spec__``), the import machinery will try
6597db96d56Sopenharmony_cito generate a repr from it.  If that fails or there is no spec, the import
6607db96d56Sopenharmony_cisystem will craft a default repr using whatever information is available
6617db96d56Sopenharmony_cion the module.  It will try to use the ``module.__name__``,
6627db96d56Sopenharmony_ci``module.__file__``, and ``module.__loader__`` as input into the repr,
6637db96d56Sopenharmony_ciwith defaults for whatever information is missing.
6647db96d56Sopenharmony_ci
6657db96d56Sopenharmony_ciHere are the exact rules used:
6667db96d56Sopenharmony_ci
6677db96d56Sopenharmony_ci * If the module has a ``__spec__`` attribute, the information in the spec
6687db96d56Sopenharmony_ci   is used to generate the repr.  The "name", "loader", "origin", and
6697db96d56Sopenharmony_ci   "has_location" attributes are consulted.
6707db96d56Sopenharmony_ci
6717db96d56Sopenharmony_ci * If the module has a ``__file__`` attribute, this is used as part of the
6727db96d56Sopenharmony_ci   module's repr.
6737db96d56Sopenharmony_ci
6747db96d56Sopenharmony_ci * If the module has no ``__file__`` but does have a ``__loader__`` that is not
6757db96d56Sopenharmony_ci   ``None``, then the loader's repr is used as part of the module's repr.
6767db96d56Sopenharmony_ci
6777db96d56Sopenharmony_ci * Otherwise, just use the module's ``__name__`` in the repr.
6787db96d56Sopenharmony_ci
6797db96d56Sopenharmony_ci.. versionchanged:: 3.4
6807db96d56Sopenharmony_ci   Use of :meth:`loader.module_repr() <importlib.abc.Loader.module_repr>`
6817db96d56Sopenharmony_ci   has been deprecated and the module spec is now used by the import
6827db96d56Sopenharmony_ci   machinery to generate a module repr.
6837db96d56Sopenharmony_ci
6847db96d56Sopenharmony_ci   For backward compatibility with Python 3.3, the module repr will be
6857db96d56Sopenharmony_ci   generated by calling the loader's
6867db96d56Sopenharmony_ci   :meth:`~importlib.abc.Loader.module_repr` method, if defined, before
6877db96d56Sopenharmony_ci   trying either approach described above.  However, the method is deprecated.
6887db96d56Sopenharmony_ci
6897db96d56Sopenharmony_ci.. versionchanged:: 3.10
6907db96d56Sopenharmony_ci
6917db96d56Sopenharmony_ci   Calling :meth:`~importlib.abc.Loader.module_repr` now occurs after trying to
6927db96d56Sopenharmony_ci   use a module's ``__spec__`` attribute but before falling back on
6937db96d56Sopenharmony_ci   ``__file__``. Use of :meth:`~importlib.abc.Loader.module_repr` is slated to
6947db96d56Sopenharmony_ci   stop in Python 3.12.
6957db96d56Sopenharmony_ci
6967db96d56Sopenharmony_ci.. _pyc-invalidation:
6977db96d56Sopenharmony_ci
6987db96d56Sopenharmony_ciCached bytecode invalidation
6997db96d56Sopenharmony_ci----------------------------
7007db96d56Sopenharmony_ci
7017db96d56Sopenharmony_ciBefore Python loads cached bytecode from a ``.pyc`` file, it checks whether the
7027db96d56Sopenharmony_cicache is up-to-date with the source ``.py`` file. By default, Python does this
7037db96d56Sopenharmony_ciby storing the source's last-modified timestamp and size in the cache file when
7047db96d56Sopenharmony_ciwriting it. At runtime, the import system then validates the cache file by
7057db96d56Sopenharmony_cichecking the stored metadata in the cache file against the source's
7067db96d56Sopenharmony_cimetadata.
7077db96d56Sopenharmony_ci
7087db96d56Sopenharmony_ciPython also supports "hash-based" cache files, which store a hash of the source
7097db96d56Sopenharmony_cifile's contents rather than its metadata. There are two variants of hash-based
7107db96d56Sopenharmony_ci``.pyc`` files: checked and unchecked. For checked hash-based ``.pyc`` files,
7117db96d56Sopenharmony_ciPython validates the cache file by hashing the source file and comparing the
7127db96d56Sopenharmony_ciresulting hash with the hash in the cache file. If a checked hash-based cache
7137db96d56Sopenharmony_cifile is found to be invalid, Python regenerates it and writes a new checked
7147db96d56Sopenharmony_cihash-based cache file. For unchecked hash-based ``.pyc`` files, Python simply
7157db96d56Sopenharmony_ciassumes the cache file is valid if it exists. Hash-based ``.pyc`` files
7167db96d56Sopenharmony_civalidation behavior may be overridden with the :option:`--check-hash-based-pycs`
7177db96d56Sopenharmony_ciflag.
7187db96d56Sopenharmony_ci
7197db96d56Sopenharmony_ci.. versionchanged:: 3.7
7207db96d56Sopenharmony_ci   Added hash-based ``.pyc`` files. Previously, Python only supported
7217db96d56Sopenharmony_ci   timestamp-based invalidation of bytecode caches.
7227db96d56Sopenharmony_ci
7237db96d56Sopenharmony_ci
7247db96d56Sopenharmony_ciThe Path Based Finder
7257db96d56Sopenharmony_ci=====================
7267db96d56Sopenharmony_ci
7277db96d56Sopenharmony_ci.. index::
7287db96d56Sopenharmony_ci    single: path based finder
7297db96d56Sopenharmony_ci
7307db96d56Sopenharmony_ciAs mentioned previously, Python comes with several default meta path finders.
7317db96d56Sopenharmony_ciOne of these, called the :term:`path based finder`
7327db96d56Sopenharmony_ci(:class:`~importlib.machinery.PathFinder`), searches an :term:`import path`,
7337db96d56Sopenharmony_ciwhich contains a list of :term:`path entries <path entry>`.  Each path
7347db96d56Sopenharmony_cientry names a location to search for modules.
7357db96d56Sopenharmony_ci
7367db96d56Sopenharmony_ciThe path based finder itself doesn't know how to import anything. Instead, it
7377db96d56Sopenharmony_citraverses the individual path entries, associating each of them with a
7387db96d56Sopenharmony_cipath entry finder that knows how to handle that particular kind of path.
7397db96d56Sopenharmony_ci
7407db96d56Sopenharmony_ciThe default set of path entry finders implement all the semantics for finding
7417db96d56Sopenharmony_cimodules on the file system, handling special file types such as Python source
7427db96d56Sopenharmony_cicode (``.py`` files), Python byte code (``.pyc`` files) and
7437db96d56Sopenharmony_cishared libraries (e.g. ``.so`` files). When supported by the :mod:`zipimport`
7447db96d56Sopenharmony_cimodule in the standard library, the default path entry finders also handle
7457db96d56Sopenharmony_ciloading all of these file types (other than shared libraries) from zipfiles.
7467db96d56Sopenharmony_ci
7477db96d56Sopenharmony_ciPath entries need not be limited to file system locations.  They can refer to
7487db96d56Sopenharmony_ciURLs, database queries, or any other location that can be specified as a
7497db96d56Sopenharmony_cistring.
7507db96d56Sopenharmony_ci
7517db96d56Sopenharmony_ciThe path based finder provides additional hooks and protocols so that you
7527db96d56Sopenharmony_cican extend and customize the types of searchable path entries.  For example,
7537db96d56Sopenharmony_ciif you wanted to support path entries as network URLs, you could write a hook
7547db96d56Sopenharmony_cithat implements HTTP semantics to find modules on the web.  This hook (a
7557db96d56Sopenharmony_cicallable) would return a :term:`path entry finder` supporting the protocol
7567db96d56Sopenharmony_cidescribed below, which was then used to get a loader for the module from the
7577db96d56Sopenharmony_ciweb.
7587db96d56Sopenharmony_ci
7597db96d56Sopenharmony_ciA word of warning: this section and the previous both use the term *finder*,
7607db96d56Sopenharmony_cidistinguishing between them by using the terms :term:`meta path finder` and
7617db96d56Sopenharmony_ci:term:`path entry finder`.  These two types of finders are very similar,
7627db96d56Sopenharmony_cisupport similar protocols, and function in similar ways during the import
7637db96d56Sopenharmony_ciprocess, but it's important to keep in mind that they are subtly different.
7647db96d56Sopenharmony_ciIn particular, meta path finders operate at the beginning of the import
7657db96d56Sopenharmony_ciprocess, as keyed off the :data:`sys.meta_path` traversal.
7667db96d56Sopenharmony_ci
7677db96d56Sopenharmony_ciBy contrast, path entry finders are in a sense an implementation detail
7687db96d56Sopenharmony_ciof the path based finder, and in fact, if the path based finder were to be
7697db96d56Sopenharmony_ciremoved from :data:`sys.meta_path`, none of the path entry finder semantics
7707db96d56Sopenharmony_ciwould be invoked.
7717db96d56Sopenharmony_ci
7727db96d56Sopenharmony_ci
7737db96d56Sopenharmony_ciPath entry finders
7747db96d56Sopenharmony_ci------------------
7757db96d56Sopenharmony_ci
7767db96d56Sopenharmony_ci.. index::
7777db96d56Sopenharmony_ci    single: sys.path
7787db96d56Sopenharmony_ci    single: sys.path_hooks
7797db96d56Sopenharmony_ci    single: sys.path_importer_cache
7807db96d56Sopenharmony_ci    single: PYTHONPATH
7817db96d56Sopenharmony_ci
7827db96d56Sopenharmony_ciThe :term:`path based finder` is responsible for finding and loading
7837db96d56Sopenharmony_ciPython modules and packages whose location is specified with a string
7847db96d56Sopenharmony_ci:term:`path entry`.  Most path entries name locations in the file system,
7857db96d56Sopenharmony_cibut they need not be limited to this.
7867db96d56Sopenharmony_ci
7877db96d56Sopenharmony_ciAs a meta path finder, the :term:`path based finder` implements the
7887db96d56Sopenharmony_ci:meth:`~importlib.abc.MetaPathFinder.find_spec` protocol previously
7897db96d56Sopenharmony_cidescribed, however it exposes additional hooks that can be used to
7907db96d56Sopenharmony_cicustomize how modules are found and loaded from the :term:`import path`.
7917db96d56Sopenharmony_ci
7927db96d56Sopenharmony_ciThree variables are used by the :term:`path based finder`, :data:`sys.path`,
7937db96d56Sopenharmony_ci:data:`sys.path_hooks` and :data:`sys.path_importer_cache`.  The ``__path__``
7947db96d56Sopenharmony_ciattributes on package objects are also used.  These provide additional ways
7957db96d56Sopenharmony_cithat the import machinery can be customized.
7967db96d56Sopenharmony_ci
7977db96d56Sopenharmony_ci:data:`sys.path` contains a list of strings providing search locations for
7987db96d56Sopenharmony_cimodules and packages.  It is initialized from the :data:`PYTHONPATH`
7997db96d56Sopenharmony_cienvironment variable and various other installation- and
8007db96d56Sopenharmony_ciimplementation-specific defaults.  Entries in :data:`sys.path` can name
8017db96d56Sopenharmony_cidirectories on the file system, zip files, and potentially other "locations"
8027db96d56Sopenharmony_ci(see the :mod:`site` module) that should be searched for modules, such as
8037db96d56Sopenharmony_ciURLs, or database queries.  Only strings should be present on
8047db96d56Sopenharmony_ci:data:`sys.path`; all other data types are ignored.
8057db96d56Sopenharmony_ci
8067db96d56Sopenharmony_ciThe :term:`path based finder` is a :term:`meta path finder`, so the import
8077db96d56Sopenharmony_cimachinery begins the :term:`import path` search by calling the path
8087db96d56Sopenharmony_cibased finder's :meth:`~importlib.machinery.PathFinder.find_spec` method as
8097db96d56Sopenharmony_cidescribed previously.  When the ``path`` argument to
8107db96d56Sopenharmony_ci:meth:`~importlib.machinery.PathFinder.find_spec` is given, it will be a
8117db96d56Sopenharmony_cilist of string paths to traverse - typically a package's ``__path__``
8127db96d56Sopenharmony_ciattribute for an import within that package.  If the ``path`` argument is
8137db96d56Sopenharmony_ci``None``, this indicates a top level import and :data:`sys.path` is used.
8147db96d56Sopenharmony_ci
8157db96d56Sopenharmony_ciThe path based finder iterates over every entry in the search path, and
8167db96d56Sopenharmony_cifor each of these, looks for an appropriate :term:`path entry finder`
8177db96d56Sopenharmony_ci(:class:`~importlib.abc.PathEntryFinder`) for the
8187db96d56Sopenharmony_cipath entry.  Because this can be an expensive operation (e.g. there may be
8197db96d56Sopenharmony_ci``stat()`` call overheads for this search), the path based finder maintains
8207db96d56Sopenharmony_cia cache mapping path entries to path entry finders.  This cache is maintained
8217db96d56Sopenharmony_ciin :data:`sys.path_importer_cache` (despite the name, this cache actually
8227db96d56Sopenharmony_cistores finder objects rather than being limited to :term:`importer` objects).
8237db96d56Sopenharmony_ciIn this way, the expensive search for a particular :term:`path entry`
8247db96d56Sopenharmony_cilocation's :term:`path entry finder` need only be done once.  User code is
8257db96d56Sopenharmony_cifree to remove cache entries from :data:`sys.path_importer_cache` forcing
8267db96d56Sopenharmony_cithe path based finder to perform the path entry search again [#fnpic]_.
8277db96d56Sopenharmony_ci
8287db96d56Sopenharmony_ciIf the path entry is not present in the cache, the path based finder iterates
8297db96d56Sopenharmony_ciover every callable in :data:`sys.path_hooks`.  Each of the :term:`path entry
8307db96d56Sopenharmony_cihooks <path entry hook>` in this list is called with a single argument, the
8317db96d56Sopenharmony_cipath entry to be searched.  This callable may either return a :term:`path
8327db96d56Sopenharmony_cientry finder` that can handle the path entry, or it may raise
8337db96d56Sopenharmony_ci:exc:`ImportError`.  An :exc:`ImportError` is used by the path based finder to
8347db96d56Sopenharmony_cisignal that the hook cannot find a :term:`path entry finder`
8357db96d56Sopenharmony_cifor that :term:`path entry`.  The
8367db96d56Sopenharmony_ciexception is ignored and :term:`import path` iteration continues.  The hook
8377db96d56Sopenharmony_cishould expect either a string or bytes object; the encoding of bytes objects
8387db96d56Sopenharmony_ciis up to the hook (e.g. it may be a file system encoding, UTF-8, or something
8397db96d56Sopenharmony_cielse), and if the hook cannot decode the argument, it should raise
8407db96d56Sopenharmony_ci:exc:`ImportError`.
8417db96d56Sopenharmony_ci
8427db96d56Sopenharmony_ciIf :data:`sys.path_hooks` iteration ends with no :term:`path entry finder`
8437db96d56Sopenharmony_cibeing returned, then the path based finder's
8447db96d56Sopenharmony_ci:meth:`~importlib.machinery.PathFinder.find_spec` method will store ``None``
8457db96d56Sopenharmony_ciin :data:`sys.path_importer_cache` (to indicate that there is no finder for
8467db96d56Sopenharmony_cithis path entry) and return ``None``, indicating that this
8477db96d56Sopenharmony_ci:term:`meta path finder` could not find the module.
8487db96d56Sopenharmony_ci
8497db96d56Sopenharmony_ciIf a :term:`path entry finder` *is* returned by one of the :term:`path entry
8507db96d56Sopenharmony_cihook` callables on :data:`sys.path_hooks`, then the following protocol is used
8517db96d56Sopenharmony_cito ask the finder for a module spec, which is then used when loading the
8527db96d56Sopenharmony_cimodule.
8537db96d56Sopenharmony_ci
8547db96d56Sopenharmony_ciThe current working directory -- denoted by an empty string -- is handled
8557db96d56Sopenharmony_cislightly differently from other entries on :data:`sys.path`. First, if the
8567db96d56Sopenharmony_cicurrent working directory is found to not exist, no value is stored in
8577db96d56Sopenharmony_ci:data:`sys.path_importer_cache`. Second, the value for the current working
8587db96d56Sopenharmony_cidirectory is looked up fresh for each module lookup. Third, the path used for
8597db96d56Sopenharmony_ci:data:`sys.path_importer_cache` and returned by
8607db96d56Sopenharmony_ci:meth:`importlib.machinery.PathFinder.find_spec` will be the actual current
8617db96d56Sopenharmony_ciworking directory and not the empty string.
8627db96d56Sopenharmony_ci
8637db96d56Sopenharmony_ciPath entry finder protocol
8647db96d56Sopenharmony_ci--------------------------
8657db96d56Sopenharmony_ci
8667db96d56Sopenharmony_ciIn order to support imports of modules and initialized packages and also to
8677db96d56Sopenharmony_cicontribute portions to namespace packages, path entry finders must implement
8687db96d56Sopenharmony_cithe :meth:`~importlib.abc.PathEntryFinder.find_spec` method.
8697db96d56Sopenharmony_ci
8707db96d56Sopenharmony_ci:meth:`~importlib.abc.PathEntryFinder.find_spec` takes two arguments: the
8717db96d56Sopenharmony_cifully qualified name of the module being imported, and the (optional) target
8727db96d56Sopenharmony_cimodule.  ``find_spec()`` returns a fully populated spec for the module.
8737db96d56Sopenharmony_ciThis spec will always have "loader" set (with one exception).
8747db96d56Sopenharmony_ci
8757db96d56Sopenharmony_ciTo indicate to the import machinery that the spec represents a namespace
8767db96d56Sopenharmony_ci:term:`portion`, the path entry finder sets "submodule_search_locations" to
8777db96d56Sopenharmony_cia list containing the portion.
8787db96d56Sopenharmony_ci
8797db96d56Sopenharmony_ci.. versionchanged:: 3.4
8807db96d56Sopenharmony_ci   :meth:`~importlib.abc.PathEntryFinder.find_spec` replaced
8817db96d56Sopenharmony_ci   :meth:`~importlib.abc.PathEntryFinder.find_loader` and
8827db96d56Sopenharmony_ci   :meth:`~importlib.abc.PathEntryFinder.find_module`, both of which
8837db96d56Sopenharmony_ci   are now deprecated, but will be used if ``find_spec()`` is not defined.
8847db96d56Sopenharmony_ci
8857db96d56Sopenharmony_ci   Older path entry finders may implement one of these two deprecated methods
8867db96d56Sopenharmony_ci   instead of ``find_spec()``.  The methods are still respected for the
8877db96d56Sopenharmony_ci   sake of backward compatibility.  However, if ``find_spec()`` is
8887db96d56Sopenharmony_ci   implemented on the path entry finder, the legacy methods are ignored.
8897db96d56Sopenharmony_ci
8907db96d56Sopenharmony_ci   :meth:`~importlib.abc.PathEntryFinder.find_loader` takes one argument, the
8917db96d56Sopenharmony_ci   fully qualified name of the module being imported.  ``find_loader()``
8927db96d56Sopenharmony_ci   returns a 2-tuple where the first item is the loader and the second item
8937db96d56Sopenharmony_ci   is a namespace :term:`portion`.
8947db96d56Sopenharmony_ci
8957db96d56Sopenharmony_ci   For backwards compatibility with other implementations of the import
8967db96d56Sopenharmony_ci   protocol, many path entry finders also support the same,
8977db96d56Sopenharmony_ci   traditional ``find_module()`` method that meta path finders support.
8987db96d56Sopenharmony_ci   However path entry finder ``find_module()`` methods are never called
8997db96d56Sopenharmony_ci   with a ``path`` argument (they are expected to record the appropriate
9007db96d56Sopenharmony_ci   path information from the initial call to the path hook).
9017db96d56Sopenharmony_ci
9027db96d56Sopenharmony_ci   The ``find_module()`` method on path entry finders is deprecated,
9037db96d56Sopenharmony_ci   as it does not allow the path entry finder to contribute portions to
9047db96d56Sopenharmony_ci   namespace packages.  If both ``find_loader()`` and ``find_module()``
9057db96d56Sopenharmony_ci   exist on a path entry finder, the import system will always call
9067db96d56Sopenharmony_ci   ``find_loader()`` in preference to ``find_module()``.
9077db96d56Sopenharmony_ci
9087db96d56Sopenharmony_ci.. versionchanged:: 3.10
9097db96d56Sopenharmony_ci    Calls to :meth:`~importlib.abc.PathEntryFinder.find_module` and
9107db96d56Sopenharmony_ci    :meth:`~importlib.abc.PathEntryFinder.find_loader` by the import
9117db96d56Sopenharmony_ci    system will raise :exc:`ImportWarning`.
9127db96d56Sopenharmony_ci
9137db96d56Sopenharmony_ci
9147db96d56Sopenharmony_ciReplacing the standard import system
9157db96d56Sopenharmony_ci====================================
9167db96d56Sopenharmony_ci
9177db96d56Sopenharmony_ciThe most reliable mechanism for replacing the entire import system is to
9187db96d56Sopenharmony_cidelete the default contents of :data:`sys.meta_path`, replacing them
9197db96d56Sopenharmony_cientirely with a custom meta path hook.
9207db96d56Sopenharmony_ci
9217db96d56Sopenharmony_ciIf it is acceptable to only alter the behaviour of import statements
9227db96d56Sopenharmony_ciwithout affecting other APIs that access the import system, then replacing
9237db96d56Sopenharmony_cithe builtin :func:`__import__` function may be sufficient. This technique
9247db96d56Sopenharmony_cimay also be employed at the module level to only alter the behaviour of
9257db96d56Sopenharmony_ciimport statements within that module.
9267db96d56Sopenharmony_ci
9277db96d56Sopenharmony_ciTo selectively prevent the import of some modules from a hook early on the
9287db96d56Sopenharmony_cimeta path (rather than disabling the standard import system entirely),
9297db96d56Sopenharmony_ciit is sufficient to raise :exc:`ModuleNotFoundError` directly from
9307db96d56Sopenharmony_ci:meth:`~importlib.abc.MetaPathFinder.find_spec` instead of returning
9317db96d56Sopenharmony_ci``None``. The latter indicates that the meta path search should continue,
9327db96d56Sopenharmony_ciwhile raising an exception terminates it immediately.
9337db96d56Sopenharmony_ci
9347db96d56Sopenharmony_ci.. _relativeimports:
9357db96d56Sopenharmony_ci
9367db96d56Sopenharmony_ciPackage Relative Imports
9377db96d56Sopenharmony_ci========================
9387db96d56Sopenharmony_ci
9397db96d56Sopenharmony_ciRelative imports use leading dots. A single leading dot indicates a relative
9407db96d56Sopenharmony_ciimport, starting with the current package. Two or more leading dots indicate a
9417db96d56Sopenharmony_cirelative import to the parent(s) of the current package, one level per dot
9427db96d56Sopenharmony_ciafter the first. For example, given the following package layout::
9437db96d56Sopenharmony_ci
9447db96d56Sopenharmony_ci    package/
9457db96d56Sopenharmony_ci        __init__.py
9467db96d56Sopenharmony_ci        subpackage1/
9477db96d56Sopenharmony_ci            __init__.py
9487db96d56Sopenharmony_ci            moduleX.py
9497db96d56Sopenharmony_ci            moduleY.py
9507db96d56Sopenharmony_ci        subpackage2/
9517db96d56Sopenharmony_ci            __init__.py
9527db96d56Sopenharmony_ci            moduleZ.py
9537db96d56Sopenharmony_ci        moduleA.py
9547db96d56Sopenharmony_ci
9557db96d56Sopenharmony_ciIn either ``subpackage1/moduleX.py`` or ``subpackage1/__init__.py``,
9567db96d56Sopenharmony_cithe following are valid relative imports::
9577db96d56Sopenharmony_ci
9587db96d56Sopenharmony_ci    from .moduleY import spam
9597db96d56Sopenharmony_ci    from .moduleY import spam as ham
9607db96d56Sopenharmony_ci    from . import moduleY
9617db96d56Sopenharmony_ci    from ..subpackage1 import moduleY
9627db96d56Sopenharmony_ci    from ..subpackage2.moduleZ import eggs
9637db96d56Sopenharmony_ci    from ..moduleA import foo
9647db96d56Sopenharmony_ci
9657db96d56Sopenharmony_ciAbsolute imports may use either the ``import <>`` or ``from <> import <>``
9667db96d56Sopenharmony_cisyntax, but relative imports may only use the second form; the reason
9677db96d56Sopenharmony_cifor this is that::
9687db96d56Sopenharmony_ci
9697db96d56Sopenharmony_ci    import XXX.YYY.ZZZ
9707db96d56Sopenharmony_ci
9717db96d56Sopenharmony_cishould expose ``XXX.YYY.ZZZ`` as a usable expression, but .moduleY is
9727db96d56Sopenharmony_cinot a valid expression.
9737db96d56Sopenharmony_ci
9747db96d56Sopenharmony_ci
9757db96d56Sopenharmony_ci.. _import-dunder-main:
9767db96d56Sopenharmony_ci
9777db96d56Sopenharmony_ciSpecial considerations for __main__
9787db96d56Sopenharmony_ci===================================
9797db96d56Sopenharmony_ci
9807db96d56Sopenharmony_ciThe :mod:`__main__` module is a special case relative to Python's import
9817db96d56Sopenharmony_cisystem.  As noted :ref:`elsewhere <programs>`, the ``__main__`` module
9827db96d56Sopenharmony_ciis directly initialized at interpreter startup, much like :mod:`sys` and
9837db96d56Sopenharmony_ci:mod:`builtins`.  However, unlike those two, it doesn't strictly
9847db96d56Sopenharmony_ciqualify as a built-in module.  This is because the manner in which
9857db96d56Sopenharmony_ci``__main__`` is initialized depends on the flags and other options with
9867db96d56Sopenharmony_ciwhich the interpreter is invoked.
9877db96d56Sopenharmony_ci
9887db96d56Sopenharmony_ci.. _main_spec:
9897db96d56Sopenharmony_ci
9907db96d56Sopenharmony_ci__main__.__spec__
9917db96d56Sopenharmony_ci-----------------
9927db96d56Sopenharmony_ci
9937db96d56Sopenharmony_ciDepending on how :mod:`__main__` is initialized, ``__main__.__spec__``
9947db96d56Sopenharmony_cigets set appropriately or to ``None``.
9957db96d56Sopenharmony_ci
9967db96d56Sopenharmony_ciWhen Python is started with the :option:`-m` option, ``__spec__`` is set
9977db96d56Sopenharmony_cito the module spec of the corresponding module or package. ``__spec__`` is
9987db96d56Sopenharmony_cialso populated when the ``__main__`` module is loaded as part of executing a
9997db96d56Sopenharmony_cidirectory, zipfile or other :data:`sys.path` entry.
10007db96d56Sopenharmony_ci
10017db96d56Sopenharmony_ciIn :ref:`the remaining cases <using-on-interface-options>`
10027db96d56Sopenharmony_ci``__main__.__spec__`` is set to ``None``, as the code used to populate the
10037db96d56Sopenharmony_ci:mod:`__main__` does not correspond directly with an importable module:
10047db96d56Sopenharmony_ci
10057db96d56Sopenharmony_ci- interactive prompt
10067db96d56Sopenharmony_ci- :option:`-c` option
10077db96d56Sopenharmony_ci- running from stdin
10087db96d56Sopenharmony_ci- running directly from a source or bytecode file
10097db96d56Sopenharmony_ci
10107db96d56Sopenharmony_ciNote that ``__main__.__spec__`` is always ``None`` in the last case,
10117db96d56Sopenharmony_ci*even if* the file could technically be imported directly as a module
10127db96d56Sopenharmony_ciinstead. Use the :option:`-m` switch if valid module metadata is desired
10137db96d56Sopenharmony_ciin :mod:`__main__`.
10147db96d56Sopenharmony_ci
10157db96d56Sopenharmony_ciNote also that even when ``__main__`` corresponds with an importable module
10167db96d56Sopenharmony_ciand ``__main__.__spec__`` is set accordingly, they're still considered
10177db96d56Sopenharmony_ci*distinct* modules. This is due to the fact that blocks guarded by
10187db96d56Sopenharmony_ci``if __name__ == "__main__":`` checks only execute when the module is used
10197db96d56Sopenharmony_cito populate the ``__main__`` namespace, and not during normal import.
10207db96d56Sopenharmony_ci
10217db96d56Sopenharmony_ci
10227db96d56Sopenharmony_ciReferences
10237db96d56Sopenharmony_ci==========
10247db96d56Sopenharmony_ci
10257db96d56Sopenharmony_ciThe import machinery has evolved considerably since Python's early days.  The
10267db96d56Sopenharmony_cioriginal `specification for packages
10277db96d56Sopenharmony_ci<https://www.python.org/doc/essays/packages/>`_ is still available to read,
10287db96d56Sopenharmony_cialthough some details have changed since the writing of that document.
10297db96d56Sopenharmony_ci
10307db96d56Sopenharmony_ciThe original specification for :data:`sys.meta_path` was :pep:`302`, with
10317db96d56Sopenharmony_cisubsequent extension in :pep:`420`.
10327db96d56Sopenharmony_ci
10337db96d56Sopenharmony_ci:pep:`420` introduced :term:`namespace packages <namespace package>` for
10347db96d56Sopenharmony_ciPython 3.3.  :pep:`420` also introduced the :meth:`find_loader` protocol as an
10357db96d56Sopenharmony_cialternative to :meth:`find_module`.
10367db96d56Sopenharmony_ci
10377db96d56Sopenharmony_ci:pep:`366` describes the addition of the ``__package__`` attribute for
10387db96d56Sopenharmony_ciexplicit relative imports in main modules.
10397db96d56Sopenharmony_ci
10407db96d56Sopenharmony_ci:pep:`328` introduced absolute and explicit relative imports and initially
10417db96d56Sopenharmony_ciproposed ``__name__`` for semantics :pep:`366` would eventually specify for
10427db96d56Sopenharmony_ci``__package__``.
10437db96d56Sopenharmony_ci
10447db96d56Sopenharmony_ci:pep:`338` defines executing modules as scripts.
10457db96d56Sopenharmony_ci
10467db96d56Sopenharmony_ci:pep:`451` adds the encapsulation of per-module import state in spec
10477db96d56Sopenharmony_ciobjects.  It also off-loads most of the boilerplate responsibilities of
10487db96d56Sopenharmony_ciloaders back onto the import machinery.  These changes allow the
10497db96d56Sopenharmony_cideprecation of several APIs in the import system and also addition of new
10507db96d56Sopenharmony_cimethods to finders and loaders.
10517db96d56Sopenharmony_ci
10527db96d56Sopenharmony_ci.. rubric:: Footnotes
10537db96d56Sopenharmony_ci
10547db96d56Sopenharmony_ci.. [#fnmo] See :class:`types.ModuleType`.
10557db96d56Sopenharmony_ci
10567db96d56Sopenharmony_ci.. [#fnlo] The importlib implementation avoids using the return value
10577db96d56Sopenharmony_ci   directly. Instead, it gets the module object by looking the module name up
10587db96d56Sopenharmony_ci   in :data:`sys.modules`.  The indirect effect of this is that an imported
10597db96d56Sopenharmony_ci   module may replace itself in :data:`sys.modules`.  This is
10607db96d56Sopenharmony_ci   implementation-specific behavior that is not guaranteed to work in other
10617db96d56Sopenharmony_ci   Python implementations.
10627db96d56Sopenharmony_ci
10637db96d56Sopenharmony_ci.. [#fnpic] In legacy code, it is possible to find instances of
10647db96d56Sopenharmony_ci   :class:`imp.NullImporter` in the :data:`sys.path_importer_cache`.  It
10657db96d56Sopenharmony_ci   is recommended that code be changed to use ``None`` instead.  See
10667db96d56Sopenharmony_ci   :ref:`portingpythoncode` for more details.
1067