importlib.reload in CPython 3.11: keeping existing object state consistent after a zero-downtime module swap
0 reputation · 17 Dec 2024, 02:24 UTC
Goal
I want to use importlib.reload() as a zero-downtime update path for a small pure-Python application running on CPython 3.11, so a new version of a module can take effect without restarting the process.
Constraints and uncertainty
The documentation confirms that reload() re-executes the module code and replaces the entry in sys.modules, but objects already instantiated from classes in that module keep referencing the old class definition. My application holds long-lived instances (service objects with internal caches and registered callbacks), so a naive reload would leave the process running two versions of the same class simultaneously. I also register signal handlers at module level, and I am unsure how to prevent duplicate registrations when the module body runs again.
All modules involved are pure Python; no C extensions are in scope.
Questions
- Is there a documented or idiomatic pattern for migrating existing instances to the reloaded class (e.g., updating
__class__or re-instantiating) without losing their internal state? - How should module-level side effects such as signal handler registration be guarded so a reload does not register them twice?
- Are there documented cases in 3.11 where
reload()silently leaves stale references that a verification step should check?