- The import keyword finds and loads a package, a sub-package or a module if they are found in the system using the import mechanism.
- Once a module is loaded, the name of the imported module is introduced in the current scope where the import statement is executed.
- Which name gets introduced - name of the actual module or the top-level module…depends on how the import statement is used.
- Regardless of how the import is used, if a module is not found, Python raises a ModuleNotFound exception.
How the import statement binds a name when used alone:
- If a top-level module is given in the import statement, the module is imported and the name is bound in the current scope. Remember, all the packages are generalized as modules. In fact, Python handles packages using the type module.
e.g., import top-level-package
- If a non-top level module is given in the import statement, the module is imported, but the name bound to the current scope is the top-level module.
e.g., import top-level-package.imported-module
To use imported-module in the code it has to be referred to as top-level-package.imported-module, because only the name top-
level-package is introduced into the current scope.
As Keyword in import statement:
- If an as keyword is used after a module name and an alias is given, the alias is introduced as a name in the current scope.
e.g., import numpy as np
The above statement imports the numpy module and introduces a name np into the current scope. Accessing the name pi in the numpy module can now be done using np.pi which will print 3.141592653589793 in the Python interactive console.
Using the from keyword in import statement:
- When a Python module is imported using the keywords import and from, the given module is imported and the given name of the module is bound to the current scope regardless of whether it is a top level module or not.