A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: fix edge case with packages and autoreload (#1172)
Akshay Agrawal65479a90e143
diff --git a/marimo/_runtime/reload/module_watcher.py b/marimo/_runtime/reload/module_watcher.pyindex fc6d45b2d5..0da4b57271 100644--- a/marimo/_runtime/reload/module_watcher.py+++ b/marimo/_runtime/reload/module_watcher.py@@ -34,9 +34,21 @@ def _modules_imported_by_cell(cell: CellImpl) -> set[str]:return modules+def is_submodule(src_name: str, target_name: str) -> bool:+ """Returns True if src_name is a parent of target_name++ eg: "marimo.plugins" is a parent of "marimo.plugins.ui", returns True+ """+ src_parts = src_name.split(".")+ target_parts = target_name.split(".")+ if len(src_parts) > len(target_parts):+ return False+ return all(src_parts[i] == target_parts[i] for i in range(len(src_parts)))++def _depends_on(src_module: types.ModuleType,- target_filenames: set[str],+ target_modules: set[types.ModuleType],failed_filenames: set[str],) -> bool:"""Returns whether src_module depends on any of target_filenames"""@@ -60,12 +72,26 @@ def _depends_on(failed_filenames.add(src_module.__file__)return False+ target_filenames = set(+ t.__file__ for t in target_modules if hasattr(t, "__file__")+ )for found_module in itertools.chain([src_module], finder.modules.values()):- if (- hasattr(found_module, "__file__")- and found_module.__file__ in target_filenames+ file = getattr(found_module, "__file__", None)+ if file is None:+ continue++ # easy case: a discovered module was directly modified+ if file in target_filenames:+ return True++ # if a discovered module is a package, check if any of the modified+ # modules are contained in that package+ if file.endswith("__init__.py") and any(+ is_submodule(src_module.__name__, target_module.__name__)+ for target_module in target_modules):return True+return False@@ -80,9 +106,7 @@ def _check_modules(for modname, module in modules.items():if _depends_on(src_module=module,- target_filenames=set(- m.__file__ for m in modified_modules if m.__file__ is not None- ),+ target_modules=set(m for m in modified_modules if m is not None),failed_filenames=failed_filenames,):stale_modules[modname] = modulediff --git a/tests/_runtime/reload/test_module_watcher.py b/tests/_runtime/reload/test_module_watcher.pyindex 6e8214c917..0f9831b381 100644--- a/tests/_runtime/reload/test_module_watcher.py+++ b/tests/_runtime/reload/test_module_watcher.py@@ -227,3 +227,47 @@ async def test_reload_nested_module_import_module_autorun(assert not k.graph.cells[er_2.cell_id].staleassert not k.graph.cells[er_3.cell_id].staleassert k.globals["x"] == 2+++async def test_reload_package(+ tmp_path: pathlib.Path,+ py_modname: str,+ k: Kernel,+ exec_req: ExecReqProvider,+):+ sys.path.append(str(tmp_path))+ b = tmp_path / (b_name := random_modname())+ b.mkdir()+ c = b / (c_name := random_modname())+ c.mkdir()+ (b / "__init__.py").write_text(f"from {b_name}.{c_name}.mod import func")+ (c / "__init__.py").write_text("")++ nested_module = c / "mod.py"+ nested_module.write_text("func = lambda: 1")++ config = copy.deepcopy(DEFAULT_CONFIG)+ config["runtime"]["auto_reload"] = "detect"+ k.set_user_config(SetUserConfigRequest(config=config))+ await k.run(+ [+ er_1 := exec_req.get(f"import {b_name}"),+ er_2 := exec_req.get(f"x = {b_name}.func()"),+ er_3 := exec_req.get("pass"),+ ]+ )+ assert not k.errors+ assert k.globals[b_name]+ assert k.globals["x"] == 1+ update_file(nested_module, "func = lambda : 2")++ # wait for the watcher to pick up the change+ await asyncio.sleep(1.5)+ assert k.graph.cells[er_1.cell_id].stale+ assert k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ await k.run_stale_cells()+ assert not k.graph.cells[er_1.cell_id].stale+ assert not k.graph.cells[er_2.cell_id].stale+ assert not k.graph.cells[er_3.cell_id].stale+ assert k.globals["x"] == 2