Reload or Unimport Module in Python

  1. Unimport a Module in Python
  2. Reload a Module in Python

Modules allow us to store definitions of different functions and classes in a Python file, and then such files can be used in other files. The pandas, numpy, scipy, matplotlib are some of the most widely used modules in Python.

We can also create our own modules in Python, which can increase modularity and simplify large programs.

Unimport a Module in Python

We use the import command to load a specific module to memory in Python. We cannot unimport a module since Python stores it in the cache memory, but we can use a few commands and try to dereference these modules so that we are unable to access it during the program. These methods, however, might fail at times, so please be careful.

The first is the del command. It is used to remove a variety of objects in Python. Removing the access of a module using this command is shown below.

import module_name
del module_name

The sys.modules is a dictionary that can be viewed using the sys module and is used to store the references of a function and modules. We can remove the required module from this dictionary using the del command to remove its every reference. It is difficult to remove modules that have been referenced a lot, so one needs to be careful while using this. This method might produce unwanted results, so please be cautious.

if 'myModule' in sys.modules:
    del sys.modules["myModule"]

Reload a Module in Python

In case we have made changes to a module and wish to implement those changes without restarting the program, we can use the reload() function that will reload the required module.

The reload() function has a long history in Python. Till Python 2.7 it was a built-in function.

In Python 3.0 to Python 3.3, it was present in the imp library that was later deprecated and changed to importlib module, which contains functions for implementing the mechanisms of importing codes in files Python.

The following code shows how to use the reload() function.

import importlib
reload(module_name)
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.