Skip to content

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.

refactor: move hooks into a container for less arg drilling (#8152)

Myles Scolnick2594ddc0c1f9
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 373b5b95ed..b85971dcf3 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -35,7 +35,7 @@ from marimo._runtime.commands import (
from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
-from marimo._runtime.runner.hooks_post_execution import render_toplevel_defs
+from marimo._runtime.runner.hooks import Priority, create_default_hooks
from marimo._runtime.runtime import Kernel
from marimo._runtime.utils.set_ui_element_request_manager import (
SetUIElementRequestManager,
@@ -446,14 +446,23 @@ def _launch_pyodide_kernel(
stdin = PyodideStdin(stream) if is_edit_mode else None
debugger = MarimoPdb(stdout=stdout, stdin=stdin) if is_edit_mode else None
- # Run mode kernels do not need additional rendering for toplevel defs
- render_hook = render_toplevel_defs if is_edit_mode else None
-
def _enqueue_control_request(req: CommandMessage) -> None:
control_queue.put_nowait(req)
if isinstance(req, UpdateUIElementCommand):
set_ui_element_queue.put_nowait(req)
+ # Create hooks with mode-specific configuration
+ from marimo._runtime.runner.hooks_post_execution import (
+ attempt_pytest,
+ render_toplevel_defs,
+ )
+
+ hooks = create_default_hooks()
+ if user_config["runtime"].get("reactive_tests", False):
+ hooks.add_post_execution(attempt_pytest, Priority.LATE)
+ if is_edit_mode:
+ hooks.add_post_execution(render_toplevel_defs, Priority.LATE)
+
kernel = Kernel(
cell_configs=configs,
app_metadata=app_metadata,
@@ -469,7 +478,7 @@ def _launch_pyodide_kernel(
enqueue_control_request=_enqueue_control_request,
debugger_override=debugger,
user_config=user_config,
- render_hook=render_hook,
+ hooks=hooks,
)
ctx = initialize_kernel_context(
kernel=kernel,
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index 568fcfea70..a258388e8a 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -70,6 +70,7 @@ class AppKernelRunner:
KernelRuntimeContext,
create_kernel_context,
)
+ from marimo._runtime.runner.hooks import NotebookCellHooks
from marimo._runtime.runner.hooks_post_execution import (
_reset_matplotlib_context,
)
@@ -103,6 +104,12 @@ class AppKernelRunner:
self.outputs[cell.cell_id] = run_result.output
filename = app.filename if app.filename is not None else "<unknown>"
+
+ # Create minimal hooks for embedded app execution
+ hooks = NotebookCellHooks()
+ hooks.add_post_execution(cache_output)
+ hooks.add_post_execution(_reset_matplotlib_context)
+
self._kernel = Kernel(
cell_configs={},
app_metadata=AppMetadata(
@@ -121,7 +128,7 @@ class AppKernelRunner:
),
user_config=DEFAULT_CONFIG,
enqueue_control_request=lambda _: None,
- post_execution_hooks=[cache_output, _reset_matplotlib_context],
+ hooks=hooks,
)
# We push a new runtime context onto the "stack", corresponding to this
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index a5d67fdccc..ba7b211060 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -13,7 +13,6 @@ from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Optional, Union
-from marimo._ast.cell import CellImpl
from marimo._ast.variables import unmangle_local
from marimo._config.config import ExecutionType, OnCellChangeType
from marimo._dependencies.dependencies import DependencyManager
@@ -49,15 +48,10 @@ from marimo._types.ids import CellId_t
LOGGER = marimo_logger()
if TYPE_CHECKING:
- from collections.abc import Iterator, Sequence
+ from collections.abc import Iterator
from marimo._runtime.context.types import ExecutionContext
- from marimo._runtime.runner.hooks_on_finish import OnFinishHookType
- from marimo._runtime.runner.hooks_post_execution import (
- PostExecutionHookType,
- )
- from marimo._runtime.runner.hooks_pre_execution import PreExecutionHookType
- from marimo._runtime.runner.hooks_preparation import PreparationHookType
+ from marimo._runtime.runner.hooks import NotebookCellHooks
from marimo._runtime.state import State
@@ -116,6 +110,7 @@ class Runner:
graph: dataflow.DirectedGraph,
glbls: dict[Any, Any],
debugger: MarimoPdb | None,
+ hooks: NotebookCellHooks,
execution_mode: OnCellChangeType = "autorun",
execution_type: ExecutionType = "relaxed",
excluded_cells: set[CellId_t] | None = None,
@@ -123,10 +118,6 @@ class Runner:
[CellId_t], contextlib._GeneratorContextManager[ExecutionContext]
]
| None = None,
- preparation_hooks: Sequence[PreparationHookType] | None = None,
- pre_execution_hooks: Sequence[PreExecutionHookType] | None = None,
- post_execution_hooks: Sequence[PostExecutionHookType] | None = None,
- on_finish_hooks: Sequence[OnFinishHookType] | None = None,
):
self.graph = graph
self.debugger = debugger
@@ -134,20 +125,8 @@ class Runner:
self._executor = get_executor(
ExecutionConfig(is_strict=execution_type == "strict")
)
- # injected context and hooks
self.execution_context = execution_context
- self.preparation_hooks: Sequence[Callable[[Runner], Any]] = (
- preparation_hooks or []
- )
- self.pre_execution_hooks: Sequence[
- Callable[[CellImpl, Runner], Any]
- ] = pre_execution_hooks or []
- self.post_execution_hooks: Sequence[
- Callable[[CellImpl, Runner, RunResult], Any]
- ] = post_execution_hooks or []
- self.on_finish_hooks: Sequence[Callable[[Runner], Any]] = (
- on_finish_hooks or []
- )
+ self._hooks = hooks
# runtime globals
self.glbls = glbls
@@ -669,7 +648,7 @@ class Runner:
async def run_all(self) -> None:
LOGGER.debug("Running preparation hooks")
- for prep_hook in self.preparation_hooks:
+ for prep_hook in self._hooks.preparation_hooks:
prep_hook(self)
while self.pending():
@@ -698,7 +677,7 @@ class Runner:
continue
LOGGER.debug("Running pre_execution hooks")
- for pre_hook in self.pre_execution_hooks:
+ for pre_hook in self._hooks.pre_execution_hooks:
pre_hook(cell, self)
LOGGER.debug("Running cell %s", cell_id)
if self.execution_context is not None:
@@ -709,7 +688,7 @@ class Runner:
run_result = await self.run(cell_id)
run_result.accumulated_output = exc_ctx.output
LOGGER.debug("Running post_execution hooks in context")
- for post_hook in self.post_execution_hooks:
+ for post_hook in self._hooks.post_execution_hooks:
post_hook(cell, self, run_result)
except KeyboardInterrupt:
LOGGER.error(
@@ -721,9 +700,9 @@ class Runner:
else:
run_result = await self.run(cell_id)
LOGGER.debug("Running post_execution hooks out of context")
- for post_hook in self.post_execution_hooks:
+ for post_hook in self._hooks.post_execution_hooks:
post_hook(cell, self, run_result)
LOGGER.debug("Running on_finish hooks")
- for finish_hook in self.on_finish_hooks:
+ for finish_hook in self._hooks.on_finish_hooks:
finish_hook(self)
diff --git a/marimo/_runtime/runner/hooks.py b/marimo/_runtime/runner/hooks.py
index 9825020b9d..b4dff2e414 100644
--- a/marimo/_runtime/runner/hooks.py
+++ b/marimo/_runtime/runner/hooks.py
@@ -1,19 +1,156 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import dataclass, field
+from enum import IntEnum
+from typing import TYPE_CHECKING, Callable
+
+if TYPE_CHECKING:
+ from collections.abc import Sequence
+
+ from marimo._ast.cell import CellImpl
+ from marimo._runtime.runner import cell_runner
+
__all__ = [
- # hooks to run before the runner starts running its subgraph
- "PREPARATION_HOOKS",
- # hooks to run right before each cell is run
- "PRE_EXECUTION_HOOKS",
- # hooks to run right after each cell is run
- "POST_EXECUTION_HOOKS",
- # hooks to run once the runner has finished executing its subgraph
- "ON_FINISH_HOOKS",
+ "NotebookCellHooks",
+ "Priority",
+ "PreparationHook",
+ "PreExecutionHook",
+ "PostExecutionHook",
+ "OnFinishHook",
+ "create_default_hooks",
+]
+
+# Hook type aliases
+PreparationHook = Callable[["cell_runner.Runner"], None]
+PreExecutionHook = Callable[["CellImpl", "cell_runner.Runner"], None]
+PostExecutionHook = Callable[
+ ["CellImpl", "cell_runner.Runner", "cell_runner.RunResult"], None
]
+OnFinishHook = Callable[["cell_runner.Runner"], None]
+
+
+class Priority(IntEnum):
+ """Hook execution priority (lower values run first)."""
+
+ EARLY = 0
+ NORMAL = 50
+ LATE = 90
+ FINAL = 100 # Reserved for status updates, cleanup
+
+
+@dataclass
+class _HookEntry:
+ """Internal wrapper for a hook with its priority."""
+
+ hook: Callable[..., None]
+ priority: Priority = Priority.NORMAL
+
+
+@dataclass
+class NotebookCellHooks:
+ """Container for cell execution hooks with priority-based ordering.
+
+ Hook lifecycle:
+ 1. preparation_hooks: Run once before the runner starts
+ 2. pre_execution_hooks: Run before each cell executes
+ 3. post_execution_hooks: Run after each cell executes
+ 4. on_finish_hooks: Run once after all cells complete
+ """
+
+ _preparation: list[_HookEntry] = field(default_factory=list)
+ _pre_execution: list[_HookEntry] = field(default_factory=list)
+ _post_execution: list[_HookEntry] = field(default_factory=list)
+ _on_finish: list[_HookEntry] = field(default_factory=list)
+
+ def add_preparation(
+ self, hook: PreparationHook, priority: Priority = Priority.NORMAL
+ ) -> None:
+ self._preparation.append(_HookEntry(hook, priority))
+
+ def add_pre_execution(
+ self, hook: PreExecutionHook, priority: Priority = Priority.NORMAL
+ ) -> None:
+ self._pre_execution.append(_HookEntry(hook, priority))
+
+ def add_post_execution(
+ self, hook: PostExecutionHook, priority: Priority = Priority.NORMAL
+ ) -> None:
+ self._post_execution.append(_HookEntry(hook, priority))
+
+ def add_on_finish(
+ self, hook: OnFinishHook, priority: Priority = Priority.NORMAL
+ ) -> None:
+ self._on_finish.append(_HookEntry(hook, priority))
+
+ @property
+ def preparation_hooks(self) -> Sequence[PreparationHook]:
+ return [
+ e.hook for e in sorted(self._preparation, key=lambda e: e.priority)
+ ]
+
+ @property
+ def pre_execution_hooks(self) -> Sequence[PreExecutionHook]:
+ return [
+ e.hook
+ for e in sorted(self._pre_execution, key=lambda e: e.priority)
+ ]
+
+ @property
+ def post_execution_hooks(self) -> Sequence[PostExecutionHook]:
+ return [
+ e.hook
+ for e in sorted(self._post_execution, key=lambda e: e.priority)
+ ]
+
+ @property
+ def on_finish_hooks(self) -> Sequence[OnFinishHook]:
+ return [
+ e.hook for e in sorted(self._on_finish, key=lambda e: e.priority)
+ ]
+
+ def copy(self) -> NotebookCellHooks:
+ return NotebookCellHooks(
+ _preparation=self._preparation.copy(),
+ _pre_execution=self._pre_execution.copy(),
+ _post_execution=self._post_execution.copy(),
+ _on_finish=self._on_finish.copy(),
+ )
+
+
+def create_default_hooks() -> NotebookCellHooks:
+ """Create hooks with standard defaults.
+
+ Returns a NotebookCellHooks instance with all standard hooks registered.
+ Callers should add mode-specific hooks (e.g., render_toplevel_defs for
+ edit mode, attempt_pytest for reactive tests) after calling this.
+ """
+ from marimo._runtime.runner.hooks_on_finish import (
+ _send_cancellation_errors,
+ _send_interrupt_errors,
+ )
+ from marimo._runtime.runner.hooks_post_execution import (
+ POST_EXECUTION_HOOKS,
+ )
+ from marimo._runtime.runner.hooks_pre_execution import (
+ PRE_EXECUTION_HOOKS,
+ )
+ from marimo._runtime.runner.hooks_preparation import (
+ PREPARATION_HOOKS,
+ )
+
+ hooks = NotebookCellHooks()
+
+ for prep_hook in PREPARATION_HOOKS:
+ hooks.add_preparation(prep_hook)
+
+ for pre_hook in PRE_EXECUTION_HOOKS:
+ hooks.add_pre_execution(pre_hook)
+
+ for post_hook in POST_EXECUTION_HOOKS:
+ hooks.add_post_execution(post_hook)
+ hooks.add_on_finish(_send_interrupt_errors)
+ hooks.add_on_finish(_send_cancellation_errors)
-from marimo._runtime.runner.hooks_on_finish import ON_FINISH_HOOKS
-from marimo._runtime.runner.hooks_post_execution import POST_EXECUTION_HOOKS
-from marimo._runtime.runner.hooks_pre_execution import PRE_EXECUTION_HOOKS
-from marimo._runtime.runner.hooks_preparation import PREPARATION_HOOKS
+ return hooks
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index ce9c68c455..181bb94be4 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -165,18 +165,10 @@ from marimo._runtime.reload.autoreload import ModuleReloader
from marimo._runtime.reload.module_watcher import ModuleWatcher
from marimo._runtime.runner import cell_runner
from marimo._runtime.runner.hooks import (
- ON_FINISH_HOOKS,
- POST_EXECUTION_HOOKS,
- PRE_EXECUTION_HOOKS,
- PREPARATION_HOOKS,
+ NotebookCellHooks,
+ Priority,
+ create_default_hooks,
)
-from marimo._runtime.runner.hooks_on_finish import OnFinishHookType
-from marimo._runtime.runner.hooks_post_execution import (
- PostExecutionHookType,
- render_toplevel_defs,
-)
-from marimo._runtime.runner.hooks_pre_execution import PreExecutionHookType
-from marimo._runtime.runner.hooks_preparation import PreparationHookType
from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._runtime.state import State
from marimo._runtime.utils.set_ui_element_request_manager import (
@@ -505,11 +497,7 @@ class Kernel:
stdin: Stdin | None,
module: ModuleType,
enqueue_control_request: Callable[[CommandMessage], None],
- preparation_hooks: list[PreparationHookType] | None = None,
- pre_execution_hooks: list[PreExecutionHookType] | None = None,
- post_execution_hooks: list[PostExecutionHookType] | None = None,
- on_finish_hooks: list[OnFinishHookType] | None = None,
- render_hook: PostExecutionHookType | None = None,
+ hooks: NotebookCellHooks,
debugger_override: marimo_pdb.MarimoPdb | None = None,
) -> None:
self.app_metadata = app_metadata
@@ -553,39 +541,10 @@ class Kernel:
if path not in sys.path:
sys.path.insert(0, path)
- self._preparation_hooks = (
- preparation_hooks
- if preparation_hooks is not None
- else PREPARATION_HOOKS
- )
- self._pre_execution_hooks = (
- pre_execution_hooks
- if pre_execution_hooks is not None
- else PRE_EXECUTION_HOOKS
- )
- self._post_execution_hooks = (
- post_execution_hooks
- if post_execution_hooks is not None
- else POST_EXECUTION_HOOKS
- )
- self._on_finish_hooks = (
- on_finish_hooks if on_finish_hooks is not None else ON_FINISH_HOOKS
- )
+ self._hooks = hooks
self._original_environ = os.environ.copy()
- # Adds in a post_execution hook to run pytest immediately
- if user_config["runtime"].get("reactive_tests", False):
- from marimo._runtime.runner.hooks_post_execution import (
- attempt_pytest,
- )
-
- self._post_execution_hooks.append(attempt_pytest)
-
- # Must be last to properly trigger render.
- if render_hook is not None:
- self._post_execution_hooks.append(render_hook)
-
self._globals_lock = threading.RLock()
self._state_lock = threading.RLock()
self._completion_worker_started = False
@@ -1422,7 +1381,7 @@ class Kernel:
Returns set of cells that need to be re-run due to state updates.
"""
- # Some hooks that are leaky and require the kernel
+ # Some hooks are leaky and require the kernel
# Free cell state ahead of running to relieve memory pressure
#
# NB: lazy kernels don't invalidate state of cancelled cells
@@ -1443,6 +1402,13 @@ class Kernel:
if isinstance(run_result.exception, MarimoInterrupt):
self.last_interrupt_timestamp = time.time()
+ # Copy hooks and add run-specific hooks
+ run_hooks = self._hooks.copy()
+ run_hooks.add_preparation(invalidate_state)
+ run_hooks.add_post_execution(note_time_of_interruption, Priority.LATE)
+ run_hooks.add_on_finish(self.packages_callbacks.missing_packages_hook)
+ run_hooks.add_on_finish(self._propagate_kernel_errors)
+
# Rebuild graph with sourceful positions
# Note, this is relatively expensive, but a reasonable tradeoff
graph = self.graph
@@ -1458,17 +1424,7 @@ class Kernel:
execution_mode=self.reactive_execution_mode,
execution_type=self.execution_type,
execution_context=self._install_execution_context,
- preparation_hooks=self._preparation_hooks + [invalidate_state],
- pre_execution_hooks=self._pre_execution_hooks,
- post_execution_hooks=self._post_execution_hooks
- + [note_time_of_interruption],
- on_finish_hooks=(
- self._on_finish_hooks
- + [
- self.packages_callbacks.missing_packages_hook,
- self._propagate_kernel_errors,
- ]
- ),
+ hooks=run_hooks,
)
# I/O
@@ -1729,6 +1685,12 @@ class Kernel:
graph = dataflow.DirectedGraph()
graph.register_cell(SCRATCH_CELL_ID, cell)
+ # Copy hooks and add scratchpad-specific hooks
+ scratchpad_hooks = self._hooks.copy()
+ scratchpad_hooks.add_on_finish(
+ self.packages_callbacks.missing_packages_hook
+ )
+
runner = cell_runner.Runner(
roots=roots,
graph=graph,
@@ -1738,13 +1700,7 @@ class Kernel:
execution_mode=self.reactive_execution_mode,
execution_type=self.execution_type,
execution_context=self._install_execution_context,
- preparation_hooks=self._preparation_hooks,
- pre_execution_hooks=self._pre_execution_hooks,
- post_execution_hooks=self._post_execution_hooks,
- on_finish_hooks=(
- self._on_finish_hooks
- + [self.packages_callbacks.missing_packages_hook]
- ),
+ hooks=scratchpad_hooks,
)
await runner.run_all()
@@ -3233,9 +3189,6 @@ def launch_kernel(
else None
)
- # Run mode kernels do not need additional rendering for toplevel defs
- render_hook = render_toplevel_defs if is_edit_mode else None
-
# In run mode, the kernel should always be in autorun, and the module
# autoreloader is disabled
if not is_edit_mode:
@@ -3248,6 +3201,18 @@ def launch_kernel(
if isinstance(req, UpdateUIElementCommand):
set_ui_element_queue.put_nowait(req)
+ # Create hooks with mode-specific configuration
+ from marimo._runtime.runner.hooks_post_execution import (
+ attempt_pytest,
+ render_toplevel_defs,
+ )
+
+ hooks = create_default_hooks()
+ if user_config["runtime"].get("reactive_tests", False):
+ hooks.add_post_execution(attempt_pytest, Priority.LATE)
+ if is_edit_mode:
+ hooks.add_post_execution(render_toplevel_defs, Priority.LATE)
+
kernel = Kernel(
cell_configs=configs,
app_metadata=app_metadata,
@@ -3263,7 +3228,7 @@ def launch_kernel(
debugger_override=debugger,
user_config=user_config,
enqueue_control_request=_enqueue_control_request,
- render_hook=render_hook,
+ hooks=hooks,
)
ctx = initialize_kernel_context(
kernel=kernel,
diff --git a/tests/_runtime/runner/test_cell_runner.py b/tests/_runtime/runner/test_cell_runner.py
index 2aa8b7c25c..e24d6aeba9 100644
--- a/tests/_runtime/runner/test_cell_runner.py
+++ b/tests/_runtime/runner/test_cell_runner.py
@@ -7,6 +7,7 @@ from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.errors import MarimoSQLError
from marimo._runtime.capture import capture_stderr
from marimo._runtime.runner.cell_runner import Runner
+from marimo._runtime.runner.hooks import NotebookCellHooks
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
@@ -23,6 +24,7 @@ async def test_cell_output(
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
+ hooks=NotebookCellHooks(),
)
run_result = await runner.run(er.cell_id)
# last expression of cell is output
@@ -55,6 +57,7 @@ async def test_traceback_includes_lineno(
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
+ hooks=NotebookCellHooks(),
)
with capture_stderr() as buffer:
await runner.run(er.cell_id)
@@ -93,6 +96,7 @@ async def test_base_exception_caught(
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
+ hooks=NotebookCellHooks(),
)
with capture_stderr() as buffer:
await runner.run(er.cell_id)
@@ -129,6 +133,7 @@ raise ParseError("malformed SQL")
graph=k.graph,
glbls=k.globals,
debugger=k.debugger,
+ hooks=NotebookCellHooks(),
)
with capture_stderr() as buffer:
diff --git a/tests/_runtime/runner/test_hooks.py b/tests/_runtime/runner/test_hooks.py
new file mode 100644
index 0000000000..b18a9c538a
--- /dev/null
+++ b/tests/_runtime/runner/test_hooks.py
@@ -0,0 +1,74 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import pytest
+
+from marimo._runtime.runner.hooks import (
+ NotebookCellHooks,
+ Priority,
+ create_default_hooks,
+)
+
+
+def hooks() -> NotebookCellHooks:
+ return NotebookCellHooks()
+
+
+class TestNotebookCellHooks:
+ def test_add_and_retrieve(self, hooks: NotebookCellHooks) -> None:
+ hook = lambda _: None # noqa: E731
+ hooks.add_preparation(hook)
+ assert hook in hooks.preparation_hooks
+
+ def test_priority_ordering(self, hooks: NotebookCellHooks) -> None:
+ order: list[str] = []
+
+ hooks.add_post_execution(
+ lambda _c, _r, _res: order.append("late"), Priority.LATE
+ )
+ hooks.add_post_execution(
+ lambda _c, _r, _res: order.append("early"), Priority.EARLY
+ )
+ hooks.add_post_execution(
+ lambda _c, _r, _res: order.append("final"), Priority.FINAL
+ )
+ hooks.add_post_execution(lambda _c, _r, _res: order.append("normal"))
+
+ for hook in hooks.post_execution_hooks:
+ hook(None, None, None) # type: ignore
+
+ assert order == ["early", "normal", "late", "final"]
+
+ def test_copy_is_independent(self, hooks: NotebookCellHooks) -> None:
+ hook1 = lambda _: None # noqa: E731
+ hooks.add_preparation(hook1)
+
+ hooks_copy = hooks.copy()
+ hook2 = lambda _: None # noqa: E731
+ hooks_copy.add_preparation(hook2)
+
+ assert len(hooks.preparation_hooks) == 1
+ assert len(hooks_copy.preparation_hooks) == 2
+
+
+class TestCreateDefaultHooks:
+ def test_creates_all_hook_types(self) -> None:
+ hooks = create_default_hooks()
+ assert len(hooks.preparation_hooks) > 0
+ assert len(hooks.pre_execution_hooks) > 0
+ assert len(hooks.post_execution_hooks) > 0
+ assert len(hooks.on_finish_hooks) > 0
+
+ def test_set_status_idle_is_last_post_execution_hook(self) -> None:
+ """Verify _set_status_idle is the last hook in POST_EXECUTION_HOOKS.
+
+ This is important because status should only be set to idle after all
+ other post-execution work (like broadcasting outputs) is complete.
+ """
+ from marimo._runtime.runner.hooks_post_execution import (
+ POST_EXECUTION_HOOKS,
+ _set_status_idle,
+ )
+
+ assert POST_EXECUTION_HOOKS[-1] is _set_status_idle
diff --git a/tests/_runtime/test_control_flow.py b/tests/_runtime/test_control_flow.py
index b5362d7bcc..aee5485c8d 100644
--- a/tests/_runtime/test_control_flow.py
+++ b/tests/_runtime/test_control_flow.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from marimo._runtime import control_flow
from marimo._runtime.commands import ExecuteCellCommand
from marimo._runtime.runner import cell_runner
+from marimo._runtime.runner.hooks import NotebookCellHooks
from marimo._runtime.runtime import Kernel
@@ -66,7 +67,11 @@ async def test_stop_output(execution_kernel: Kernel) -> None:
)
# Run the cell through the runner to get the output
runner = cell_runner.Runner(
- set(["0"]), graph=k.graph, glbls=k.globals, debugger=k.debugger
+ set(["0"]),
+ graph=k.graph,
+ glbls=k.globals,
+ debugger=k.debugger,
+ hooks=NotebookCellHooks(),
)
run_result = await runner.run("0")
# Check that the cell was stopped and its output is the stop output
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 3c57e901e6..76387d0dd5 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -43,6 +43,7 @@ from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.context.types import teardown_context
from marimo._runtime.dataflow import EdgeWithVar
from marimo._runtime.patches import create_main_module
+from marimo._runtime.runner.hooks import create_default_hooks
from marimo._runtime.runtime import Kernel, notebook_dir, notebook_location
from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._session.model import SessionMode
@@ -1359,6 +1360,7 @@ except NameError:
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
+ hooks=create_default_hooks(),
)
initialize_kernel_context(
kernel=k,
@@ -1424,6 +1426,7 @@ except NameError:
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
+ hooks=create_default_hooks(),
)
assert str(tmp_path) in sys.path
assert str(tmp_path) == sys.path[0]
@@ -1451,6 +1454,7 @@ except NameError:
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
+ hooks=create_default_hooks(),
)
assert len(sys.argv) == 3
@@ -1484,6 +1488,7 @@ except NameError:
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
+ hooks=create_default_hooks(),
)
assert argv == sys.argv
finally:
@@ -1521,6 +1526,7 @@ except NameError:
),
enqueue_control_request=lambda _: None,
module=create_main_module(None, None, None),
+ hooks=create_default_hooks(),
)
initialize_kernel_context(
kernel=k,
diff --git a/tests/conftest.py b/tests/conftest.py
index c8446d8852..13e56da1f2 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -38,6 +38,7 @@ from marimo._runtime.context import teardown_context
from marimo._runtime.context.kernel_context import initialize_kernel_context
from marimo._runtime.input_override import input_override
from marimo._runtime.marimo_pdb import MarimoPdb
+from marimo._runtime.runner.hooks import create_default_hooks
from marimo._runtime.runtime import Kernel
from marimo._save.stubs.module_stub import ModuleStub
from marimo._server.utils import initialize_mimetypes
@@ -209,6 +210,7 @@ class MockedKernel:
debugger_override=MarimoPdb(stdout=self.stdout, stdin=self.stdin),
enqueue_control_request=lambda _: None,
module=module,
+ hooks=create_default_hooks(),
)
initialize_kernel_context(