How do you reload an updated Python module at runtime without restarting? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you reload an updated Python module at runtime without restarting?

message-square
0

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") raises TypeError: reload() argument must be a module. Always import the module first (import my_utils) or look it up in sys.modules["my_utils"].
  • Why from my_utils import greet does NOT update after importlib.reload(my_utils):
    • importlib.reload(my_utils) mutates my_utils.__dict__ in place, so attribute lookups via my_utils.greet() immediately see the new function. However, from my_utils import greet copied a direct reference into your caller’s namespace at the time of the initial import—re-run from my_utils import greet after reloading if you use bare names.
  • Existing class instances keep their old methods (isinstance(old_obj, my_utils.MyClass) becomes False):
    • Reloading re-runs class MyClass: and creates a brand-new class object under my_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 fail isinstance() checks against the reloaded class until re-instantiated.
  • Reloading is shallow (does NOT recursively reload submodules):
    • If app.py imports helpers.py and you edit helpers.py, calling importlib.reload(app) re-runs import helpers, which sees "helpers" already cached in sys.modules and skips reading helpers.py from disk! Reload dependencies bottom-up (importlib.reload(helpers) first, then importlib.reload(app)).
  • IPython / Jupyter automatic module reloading (%autoreload):
    • In interactive notebooks or IPython shells, enable %load_ext autoreload followed by %autoreload 2 once at startup so IPython automatically reloads all modified modules (and updates from ... import ... bindings and class methods) before executing every cell.
  • Stale .pyc bytecode timestamps when editing within the same second:
    • Python checks file modification timestamps (mtime) to decide whether to recompile .pyc bytecode; automated scripts that rewrite a .py file twice within the same filesystem tick may load cached .pyc unless importlib.invalidate_caches() is called beforehand.

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.