Reloading Module
M3-R5.1 · Chapter 8: Scope and Modules · 2 min read
Reloding Modules
Why Reload a Module?
Since Python caches modules in sys.modules, if you change a module's source code after importing it, re-running import will NOT pick up the changes.
To force Python to re-read the updated file, use importlib.reload()
Syntax
from importlib import reload
reload(module_name)
Step-by-Step Example
import mymodule # First import -- loaded and cached
# (You edit mymodule.py now...)
import mymodule # Re-import -- uses cache, NO changes!
from importlib import reload
reload(mymodule) # Reload -- re-reads file, picks up changes!
Practical Example — Config File
# config.py -> DEBUG = False
import config
print(config.DEBUG) # False
# (You update config.py: DEBUG = True)
import config # Re-import does nothing
print(config.DEBUG) # Still False! (cached)
from importlib import reload
reload(config)
print(config.DEBUG) # True (reloaded from disk)
When is reload() Useful?
- Interactive development in Python shell or Jupyter Notebook
- When a module file changes during program execution
- Testing and debugging without restarting the interpreter
- Live configuration files that update dynamically
Important Points About reload()
|
Point |
Explanation |
|
Must import first |
Module must already be imported before reloading |
|
Partial update risk |
Objects created from old version still use old code |
|
Not recursive |
Module dependencies are NOT automatically reloaded |
|
sys.modules updated |
Entry in sys.modules is refreshed after reload |
|
Python 3 only syntax |
from importlib import reload (not built-in in Python 3) |
import vs reload — Key Difference
|
import (repeated) |
reload(module) |
|
Uses cached version from sys.modules |
Re-executes the module file from disk |
|
Does NOT pick up file changes |
DOES pick up file changes |
|
Fast (no file I/O) |
Slower (reads and compiles the file again) |
|
Default Python behavior |
Requires explicit importlib.reload() call |