Thursday, July 1, 2021

Python how to reload a module

import looks first in sys.modules to see whether it has already imported the module. If it has, it will just give you the module object that it made when it last imported the module. Since del mymodule doesn't remove the module object from sys.modules, re-importing it will just rebind the name to the object in sys.modules. 


if you want it to re-import the module, do reload(module). Equivalently, delete it from sys.modules and then import it.


Just like any other Python object, a module continues to exist until there are no more references to it. In other words, sys.modules behaves like a regular dict, and


import mymodule

lst = {mymodule.__name__: mymodule}

'mymodule' in globals()   # True

'mymodule' in lst         # True

del mymodule

'mymodule' in globals()   # False

'mymodule' in lst         # Still True



sys.modules is only consulted on import statements. You can delete a module from sys.modules to make Python reload it the next time it is imported.

del removes the binding of a name in the appropriate scope; it has nothing to do with modules per se.

sys.modules keeps a list of all modules that have been loaded, regardless of whether they're bound to any name in your program.




References:

https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module

https://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module/438845#438845

https://stackoverflow.com/questions/7121802/module-name-in-sys-modules-and-globals => Globals



No comments:

Post a Comment