Call importlib.reload(module) from Python’s built-in importlib module—passing the already-imported module object (not a string name)—to re-execute the module’s top-level source file in place and update its attributes in sys.modules without restarting your REPL, Jupyter notebook, or long-running process, while keeping in mind that existing from module import func bindings and instances of old classes still point to the pre-reload definitions until refreshed.
Basic Example
import importlib
import my_utils # Initial import
# ... edit and save `my_utils.py` on disk ...
# 1. Recommended: Pass the imported module object to `importlib.reload()`
my_utils = importlib.reload(my_utils)
my_utils.run_task() # Executes the updated code from disk
# 2. If you only have the module's name as a string:
import sys
module_name = "my_utils"
if module_name in sys.modules:
importlib.reload(sys.modules[module_name])
Key Details & Edge Cases
importlib.reload()requires an imported module object, not a string (TypeError):- Calling
importlib.reload("my_utils")raisesTypeError: reload() argument must be a module. Always import the module first (import my_utils) or look it up insys.modules["my_utils"].
- Calling
- Why
from my_utils import greetdoes NOT update afterimportlib.reload(my_utils):importlib.reload(my_utils)mutatesmy_utils.__dict__in place, so attribute lookups viamy_utils.greet()immediately see the new function. However,from my_utils import greetcopied a direct reference into your caller’s namespace at the time of the initial import—re-runfrom my_utils import greetafter reloading if you use bare names.
- Existing class instances keep their old methods (
isinstance(old_obj, my_utils.MyClass)becomesFalse):- Reloading re-runs
class MyClass:and creates a brand-new class object undermy_utils.MyClass. Any instance instantiated before the reload still points to the old class object (old_obj.__class__ is not my_utils.MyClass), so existing objects keep old method definitions and failisinstance()checks against the reloaded class until re-instantiated.
- Reloading re-runs
- Reloading is shallow (does NOT recursively reload submodules):
- If
app.pyimportshelpers.pyand you edithelpers.py, callingimportlib.reload(app)re-runsimport helpers, which sees"helpers"already cached insys.modulesand skips readinghelpers.pyfrom disk! Reload dependencies bottom-up (importlib.reload(helpers)first, thenimportlib.reload(app)).
- If
- IPython / Jupyter automatic module reloading (
%autoreload):- In interactive notebooks or IPython shells, enable
%load_ext autoreloadfollowed by%autoreload 2once at startup so IPython automatically reloads all modified modules (and updatesfrom ... import ...bindings and class methods) before executing every cell.
- In interactive notebooks or IPython shells, enable
- Stale
.pycbytecode timestamps when editing within the same second:- Python checks file modification timestamps (
mtime) to decide whether to recompile.pycbytecode; automated scripts that rewrite a.pyfile twice within the same filesystem tick may load cached.pycunlessimportlib.invalidate_caches()is called beforehand.
- Python checks file modification timestamps (
Comparison of Runtime Module Reloading Approaches in Python
| Approach | Scope of Reload | Updates from mod import x & Existing Instances? |
Extra Dependencies | Best Used When |
|---|---|---|---|---|
importlib.reload(mod) (Recommended) |
Single specified module object | No (updates mod.attr lookups only; submodules must be reloaded manually) |
None (standard library) | Standard Python REPL, debugging sessions, or explicit plugin reload hooks. |
IPython %load_ext autoreload + %autoreload 2 |
All modified imported modules automatically | Yes (patches functions, from imports, and class methods in place) |
ipython / Jupyter |
Interactive data science and exploratory coding in Jupyter Notebooks or IPython. |
Subprocess / Dev-Server Watcher (uvicorn --reload, watchdog, watchfiles) |
Restarts clean worker process on file save | Yes (clean slate—zero stale state or isinstance mismatches) |
watchfiles / framework CLI |
Web servers, background workers, and production-like development workflows. |
Deleting from sys.modules (del sys.modules["mod"]) |
Forces fresh import mod |
No (creates a second module object; old references diverge) | None (standard library) | Avoid in general code—breaks singletons and isinstance() checks across modules. |
You must log in or register to comment.
