From 52d057a7339afd05198b31cd2e6661331b6a67db Mon Sep 17 00:00:00 2001 From: Stephen Macke Date: Mon, 6 Nov 2023 18:23:59 -0800 Subject: [PATCH] improve ipyflow integration and handle case where ipyflow already instantiated reloader singleton --- core/superduperreload/magics.py | 7 ++++++- core/superduperreload/superduperreload.py | 19 +++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/core/superduperreload/magics.py b/core/superduperreload/magics.py index d75de4c..98c7443 100644 --- a/core/superduperreload/magics.py +++ b/core/superduperreload/magics.py @@ -106,7 +106,12 @@ def __init__(self, *a, **kw): raise RuntimeError("CPython required for superduperreload extension") flow = kw.pop("flow", None) super().__init__(*a, **kw) - self._reloader = ModuleReloader.instance(self.shell, flow=flow) + if ModuleReloader.initialized(): + self._reloader = ModuleReloader.instance() + self._reloader.enabled = True + self._reloader.start_watcher_thread_if_applicable() + else: + self._reloader = ModuleReloader.instance(self.shell, flow=flow, enabled=True) self.loaded_modules = set(sys.modules) @line_magic diff --git a/core/superduperreload/superduperreload.py b/core/superduperreload/superduperreload.py index b35358e..ee636fa 100644 --- a/core/superduperreload/superduperreload.py +++ b/core/superduperreload/superduperreload.py @@ -94,10 +94,11 @@ def __init__( self, shell: Optional[Union["InteractiveShell", "FakeShell"]] = None, flow: Optional["NotebookFlow"] = None, + enabled: bool = True, ) -> None: super().__init__(patch_referrers=SHOULD_PATCH_REFERRERS) # Whether this reloader is enabled - self.enabled = True + self.enabled = enabled # Whether to print reloaded modules and other messages self.verbose = True # Modules that failed to reload: {module: mtime-on-failed-reload, ...} @@ -142,10 +143,14 @@ def __init__( self.check(do_reload=False) self._watcher: Optional[Thread] = None self._watcher_running = False - if self.flow is not None: - self._watcher = Thread(target=self._watch, daemon=True) - self._watcher_running = True - self._watcher.start() + self.start_watcher_thread_if_applicable() + + def start_watcher_thread_if_applicable(self) -> None: + if self._watcher is not None or self.flow is None or not self.enabled: + return + self._watcher = Thread(target=self._watch, daemon=True) + self._watcher_running = True + self._watcher.start() @classmethod def clear_instance(cls) -> None: @@ -313,9 +318,7 @@ def handle_module_refreshed( pass def _watch(self, interval: float = 1) -> None: - assert self.flow is not None - for m in list(sys.modules.values()): - self.handle_module_refreshed(m) + assert self.enabled and self.flow is not None while self._watcher_running: try: with self._reloading_lock: