How do I unload (reload) a Python module?


The function reload(moduleName) reloads a previously loaded module (assuming you loaded it with the syntax "importmoduleName" without exiting the script. It is intended for conversational use, where you have edited the source file for a module and want to test it without leaving Python and starting it again. For example,

>>> import mymodule
>>> # Edited mymoduleand want to reload it in this script
>>> reload(mymodule)

Note that the moduleName is the actual name of the module, not a string containing its name. The python docs state following about reload function:

 Python modules’ code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module’s dictionary. The init function of extension modules is not called a second time. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.

Updated on: 30-Sep-2019

417 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements