How to reload module in Python | applied electronics engineering


How to reload module in Python

By Applied Electronics - Sunday, May 8, 2016 No Comments
If you have noticed, in Python programming there is a awkward situation when you import modules in another program. You must have noticed that if you change any statement in the imported module while working with the main program, the change is not reflected in main program. So how to deal with this?

One way(perhaps the only way) is to force reloading the imported module after having made some changes in it. Consider that there is a in D:/python directory. The content of the say is as follows.

import sys
print("great, it's working!")

Suppose while working in the interactive programming mode, you need to make change in the For example in this case let's change the print statement to-

print("it changed")

Having done so, if you write-

>>> import file

Nothing will happen, as opposed to printing the output- it changed. This is because python still remembers the statement of the module that was imported/loaded earlier. And it will not change during the session. It will only change when you stop and restart a new session. This is not very helpful, specially if you got long program with lots of imports.

One way to deal with this is using reload function from imp library.

To do you have to import reload function from imp library itself because starting from python v3 it stopped inbuild reload function.

So first import reload function from the imp library using the following statement-

from imp import reload

The reload the desired module, in this case the file module.

>>> reload(file)

The following picture illustrates this in Python IDLE GUI-

So this tutorial showed you deal with problem of changing python module program does not change in main program.

No Comment to " How to reload module in Python "