How do I unload (reload) a Python module?
To unload a Python module, you can use the del statement to remove it from memory.
To truly unload a Python module, you must remove it from sys.modules and clear all references to it. The del statement only removes the name from the current namespace, not the module object itself. For example, to unload a module named example_module:
Unload an imported module in Python
import sys
del example_module
del sys.modules['example_module']Note: Unloading modules is generally discouraged in production code due to potential side effects on running applications. This approach only removes the module from the current namespace and
sys.modules; other modules holding references to it will continue using the old version.
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
To reload a module, you can use the importlib library's reload function. For example, if you have imported a module named example_module, you can reload it with the following code:
Reload a module in Python
import importlib
importlib.reload(example_module)Warning: Reloading a module does not update existing instances of classes or functions created from the old module. It only updates the module object in
sys.modules. Ensure the module is already imported before callingreload(). Use with caution, especially if other parts of your application hold references to the original module.