How to Reload Custom Python Modules To Apply Changes in Visual Studio Code Using importlib

When you program with Visual Studio Code (VS Code) and import a module in Python, the code in that module is only executed once, and subsequent imports of the same module will simply use the already imported module without re-executing its code. This means that if you modify a module after it has been imported, the changes will not be applied until you reload the module.

To reload a module in Python, you can use the importlib module, which provides a function called reload(). Here’s an example:

import custom_module
# ... do some modifications to the custom_module ...

import importlib
importlib.reload(custom_module)

In this example, we first import the custom_module module, which contains the code we want to modify. We then make some modifications to the module’s code.

To apply the changes, we use the importlib module to reload the custom_module module. We call importlib.reload(custom_module), which re-executes the code in the custom_module module, applying any changes we made.

Note that the reload() function only works with modules that were originally loaded using the import statement. If the module was loaded using other methods, such as the __import__() function or the exec() function, reload() will not work.