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
chore: cleanup executor, prefer composition (#4783)
Myles Scolnickb071f90f812e
diff --git a/marimo/_ast/variables.py b/marimo/_ast/variables.pyindex db70142195..8f19a4efe6 100644--- a/marimo/_ast/variables.py+++ b/marimo/_ast/variables.py@@ -3,12 +3,15 @@ from __future__ import annotationsimport builtinsimport re-from collections import namedtuple-from typing import Optional+from typing import NamedTuple, Optionalfrom marimo._types.ids import CellId_t-UnmagledLocal = namedtuple("UnmagledLocal", "name cell")++class UnmagledLocal(NamedTuple):+ name: str+ cell: CellId_t+_EMPTY_CELL_ID = CellId_t("")@@ -36,11 +39,13 @@ def unmangle_local(name: str, cell_id: CellId_t = _EMPTY_CELL_ID) -> UnmagledLocal:if not is_mangled_local(name, cell_id):- return UnmagledLocal(name, "")+ return UnmagledLocal(name, CellId_t(""))private_prefix = r"^_cell_\w+?_"if cell_id:private_prefix = f"^_cell_{cell_id}_"- return UnmagledLocal(re.sub(private_prefix, "_", name), name.split("_")[2])+ return UnmagledLocal(+ re.sub(private_prefix, "_", name), CellId_t(name.split("_")[2])+ )def is_mangled_local(name: str, cell_id: CellId_t = _EMPTY_CELL_ID) -> bool:diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.pyindex 8caaa282fb..0456b2f133 100644--- a/marimo/_runtime/app/script_runner.py+++ b/marimo/_runtime/app/script_runner.py@@ -20,8 +20,8 @@ from marimo._runtime.exceptions import (MarimoRuntimeException,)from marimo._runtime.executor import (- execute_cell,- execute_cell_async,+ ExecutionConfig,+ get_executor,)from marimo._runtime.patches import (create_main_module,@@ -52,6 +52,7 @@ class AppScriptRunner:if app.cell_manager.cell_data_at(cid).cell is not Noneand not self.app.graph.is_disabled(cid)]+ self._executor = get_executor(ExecutionConfig())def _cancel(self, cell_id: CellId_t) -> None:self.cells_cancelled[cell_id] = set(@@ -87,7 +88,9 @@ class AppScriptRunner:cell = self.app.graph.cells[cid]with get_context().with_cell_id(cid):try:- output = execute_cell(cell, glbls, self.app.graph)+ output = self._executor.execute_cell(+ cell, glbls, self.app.graph+ )outputs[cid] = outputexcept MarimoRuntimeException as e:unwrapped_exception: BaseException | None = e.__cause__@@ -124,7 +127,7 @@ class AppScriptRunner:cell = self.app.graph.cells[cid]with get_context().with_cell_id(cid):try:- output = await execute_cell_async(+ output = await self._executor.execute_cell_async(cell, glbls, self.app.graph)outputs[cid] = outputdiff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex 1545e29148..8e7076adb2 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -13,7 +13,10 @@ from marimo._ast.cell import (from marimo._ast.compiler import code_keyfrom marimo._ast.variables import is_mangled_localfrom marimo._ast.visitor import ImportData, Name, VariableData-from marimo._runtime.executor import execute_cell, execute_cell_async+from marimo._runtime.executor import (+ ExecutionConfig,+ get_executor,+)from marimo._types.ids import CellId_tif TYPE_CHECKING:@@ -176,7 +179,7 @@ class DirectedGraph:self.parents[child].add(cell_id)for name in cell.refs:- other_ids_defining_name = (+ other_ids_defining_name: set[CellId_t] = (self.definitions[name]if name in self.definitionselse set()@@ -339,14 +342,14 @@ class DirectedGraph:return importsdef get_multiply_defined(self) -> list[Name]:- names = []+ names: list[Name] = []for name, definers in self.definitions.items():if len(definers) > 1:names.append(name)return namesdef get_deleted_nonlocal_ref(self) -> list[Name]:- names = []+ names: list[Name] = []for cell in self.cells.values():for ref in cell.deleted_refs:if ref in self.definitions:@@ -594,6 +597,7 @@ class Runner:def __init__(self, graph: DirectedGraph) -> None:self._graph = graph+ self._executor = get_executor(ExecutionConfig())@staticmethoddef _returns(cell_impl: CellImpl, glbls: dict[str, Any]) -> dict[str, Any]:@@ -662,10 +666,12 @@ class Runner:glbls: dict[str, Any] = {}for cid in topological_sort(graph, ancestor_ids):- await execute_cell_async(graph.cells[cid], glbls, graph)+ await self._executor.execute_cell_async(+ graph.cells[cid], glbls, graph+ )Runner._substitute_refs(cell_impl, glbls, kwargs)- output = await execute_cell_async(+ output = await self._executor.execute_cell_async(graph.cells[cell_impl.cell_id], glbls, graph)defs = Runner._returns(cell_impl, glbls)@@ -701,9 +707,11 @@ class Runner:glbls: dict[str, Any] = {}for cid in topological_sort(graph, ancestor_ids):- execute_cell(graph.cells[cid], glbls, graph)+ self._executor.execute_cell(graph.cells[cid], glbls, graph)self._substitute_refs(cell_impl, glbls, kwargs)- output = execute_cell(graph.cells[cell_impl.cell_id], glbls, graph)+ output = self._executor.execute_cell(+ graph.cells[cell_impl.cell_id], glbls, graph+ )defs = Runner._returns(cell_impl, glbls)return output, defsdiff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.pyindex e41d0d80c0..197d4879a7 100644--- a/marimo/_runtime/executor.py+++ b/marimo/_runtime/executor.py@@ -5,7 +5,8 @@ import inspectimport refrom abc import ABC, abstractmethodfrom copy import deepcopy-from typing import TYPE_CHECKING, Any, Callable, Optional+from dataclasses import dataclass+from typing import TYPE_CHECKING, Any, Optionalfrom marimo._ast.cell import CellImpl, _is_coroutinefrom marimo._ast.variables import is_mangled_local, unmangle_local@@ -31,10 +32,14 @@ if TYPE_CHECKING:from marimo._runtime.dataflow import DirectedGraph-EXECUTION_TYPES: dict[str, type[Executor]] = {}+@dataclass+class ExecutionConfig:+ """Configuration for cell execution."""+ is_strict: bool = False-def raise_name_error(++def _raise_name_error(graph: Optional[DirectedGraph], name_error: NameError) -> None:if graph is None:@@ -48,50 +53,27 @@ def raise_name_error(raise MarimoRuntimeException from name_error-def register_execution_type(- key: str,-) -> Callable[[type[Executor]], type[Executor]]:- # Potentially expose as part of custom kernel API- def wrapper(cls: type[Executor]) -> type[Executor]:- EXECUTION_TYPES[key] = cls- return cls-- return wrapper---async def execute_cell_async(- cell: CellImpl,- glbls: dict[str, Any],- graph: DirectedGraph,- execution_type: str = "relaxed",-) -> Any:- return await EXECUTION_TYPES[execution_type].execute_cell_async(- cell, glbls, graph- )---def execute_cell(- cell: CellImpl,- glbls: dict[str, Any],- graph: DirectedGraph,- execution_type: str = "relaxed",-) -> Any:- return EXECUTION_TYPES[execution_type].execute_cell(cell, glbls, graph)+def get_executor(config: ExecutionConfig) -> Executor:+ """Get a code executor based on the execution configuration."""+ base = DefaultExecutor()+ if config.is_strict:+ return StrictExecutor(base)+ return baseclass Executor(ABC):- @staticmethod@abstractmethoddef execute_cell(+ self,cell: CellImpl,glbls: dict[str, Any],graph: DirectedGraph,) -> Any:pass- @staticmethod@abstractmethodasync def execute_cell_async(+ self,cell: CellImpl,glbls: dict[str, Any],graph: DirectedGraph,@@ -99,10 +81,9 @@ class Executor(ABC):pass-@register_execution_type("relaxed")class DefaultExecutor(Executor):- @staticmethodasync def execute_cell_async(+ self,cell: CellImpl,glbls: dict[str, Any],graph: Optional[DirectedGraph] = None,@@ -121,14 +102,14 @@ class DefaultExecutor(Executor):else:return eval(cell.last_expr, glbls)except NameError as e:- raise_name_error(graph, e)+ _raise_name_error(graph, e)except (BaseException, Exception) as e:# Raising from a BaseException will fold in the stacktrace prior# to executionraise MarimoRuntimeException from e- @staticmethoddef execute_cell(+ self,cell: CellImpl,glbls: dict[str, Any],graph: Optional[DirectedGraph] = None,@@ -141,16 +122,20 @@ class DefaultExecutor(Executor):exec(cell.body, glbls)return eval(cell.last_expr, glbls)except NameError as e:- raise_name_error(graph, e)+ _raise_name_error(graph, e)except (BaseException, Exception) as e:raise MarimoRuntimeException from e-@register_execution_type("strict")class StrictExecutor(Executor):- @staticmethod+ def __init__(self, base: Executor):+ self.base = base+async def execute_cell_async(- cell: CellImpl, glbls: dict[str, Any], graph: DirectedGraph+ self,+ cell: CellImpl,+ glbls: dict[str, Any],+ graph: DirectedGraph,) -> Any:# Manage globals and references, but refers to the default beyond that.refs = graph.get_transitive_references(@@ -159,19 +144,19 @@ class StrictExecutor(Executor):glbls, CLONE_PRIMITIVES),)- backup = StrictExecutor.sanitize_inputs(cell, refs, glbls)+ backup = self._sanitize_inputs(cell, refs, glbls)try:- response = await DefaultExecutor.execute_cell_async(- cell, glbls, graph- )+ response = await self.base.execute_cell_async(cell, glbls, graph)finally:# Restore globals from backup and backfill outputs- StrictExecutor.update_outputs(cell, glbls, backup)+ self._update_outputs(cell, glbls, backup)return response- @staticmethoddef execute_cell(- cell: CellImpl, glbls: dict[str, Any], graph: DirectedGraph+ self,+ cell: CellImpl,+ glbls: dict[str, Any],+ graph: DirectedGraph,) -> Any:refs = graph.get_transitive_references(cell.refs,@@ -179,16 +164,18 @@ class StrictExecutor(Executor):glbls, CLONE_PRIMITIVES),)- backup = StrictExecutor.sanitize_inputs(cell, refs, glbls)+ backup = self._sanitize_inputs(cell, refs, glbls)try:- response = DefaultExecutor.execute_cell(cell, glbls, graph)+ response = self.base.execute_cell(cell, glbls, graph)finally:- StrictExecutor.update_outputs(cell, glbls, backup)+ self._update_outputs(cell, glbls, backup)return response- @staticmethod- def sanitize_inputs(- cell: CellImpl, refs: set[str], glbls: dict[str, Any]+ def _sanitize_inputs(+ self,+ cell: CellImpl,+ refs: set[str],+ glbls: dict[str, Any],) -> dict[str, Any]:# Some attributes should remain globallcls = {@@ -254,9 +241,11 @@ class StrictExecutor(Executor):glbls.update(lcls)return backup- @staticmethod- def update_outputs(- cell: CellImpl, glbls: dict[str, Any], backup: dict[str, Any]+ def _update_outputs(+ self,+ cell: CellImpl,+ glbls: dict[str, Any],+ backup: dict[str, Any],) -> None:# NOTE: After execution, restore global state and update outputs.lcls = {**glbls}diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.pyindex 35b13a8c16..5594872564 100644--- a/marimo/_runtime/runner/cell_runner.py+++ b/marimo/_runtime/runner/cell_runner.py@@ -33,8 +33,8 @@ from marimo._runtime.exceptions import (MarimoRuntimeException,)from marimo._runtime.executor import (- execute_cell,- execute_cell_async,+ ExecutionConfig,+ get_executor,)from marimo._runtime.marimo_pdb import MarimoPdbfrom marimo._types.ids import CellId_t@@ -100,7 +100,9 @@ class Runner:self.graph = graphself.debugger = debuggerself.excluded_cells = excluded_cells or set()-+ self._executor = get_executor(+ ExecutionConfig(is_strict=execution_type == "strict")+ )# injected context and hooksself.execution_context = execution_contextself.preparation_hooks: Sequence[Callable[[Runner], Any]] = (@@ -327,11 +329,10 @@ class Runner:try:if cell.is_coroutine():return_value_future = asyncio.ensure_future(- execute_cell_async(+ self._executor.execute_cell_async(cell,self.glbls,self.graph,- execution_type=self.execution_type,))if threading.current_thread() == threading.main_thread():@@ -343,11 +344,10 @@ class Runner:# by user anyway.return_value = await return_value_futureelse:- return_value = execute_cell(+ return_value = self._executor.execute_cell(cell,self.glbls,self.graph,- execution_type=self.execution_type,)run_result = RunResult(output=return_value, exception=None)except asyncio.exceptions.CancelledError: