Python Tutorials - Herong's Tutorial Examples - v2.14, by Herong Yang
"import module" - Two-Step Process
This section describes the two-step process of the 'import module' statement execution.
In the last tutorial, we learned how to create a "module" object using the "import module" statement. Now let's take a closer look at the behavior of the "import module" statement.
Keep the module file in the current directory and run the following code:
herong$ ls -l -rw-r--r--@ 1 herong staff 423 Apr 1 07:35 module_test.py herong$ python # import the module >>> import module_test Hi there! - from 'module_test' module Welcome on board! - from 'first' class # import the module again >>> import module_test
As you can see from the output, module sub-statements are executed only when the module is imported for the first time.
This is because the "import" statement is designed as a two-step process with a cache mechanism:
Step 1: Loading - In this step, the Python system will do nothing, if the requested module already exists in the cache. Otherwise, it will:
This is why when you run the "import module_test" statement for the second time, you don't see those "print" statements get executed. The requested module is already in the cache. It will not be loaded again.
Step 2: Binding - In this step, the Python system will:
This binding step actually acts like an assignment statement, assigning the reference of "module" object to a variable.
Table of Contents
Variables, Operations and Expressions
Function Statement and Function Call
Iterators, Generators and List Comprehensions
►"import module" - Two-Step Process
sys.modules - Listing Loaded Modules
importlib.reload(module) - Reloading Module
"from module import member" Statement
"from module import *" Statement
__pycache__/module.version.pyc Files
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
Anaconda - Python Environment Manager