CHAPTER FIVE THE IMPORT SYSTEM Python code in one module gains access to the code in another module by the process of importing it. The import statement is the most common way of invoking the import machinery, but it is not the only way. Functions such as importlib.import_module() and built-in$_{__import__()}$ can also be used to invoke the import machin- ery. The $_{import}$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 import statement is defined as a call to the __import__() function, with the appropriate arguments. The return value of __import__() is used to perform the name binding operation of the$_{import}$ statement. See the$_{import}$ statement for the exact details of that name binding operation. A direct call to$_{__import__()}$ 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$_{sys.modules}$ ), only the$_{import}$ statement performs a name binding operation. When an $_{import}$statement is executed, the standard builtin$_{__import__()}$ function is called. Other mech- anisms for invoking the import system (such as importlib.import_module() ) may choose to bypass __import__() and use their own solutions to implement import semantics. When a module is first imported, Python searches for the module and if found, it creates a module object$^{1}$, initializing it. If the named module cannot be found, a ModuleNotFoundError 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. Changed in version 3.3: The import system has been updated to fully implement the second phase of PEP 302 . There is no longer any implicit import machinery - the full import system is exposed through$_{sys.meta_path}$ . In addition, native namespace package support has been implemented (see PEP 420 ). The$_{importlib}$module provides a rich API for interacting with the import system. For example$_{importlib.}$ import_module() provides a recommended, simpler API than built-in$_{__import__()}$ for invoking the im- port machinery. Refer to the$_{importlib}$library documentation for additional detail. 1 See types.ModuleType . 5.1 importlib 49