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: allow cache blocks to be invoked in script mode (#6819)
Dylan Madisetti48f64494723d
diff --git a/marimo/_ast/load.py b/marimo/_ast/load.pyindex c3e6f77452..b207adc987 100644--- a/marimo/_ast/load.py+++ b/marimo/_ast/load.py@@ -14,7 +14,11 @@ from marimo._ast.parse import (is_non_marimo_python_script,parse_notebook,)-from marimo._schemas.serialization import NotebookSerialization, UnparsableCell+from marimo._schemas.serialization import (+ CellDef,+ NotebookSerialization,+ UnparsableCell,+)LOGGER = _loggers.marimo_logger()@@ -89,6 +93,24 @@ def _static_load(filepath: Path) -> Optional[App]:return load_notebook_ir(notebook, filepath=str(filepath))+def find_cell(filename: str, lineno: int) -> CellDef | None:+ """Find the cell at the given line number in the notebook.++ Args:+ filename: Path to a marimo notebook file (.py or .md)+ lineno: Line number to search for+ """+ load_result = get_notebook_status(filename)+ if load_result.notebook is None:+ raise OSError("Could not resolve notebook.")+ previous = None+ for cell in load_result.notebook.cells:+ if cell.lineno > lineno:+ break+ previous = cell+ return previous++def load_notebook_ir(notebook: NotebookSerialization, filepath: Optional[str] = None) -> App:diff --git a/marimo/_save/save.py b/marimo/_save/save.pyindex bd6e9795e8..bff421435b 100644--- a/marimo/_save/save.py+++ b/marimo/_save/save.py@@ -27,6 +27,7 @@ from typing import ()from marimo._ast.cell_id import is_external_cell_id+from marimo._ast.load import find_cellfrom marimo._ast.transformers import (ARG_PREFIX,CacheExtractWithBlock,@@ -596,7 +597,7 @@ class _cache_context(SkipContext, CacheContext):# causing this function to terminate before reaching this block.self._frame = with_framefor i, frame in enumerate(stack[::-1]):- _filename, lineno, function_name, _code = frame+ filename, lineno, function_name, _code = frameif function_name == "<module>":ctx = get_context()if ctx.execution_context is None:@@ -608,10 +609,30 @@ class _cache_context(SkipContext, CacheContext):)graph = ctx.graphcell_id = ctx.cell_id or ctx.execution_context.cell_id++ # We are calling from script mode, so our line number is+ # absolute.+ if "__marimo__" not in filename:+ cell = find_cell(filename, lineno)+ if cell is None:+ raise CacheException(+ "Could not resolve cell for cache."+ f"{UNEXPECTED_FAILURE_BOILERPLATE}"+ )+ lineno -= cell.lineno+ code = cell.code+ elif cell_id in graph.cells:+ code = graph.cells[cell_id].code+ else:+ raise CacheException(+ "Could not resolve cell for cache."+ f"{UNEXPECTED_FAILURE_BOILERPLATE}"+ )+pre_module, save_module = CacheExtractWithBlock(lineno - 1).visit(- ast.parse(graph.cells[cell_id].code).body # type: ignore[arg-type]+ ast.parse(code).body # type: ignore[arg-type])self._cache = cache_attempt_from_hash(diff --git a/tests/_save/external_decorators/app.py b/tests/_save/external_decorators/app.pyindex 4d999919a8..7f07522fb0 100644--- a/tests/_save/external_decorators/app.py+++ b/tests/_save/external_decorators/app.py@@ -8,7 +8,7 @@ with app.setup:@app.cell-def _():+def decorator_wrap():@mo.cachedef cache(x):return x + 1@@ -17,5 +17,14 @@ def _():return (bar, cache)+def block_wrap(mo):+ with mo.cache("random"):+ x = []++ a = "need a final line to trigger invalid block capture"+ return (x,)++if __name__ == "__main__":app.run()diff --git a/tests/_save/test_external_decorators.py b/tests/_save/test_external_decorators.pyindex 0f18050067..6fe6264698 100644--- a/tests/_save/test_external_decorators.py+++ b/tests/_save/test_external_decorators.py@@ -282,6 +282,10 @@ class TestAsExternalApp:_, defs = ex_app.run()assert defs["bar"] == 2assert defs["cache"](1) == 2+ assert len(defs["x"]) == 0+ defs["x"].append(1)+ _, defs = ex_app.run()+ assert len(defs["x"]) == 1return@staticmethod