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
Reloading modules in Python?
The reload() function is used to reload a previously imported module. This is particularly useful during interactive development sessions where you modify a module's code and want to see changes without restarting the Python interpreter.
When you modify a module file after importing it, Python continues to use the cached version. The reload() function forces Python to re-read and re-execute the module code.
How reload() Works
When reload() is executed, several important things happen:
The module's code is recompiled and re-executed, creating new objects bound to names in the module's dictionary
Old objects are only garbage collected when their reference counts drop to zero
Names in the module namespace are updated to point to new objects
External references to old objects are not automatically updated and must be manually refreshed
Basic Syntax
In Python 3, reload() is available in the importlib module:
import importlib importlib.reload(module_name)
Example: Reloading a Built-in Module
Here's how to reload the sys module:
import sys
import importlib
# Reload the sys module
importlib.reload(sys)
print("sys module reloaded successfully")
sys module reloaded successfully
Example: Reloading a Custom Module
Let's create a simple module and demonstrate reloading:
# Create a file called mymodule.py with this content:
def greet():
return "Hello from version 1"
version = "1.0"
Now import and use the module:
import mymodule
import importlib
print(mymodule.greet())
print(f"Version: {mymodule.version}")
# After modifying mymodule.py to version 2
importlib.reload(mymodule)
print(mymodule.greet()) # Shows updated content
print(f"Version: {mymodule.version}")
Important Considerations
Keep these limitations in mind when using reload():
The module must have been successfully imported before reloading
Existing references to old objects are not automatically updated
Class instances created before reload still use the old class definition
Submodules are not automatically reloaded
Alternative: Using importlib.import_module()
For more control, you can use import_module() with reload:
import importlib
# Import and immediately reload
module = importlib.import_module('sys')
importlib.reload(module)
print("Module imported and reloaded")
Module imported and reloaded
Conclusion
Use importlib.reload() for interactive development when you need to refresh module changes. Remember that existing object references won't be automatically updated, so use it primarily during development and testing phases.
