Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do I unload (reload) a Python module?
The reload() function reloads a previously imported module without restarting Python. This is useful when you modify a module's source code and want to test changes in an interactive session.
Python 2 vs Python 3
In Python 2, reload() was a built-in function. In Python 3, it was moved to the importlib module.
Python 2 Syntax
import mymodule # Edit mymodule.py and want to reload it reload(mymodule)
Python 3 Syntax
import importlib import mymodule # Edit mymodule.py and want to reload it importlib.reload(mymodule)
Example
Let's create a simple module and demonstrate reloading ?
# First, let's simulate a module with a simple function
import types
import sys
# Create a module dynamically
mymodule = types.ModuleType('mymodule')
mymodule.greet = lambda: print("Hello from original module!")
sys.modules['mymodule'] = mymodule
# Import and use the module
import mymodule
mymodule.greet()
Hello from original module!
Now let's modify and reload the module ?
import importlib
# Modify the module (simulating editing the source file)
mymodule.greet = lambda: print("Hello from reloaded module!")
# Reload the module
importlib.reload(mymodule)
mymodule.greet()
Hello from reloaded module!
How It Works
When you reload a module, Python:
- Recompiles the module's source code
- Re-executes the module-level code
- Creates new objects bound to names in the module's dictionary
- Updates the module namespace with new or changed objects
Important Notes
References to old objects: Existing references to the old module objects are not automatically updated. You must update them manually.
import importlib
# Create a reference to a function
old_function = mymodule.greet
# Reload the module
importlib.reload(mymodule)
# old_function still points to the original function
print("Old reference:")
old_function()
print("New reference:")
mymodule.greet()
Old reference: Hello from reloaded module! New reference: Hello from reloaded module!
Extension modules: The initialization function of C extension modules is not called a second time during reload.
Common Use Cases
- Interactive development and testing
- Debugging module code without restarting Python
- Hot-swapping code in development environments
Conclusion
Use importlib.reload() in Python 3 to reload modified modules during development. Remember that existing references to old objects won't be automatically updated.
