Reloading a module in Python

Sometimes when you are testing a script in Python, you may need to make changes in your code and then reload the module. In such cases, reload() can be very helpful.

The syntax for the reload() can be given as follows:

importlib.reload(module)

The argument passed in the reload() function should be the module that we are reloading. Note that this module must have been imported before in our program.

See the below example.

import math
import importlib
importlib.reload(math)

Here, we use reload() function for math module which has been imported before as you can see in the program. The above Python code runs fine.

When we try to reload a module that has not been imported before, the reload() throws an error. Have a look at the below code.

import importlib
importlib.reload(math)

Output for the above program:

Traceback (most recent call last):
File "imp.py", line 2, in <module>
importlib.reload(math)
NameError: name 'math' is not defined

Some important points regarding reloading the module that must be kept in mind:

  • That module that we are importing must have been imported before or else an error will be thrown.
  • While reloading the init function of the module is not loaded again.
  • The names in module namespaces are changed to point to the new objects.
  • When a module is reloaded its dictionary (module’s global variables) is retained. The redefinition of names will override the old definition.

Thank you and keep coding.

Also read: Pygorithm module in Python

Leave a Reply