"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

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

 Statements - Execution Units

 Function Statement and Function Call

 Iterators, Generators and List Comprehensions

 Classes and Instances

Modules and Module Files

 What Is Module

"import module" - Two-Step Process

 sys.modules - Listing Loaded Modules

 importlib.reload(module) - Reloading Module

 What Are Module Members

 "from module import member" Statement

 "from module import *" Statement

 What Is __all__ List

 __pycache__/module.version.pyc Files

 What Is the __main__ Module

 Packages and Package Directories

 "sys" and "os" Modules

 "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

 Jupyter Notebook and JupyterLab


 Full Version in PDF/EPUB