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: proper fallback for mo.watch.file in wasm (#7982)
Myles Scolnick1d53c6095b87
diff --git a/marimo/_runtime/watch/_path.py b/marimo/_runtime/watch/_path.pyindex 8b924570ff..a16bd067f4 100644--- a/marimo/_runtime/watch/_path.py+++ b/marimo/_runtime/watch/_path.py@@ -6,6 +6,7 @@ import threadingfrom pathlib import Pathfrom typing import Any, Callable, TypeVar+from marimo import _loggersfrom marimo._runtime.context import (ContextNotInitializedError,get_context,@@ -14,6 +15,9 @@ from marimo._runtime.context import (from marimo._runtime.side_effect import SideEffectfrom marimo._runtime.state import Statefrom marimo._runtime.threads import Thread+from marimo._utils.platform import is_pyodide++LOGGER = _loggers.marimo_logger()if sys.version_info >= (3, 11):from typing import Self@@ -71,11 +75,21 @@ class PathState(State[Path]):# Only bother with the watcher if the context is installed# State is not enabled in script modeif runtime_context_installed():- Thread(- target=self._target,- args=(path, self, self._should_exit),- daemon=True,- ).start()+ # File watching with threads is not supported in Pyodide/WASM+ # The file can still be read/written, but won't trigger reactive+ # updates when changed externally+ if is_pyodide():+ LOGGER.warning(+ "Reactive file watching is not supported in "+ "Pyodide/WebAssembly. The file can still be read/written, "+ "but external changes won't trigger reactive updates."+ )+ else:+ Thread(+ target=self._target,+ args=(path, self, self._should_exit),+ daemon=True,+ ).start()def __getattr__(self, name: str) -> Any:"""Get an attribute from the file path."""diff --git a/tests/_pyodide/test_pyodide_acceptance.mjs b/tests/_pyodide/test_pyodide_acceptance.mjsindex c6d446cb26..249b4cfd94 100644--- a/tests/_pyodide/test_pyodide_acceptance.mjs+++ b/tests/_pyodide/test_pyodide_acceptance.mjs@@ -257,6 +257,67 @@ result = {"kernel_ready": kernel_ready_received,}json.dumps(result)+`);++ // Step 6: Test mo.watch.file in Pyodide (within execution context)+ console.log("Step 6: Testing mo.watch.file in Pyodide...");++ // Use bridge.put_control_request to run code within the marimo execution context+ // This ensures runtime_context_installed() returns True+ await pyodide.runPythonAsync(`+import json+from pathlib import Path++# Create a test file first+test_file_path = Path("/home/pyodide/watch_test.txt")+test_file_path.write_text("initial content")+print(f"Created test file: {test_file_path}")++# Run code within the marimo execution context using the bridge+# This simulates what happens when a cell runs mo.watch.file+code_to_run = '''+import marimo as mo+from pathlib import Path++# This should NOT throw an error in Pyodide - it should gracefully degrade+# by logging a warning and returning a FileState that can still read/write+test_file_path = Path("/home/pyodide/watch_test.txt")+file_state = mo.watch.file(test_file_path)++# Verify we can read the file+content = file_state.read_text()+assert content == "initial content", f"Expected 'initial content', got '{content}'"++# Verify we can write to the file+file_state.write_text("new content")+updated_content = file_state.read_text()+assert updated_content == "new content", f"Expected 'new content', got '{updated_content}'"++# Verify basic Path methods still work+assert file_state.exists(), "File should exist"+assert file_state.name == "watch_test.txt", f"Expected 'watch_test.txt', got '{file_state.name}'"++# Return success indicator+file_state_type = type(file_state).__name__+'''++# Use the bridge to run the code in the execution context+# ExecuteCellsCommand expects cell_ids and codes arrays+bridge.put_control_request(json.dumps({+ "type": "execute-cells",+ "cellIds": ["test_watch_cell"],+ "codes": [code_to_run]+}))++# Wait for execution to complete+await asyncio.sleep(1.0)++# Verify the file was modified (proves write_text worked)+final_content = test_file_path.read_text()+assert final_content == "new content", f"Expected 'new content', got '{final_content}'"+print(f"Final file content verified: '{final_content}' - OK")++print("\\nmo.watch.file works correctly in Pyodide execution context!")`);console.log("");