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
Cell lifecycle (#178)
Akshay Agrawale0063b5a9f42
diff --git a/marimo/_plugins/stateless/mpl/_mpl.py b/marimo/_plugins/stateless/mpl/_mpl.pyindex 6b12c5ba86..b9a0f0f9db 100644--- a/marimo/_plugins/stateless/mpl/_mpl.py+++ b/marimo/_plugins/stateless/mpl/_mpl.py@@ -13,7 +13,6 @@ import jsonimport mimetypesimport socketimport threading-from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Optional@@ -24,11 +23,11 @@ import tornado.netutilimport tornado.webimport tornado.websocket-from marimo._ast.cell import CellId_tfrom marimo._output.builder import hfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc-from marimo._runtime.context import get_context+from marimo._runtime.cell_lifecycle_item import CellLifecycleItem+from marimo._runtime.context import RuntimeContext, get_contextclass MplApplication(tornado.web.Application):@@ -185,37 +184,19 @@ class MplApplication(tornado.web.Application):)-@dataclass-class CleanupHandle:+class CleanupHandle(CellLifecycleItem):"""Handle to shutdown a figure server."""shutdown_event: Optional[asyncio.Event] = None+ def create(self, context: RuntimeContext) -> None:+ del context+ pass-class InteractiveMplRegistry:- """Registry of figures created by each cell.-- Allows the kernel to tear down all figures for a given cell.- """-- _registry: dict[CellId_t, list[CleanupHandle]] = {}-- def register(- self, cell_id: CellId_t, cleanup_handle: CleanupHandle- ) -> None:- """Register a figure's cleanup handle for a cell."""- if cell_id not in self._registry:- self._registry[cell_id] = [cleanup_handle]- else:- self._registry[cell_id].append(cleanup_handle)-- def cleanup(self, cell_id: CellId_t) -> None:- """Tear down figures for a cell."""- if cell_id in self._registry:- for cleanup_handle in self._registry[cell_id]:- if cleanup_handle.shutdown_event is not None:- cleanup_handle.shutdown_event.set()- del self._registry[cell_id]+ def dispose(self, context: RuntimeContext) -> None:+ del context+ if self.shutdown_event is not None:+ self.shutdown_event.set()@mddoc@@ -280,11 +261,7 @@ def interactive(figure: "Figure | Axes") -> Html: # type: ignore[name-defined]raise RuntimeError("Failed to create sockets for mpl.interactive.")assert ctx.kernel.execution_context is not None- ctx.interactive_mpl_registry.register(- cell_id=ctx.kernel.execution_context.cell_id,- cleanup_handle=cleanup_handle,- )-+ ctx.cell_lifecycle_registry.add(cleanup_handle)threading.Thread(target=start_server).start()return Html(h.iframe(diff --git a/marimo/_runtime/cell_lifecycle_item.py b/marimo/_runtime/cell_lifecycle_item.pynew file mode 100644index 0000000000..a8edb31712--- /dev/null+++ b/marimo/_runtime/cell_lifecycle_item.py@@ -0,0 +1,18 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import abc+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from marimo._runtime.context import RuntimeContext+++class CellLifecycleItem(abc.ABC):+ @abc.abstractmethod+ def create(self, context: "RuntimeContext") -> None:+ ...++ @abc.abstractmethod+ def dispose(self, context: "RuntimeContext") -> None:+ ...diff --git a/marimo/_runtime/cell_lifecycle_registry.py b/marimo/_runtime/cell_lifecycle_registry.pynew file mode 100644index 0000000000..34bd69b7d0--- /dev/null+++ b/marimo/_runtime/cell_lifecycle_registry.py@@ -0,0 +1,45 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import dataclasses++from marimo._ast.cell import CellId_t+from marimo._runtime.cell_lifecycle_item import CellLifecycleItem+++class CellLifecycleRegistry:+ registry: dict[CellId_t, set[CellLifecycleItem]] = dataclasses.field(+ default_factory=dict+ )++ def add(self, item: CellLifecycleItem) -> None:+ """Add a lifecycle item for the currently running cell.++ Calls the item's create method upon adding. No-op if no cell+ is running.+ """+ from marimo._runtime.context import get_context++ ctx = get_context()+ cell_id = ctx.cell_id+ if cell_id is None:+ return++ if cell_id not in self.registry:+ self.registry[cell_id] = set()+ item.create(ctx)+ self.registry[cell_id].add(item)++ def dispose(self, cell_id: CellId_t) -> None:+ """Dispose lifecycle items associated with `cell_id`++ Calls `dispose` hooks and clears items from the registry.+ """+ from marimo._runtime.context import get_context++ ctx = get_context()+ if cell_id in self.registry:+ for lifecycle_item in self.registry[cell_id]:+ lifecycle_item.dispose(context=ctx)+ del self.registry[cell_id]diff --git a/marimo/_runtime/conftest.py b/marimo/_runtime/conftest.pyindex 1ed1fa53b7..25fe978321 100644--- a/marimo/_runtime/conftest.py+++ b/marimo/_runtime/conftest.py@@ -8,11 +8,12 @@ from typing import Any, Generatorimport pytestfrom marimo._ast.cell import CellId_t-from marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistry+from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistryfrom marimo._runtime.context import get_contextfrom marimo._runtime.requests import ExecutionRequestfrom marimo._runtime.runtime import Kernel+from marimo._runtime.virtual_file import VirtualFileRegistry@dataclasses.dataclass@@ -44,7 +45,8 @@ class MockedKernel:get_context().initialize(kernel=self.k,ui_element_registry=UIElementRegistry(),- interactive_mpl_registry=InteractiveMplRegistry(),+ cell_lifecycle_registry=CellLifecycleRegistry(),+ virtual_file_registry=VirtualFileRegistry(),stream=self.stream, # type: ignorestdout=self.stdout, # type: ignorestderr=self.stderr, # type: ignorediff --git a/marimo/_runtime/context.py b/marimo/_runtime/context.pyindex 9707056fcd..20f6ee00e0 100644--- a/marimo/_runtime/context.py+++ b/marimo/_runtime/context.py@@ -12,12 +12,14 @@ from contextlib import contextmanagerfrom typing import TYPE_CHECKING, Iterator, Optionalfrom marimo._plugins.ui._core.ids import IDProvider, NoIDProviderException+from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistryif TYPE_CHECKING:+ from marimo._ast.cell import CellId_tfrom marimo._messaging.streams import Stderr, Stdout, Stream- from marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._runtime.runtime import Kernel+ from marimo._runtime.virtual_file import VirtualFileRegistryclass GlobalContext:@@ -47,6 +49,8 @@ class RuntimeContext(threading.local):def __init__(self) -> None:self._kernel: Optional[Kernel] = Noneself._ui_element_registry: Optional[UIElementRegistry] = None+ self._cell_lifecycle_items: Optional[CellLifecycleRegistry] = None+ self._virtual_file_registry: Optional[VirtualFileRegistry] = Noneself._stream: Optional[Stream] = Noneself._stdout: Optional[Stdout] = Noneself._stderr: Optional[Stderr] = None@@ -57,14 +61,16 @@ class RuntimeContext(threading.local):self,kernel: Kernel,ui_element_registry: UIElementRegistry,- interactive_mpl_registry: InteractiveMplRegistry,+ cell_lifecycle_registry: CellLifecycleRegistry,+ virtual_file_registry: VirtualFileRegistry,stream: Stream,stdout: Optional[Stdout],stderr: Optional[Stderr],) -> None:self._kernel = kernelself._ui_element_registry = ui_element_registry- self._interactive_mpl_registry = interactive_mpl_registry+ self._cell_lifecycle_registry = cell_lifecycle_registry+ self._virtual_file_registry = virtual_file_registryself._stream = streamself._stdout = stdoutself._stderr = stderr@@ -75,15 +81,30 @@ class RuntimeContext(threading.local):assert self._kernel is not Nonereturn self._kernel+ @property+ def cell_id(self) -> Optional[CellId_t]:+ """Get the cell id of the currently executing cell, if any."""+ if (+ self._kernel is not None+ and self._kernel.execution_context is not None+ ):+ return self._kernel.execution_context.cell_id+ return None++ @property+ def cell_lifecycle_registry(self) -> CellLifecycleRegistry:+ assert self._cell_lifecycle_registry is not None+ return self._cell_lifecycle_registry+@propertydef ui_element_registry(self) -> UIElementRegistry:assert self._ui_element_registry is not Nonereturn self._ui_element_registry@property- def interactive_mpl_registry(self) -> InteractiveMplRegistry:- assert self._interactive_mpl_registry- return self._interactive_mpl_registry+ def virtual_file_registry(self) -> VirtualFileRegistry:+ assert self._virtual_file_registry is not None+ return self._virtual_file_registry@propertydef stream(self) -> Stream:@@ -122,7 +143,8 @@ _RUNTIME_CONTEXT = RuntimeContext()def initialize_context(kernel: Kernel,ui_element_registry: UIElementRegistry,- interactive_mpl_registry: InteractiveMplRegistry,+ cell_lifecycle_registry: CellLifecycleRegistry,+ virtual_file_registry: VirtualFileRegistry,stream: Stream,stdout: Optional[Stdout],stderr: Optional[Stderr],@@ -133,7 +155,8 @@ def initialize_context(_RUNTIME_CONTEXT.initialize(kernel=kernel,ui_element_registry=ui_element_registry,- interactive_mpl_registry=interactive_mpl_registry,+ cell_lifecycle_registry=cell_lifecycle_registry,+ virtual_file_registry=virtual_file_registry,stream=stream,stdout=stdout,stderr=stderr,diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 9c3a2c7a8a..52e4c01475 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -40,10 +40,10 @@ from marimo._messaging.ops import (from marimo._messaging.streams import Stderr, Stdout, Streamfrom marimo._output import formattingfrom marimo._output.rich_help import mddoc-from marimo._plugins.stateless.mpl._mpl import InteractiveMplRegistryfrom marimo._plugins.ui._core.registry import UIElementRegistryfrom marimo._plugins.ui._core.ui_element import MarimoConvertValueExceptionfrom marimo._runtime import cell_runner, dataflow+from marimo._runtime.cell_lifecycle_registry import CellLifecycleRegistryfrom marimo._runtime.complete import completefrom marimo._runtime.context import (get_context,@@ -66,6 +66,7 @@ from marimo._runtime.requests import ()from marimo._runtime.state import Statefrom marimo._runtime.validate_graph import check_for_errors+from marimo._runtime.virtual_file import VirtualFileRegistryLOGGER = _loggers.marimo_logger()@@ -290,7 +291,7 @@ class Kernel:self._delete_names(defs_to_delete, exclude_defs if exclude_defs is not None else set())- get_context().interactive_mpl_registry.cleanup(cell_id)+ get_context().cell_lifecycle_registry.dispose(cell_id)RemoveUIElements(cell_id=cell_id).broadcast()def _deactivate_cell(self, cell_id: CellId_t) -> set[CellId_t]:@@ -939,7 +940,8 @@ def launch_kernel(initialize_context(kernel=kernel,ui_element_registry=UIElementRegistry(),- interactive_mpl_registry=InteractiveMplRegistry(),+ cell_lifecycle_registry=CellLifecycleRegistry(),+ virtual_file_registry=VirtualFileRegistry(),stream=stream,stdout=stdout,stderr=stderr,diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.pynew file mode 100644index 0000000000..9a2afbb23b--- /dev/null+++ b/marimo/_runtime/virtual_file.py@@ -0,0 +1,50 @@+# Copyright 2023 Marimo. All rights reserved.+from __future__ import annotations++import dataclasses+import io+from typing import TYPE_CHECKING, Callable++from marimo._runtime.cell_lifecycle_item import CellLifecycleItem++if TYPE_CHECKING:+ from marimo._runtime.context import RuntimeContext+++class VirtualFile:+ url: str++ def __init__(self, filename: str) -> None:+ raise NotImplementedError+++class VirutalFileLifeCycleItem(CellLifecycleItem):+ def __init__(+ self, filename: str, to_stream: Callable[[], io.BytesIO]+ ) -> None:+ self.filename = filename+ self.to_stream = to_stream++ def create(self, context: "RuntimeContext") -> None:+ context.virtual_file_registry.add(+ self.filename, self.to_virtual_file()+ )++ def dispose(self, context: "RuntimeContext") -> None:+ context.virtual_file_registry.remove(self.filename)++ def to_virtual_file(self) -> VirtualFile:+ return VirtualFile(self.filename)+++class VirtualFileRegistry:+ registry: dict[str, VirtualFile] = dataclasses.field(default_factory=dict)++ def add(self, filename: str, virtual_file: VirtualFile) -> None:+ self.registry[filename] = virtual_file++ def remove(self, filename: str) -> None:+ if filename in self.registry:+ del self.registry[filename]