importlib.reload(module) - Reloading Module

This section provides a tutorial example on how to reload a given 'module' object using the 'importlib.reload(module)' function.

In previous tutorials, we learned that a module file will be loaded into memory cache only once, even we call "import module" multiple times.

This means that sub-statements included in the module file will be executed only once, even we call the "import module" multiple times.

Normally, there is no need to load the module file again.

But if you have modified the module file after it's been loaded, and you want to use the modified version in your running process, you can use the "importlib.reload(module)" function to reload the module file.

The code below shows you an example of reloading a loaded module.

# load a module from a module file and bind it to "x"
>>> import module_test as x
Hi there! - from 'module_test' module
Welcome on board! - from 'first' class
>>> id(x)
4483027968

# bind the same module it to "y"
>>> import module_test as y
>>> id(y)
4483027968

>>> import importlib
>>> res = importlib.reload(x)
Hi there! - from 'module_test' module
Welcome on board! - from 'first' class
>>> res
<module 'module_test' from '/home/herong/module_test.py'>

>>> id(x)
4483027968

Note that the "importlib.reload(module)" function only updates the given "module" object by executing statements stored in the module file. It does not destroy the given "module" object and create a new one.

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

 References

 Full Version in PDF/EPUB