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
feat: import and run named cells (#843)
Akshay Agrawal6ca0494145dd
diff --git a/docs/api/cell.md b/docs/api/cell.mdnew file mode 100644index 0000000000..9b3e3b1932--- /dev/null+++ b/docs/api/cell.md@@ -0,0 +1,8 @@+# Cell++```{eval-rst}+.. autoclass:: marimo.ACell+ :members:++ .. autoclasstoc::+```diff --git a/docs/api/index.md b/docs/api/index.mdindex d7f31e7110..f20e4e9958 100644--- a/docs/api/index.md+++ b/docs/api/index.md@@ -16,6 +16,7 @@control_flowhtmlstate+ celldebugging```@@ -40,4 +41,5 @@ Use the marimo library in marimo notebooks (`import marimo as mo`) to| {doc}`control_flow` | Control how cells execute || {doc}`html` | Manipulate HTML objects || {doc}`state` | Synchronize multiple UI elements with `mo.state` |+| {doc}`cell` | Run cells defined in another notebook || {doc}`debugging` | Debugging utilities |diff --git a/marimo/__init__.py b/marimo/__init__.pyindex 8cd9ac02a2..892f129dd6 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -14,6 +14,7 @@ marimo is designed to be:__all__ = ["App",+ "Cell","MarimoStopError","accordion","as_html",@@ -54,6 +55,7 @@ __all__ = [__version__ = "0.2.8"from marimo._ast.app import App+from marimo._ast.cell import Cellfrom marimo._output.doc import docfrom marimo._output.formatting import as_htmlfrom marimo._output.hypertext import Htmldiff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex c88571f2bb..db96ce9547 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -10,21 +10,14 @@ from typing import (Any,Callable,Iterable,+ Iterator,Literal,+ Mapping,Optional,- Union,- cast,)from marimo import _loggers-from marimo._ast.cell import (- CellConfig,- CellFunction,- CellFuncType,- CellFuncTypeBound,- CellId_t,- execute_cell_async,-)+from marimo._ast.cell import Cell, CellConfig, CellId_t, execute_cell_asyncfrom marimo._ast.compiler import cell_factoryfrom marimo._ast.errors import (CycleError,@@ -32,8 +25,9 @@ from marimo._ast.errors import (MultipleDefinitionError,UnparsableError,)+from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.rich_help import mddoc-from marimo._runtime.dataflow import DirectedGraph, topological_sort+from marimo._runtime import dataflowfrom marimo._runtime.patches import patch_main_module_contextLOGGER = _loggers.marimo_logger()@@ -76,8 +70,27 @@ class CellData:# Cell configconfig: CellConfig- # Callable cell, or None if cell was not parsable- cell_function: Optional[CellFunction[CellFuncType]]+ # The original cell, or None if cell was not parsable+ cell: Optional[Cell]+++class _Namespace(Mapping[str, object]):+ def __init__(self, dictionary: dict[str, object]) -> None:+ self._dict = dictionary++ def __getitem__(self, item: str) -> object:+ return self._dict[item]++ def __iter__(self) -> Iterator[str]:+ return iter(self._dict)++ def __len__(self) -> int:+ return len(self._dict)++ def _mime_(self) -> tuple[KnownMimeType, str]:+ from marimo._plugins.stateless.tree import tree++ return tree(self._dict)._mime_()@mddoc@@ -100,22 +113,20 @@ class App:self._config.__setattr__(key, kwargs.pop(key))self._cell_manager = CellManager()- self._graph = DirectedGraph()+ self._graph = dataflow.DirectedGraph()+ self._runner = dataflow.Runner(self._graph)self._unparsable = Falseself._initialized = Falsedef cell(self,- func: Optional[CellFuncTypeBound] = None,+ func: Callable[..., Any] | None = None,*,disabled: bool = False,hide_code: bool = False,**kwargs: Any,- ) -> Union[- Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],- CellFunction[CellFuncTypeBound],- ]:+ ) -> Cell | Callable[[Callable[..., Any]], Cell]:"""A decorator to add a cell to the appThis decorator can be called with or without parentheses. Each of the@@ -142,7 +153,9 @@ class App:"""del kwargs- return self._cell_manager.cell_decorator(func, disabled, hide_code)+ return self._cell_manager.cell_decorator(+ func, disabled, hide_code, app=InternalApp(self)+ )def _unparsable_cell(self,@@ -158,17 +171,18 @@ class App:self._unparsable = Truedef _maybe_initialize(self) -> None:- assert not self._unparsable+ if self._unparsable:+ raise RuntimeError(+ "This notebook has cells with syntax errors, "+ "so it cannot be initialized."+ )if self._initialized:- LOGGER.warning(- "App was initialized twice. This is probably a bug in marimo."- )return# Add cells to graph- for cell_id, cell_fn in self._cell_manager.valid_cells():- self._graph.register_cell(cell_id, cell_fn.cell)+ for cell_id, cell in self._cell_manager.valid_cells():+ self._graph.register_cell(cell_id, cell._cell)self._defs = self._graph.definitions.keys()try:@@ -189,7 +203,7 @@ class App:"This app can't be run because at least one cell "f"deletes one of its refs (the ref's name is {ref})")- self._execution_order = topological_sort(+ self._execution_order = dataflow.topological_sort(self._graph, list(self._cell_manager.valid_cell_ids()))finally:@@ -211,13 +225,9 @@ class App:# Execute cells and collect outputsoutputs: dict[CellId_t, Any] = {}for cid in self._execution_order:- cell_function = self._cell_manager.cell_data_at(- cid- ).cell_function- if cell_function is not None:- outputs[cid] = await execute_cell_async(- cell_function.cell, glbls- )+ cell = self._cell_manager.cell_data_at(cid).cell+ if cell is not None:+ outputs[cid] = await execute_cell_async(cell._cell, glbls)# Return# - the outputs, sorted in the order that cells were added to the@@ -238,6 +248,22 @@ class App:def run(self) -> tuple[Sequence[Any], dict[str, Any]]:return asyncio.run(self._run_async())+ async def _run_cell_async(+ self, cell: Cell, kwargs: dict[str, Any]+ ) -> tuple[Any, _Namespace]:+ self._maybe_initialize()+ output, defs = await self._runner.run_cell_async(+ cell._cell.cell_id, kwargs+ )+ return output, _Namespace(defs)++ def _run_cell_sync(+ self, cell: Cell, kwargs: dict[str, Any]+ ) -> tuple[Any, _Namespace]:+ self._maybe_initialize()+ output, defs = self._runner.run_cell_sync(cell._cell.cell_id, kwargs)+ return output, _Namespace(defs)+class CellManager:"""@@ -258,50 +284,42 @@ class CellManager:def cell_decorator(self,- func: Optional[CellFuncTypeBound],+ func: Callable[..., Any] | None,disabled: bool,hide_code: bool,- ) -> Union[- Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],- CellFunction[CellFuncTypeBound],- ]:+ app: InternalApp | None = None,+ ) -> Cell | Callable[..., Cell]:cell_config = CellConfig(disabled=disabled, hide_code=hide_code)+ def _register(func: Callable[..., Any]) -> Cell:+ cell = cell_factory(func, cell_id=self.create_cell_id())+ cell._cell.configure(cell_config)+ self._register_cell(cell, app=app)+ return cell+if func is None:# If the decorator was used with parentheses, func will be None,# and we return a decorator that takes the decorated function as an# argument- def decorator(- func: CellFuncTypeBound,- ) -> CellFunction[CellFuncTypeBound]:- cell_function = cell_factory(- func, cell_id=self.create_cell_id()- )- cell_function.cell.configure(cell_config)- self._register_cell_function(cell_function)- return cell_function+ def decorator(func: Callable[..., Any]) -> Cell:+ return _register(func)- return cast(- Callable[[CellFuncType], CellFunction[CellFuncTypeBound]],- decorator,- )-- # If the decorator was used without parentheses, func will be the- # decorated function- cell_function = cell_factory(func, cell_id=self.create_cell_id())- cell_function.cell.configure(cell_config)- self._register_cell_function(cell_function)- return cell_function+ return decorator+ else:+ return _register(func)- def _register_cell_function(- self, cell_function: CellFunction[CellFuncTypeBound]+ def _register_cell(+ self, cell: Cell, app: InternalApp | None = None) -> None:+ if app is not None:+ cell._register_app(app)+ cell_impl = cell._cellself.register_cell(- cell_id=cell_function.cell.cell_id,- code=cell_function.cell.code,- name=cell_function.__name__,- config=cell_function.cell.config,- cell_function=cast(CellFunction[CellFuncType], cell_function),+ cell_id=cell_impl.cell_id,+ code=cell_impl.code,+ name=cell.name,+ config=cell_impl.config,+ cell=cell,)def register_cell(@@ -310,7 +328,7 @@ class CellManager:code: str,config: Optional[CellConfig],name: str = "__",- cell_function: Optional[CellFunction[CellFuncType]] = None,+ cell: Optional[Cell] = None,) -> None:if cell_id is None:cell_id = self.create_cell_id()@@ -320,7 +338,7 @@ class CellManager:code=code,name=name,config=config or CellConfig(),- cell_function=cell_function,+ cell=cell,)def register_unparsable_cell(@@ -343,7 +361,7 @@ class CellManager:code=code,config=cell_config,name=name or "__",- cell_function=None,+ cell=None,)def names(self) -> Iterable[str]:@@ -360,26 +378,26 @@ class CellManager:def valid_cells(self,- ) -> Iterable[tuple[CellId_t, CellFunction[CellFuncType]]]:+ ) -> Iterable[tuple[CellId_t, Cell]]:"""Return cells and functions for each valid cell."""for cell_data in self._cell_data.values():- if cell_data.cell_function is not None:- yield (cell_data.cell_id, cell_data.cell_function)+ if cell_data.cell is not None:+ yield (cell_data.cell_id, cell_data.cell)def valid_cell_ids(self) -> Iterable[CellId_t]:for cell_data in self._cell_data.values():- if cell_data.cell_function is not None:+ if cell_data.cell is not None:yield cell_data.cell_iddef cell_ids(self) -> Iterable[CellId_t]:"""Cell IDs in the order they were registered."""return self._cell_data.keys()- def cell_functions(+ def cells(self,- ) -> Iterable[Optional[CellFunction[CellFuncType]]]:+ ) -> Iterable[Optional[Cell]]:for cell_data in self._cell_data.values():- yield cell_data.cell_function+ yield cell_data.celldef config_map(self) -> dict[CellId_t, CellConfig]:return {cid: cd.config for cid, cd in self._cell_data.items()}@@ -410,6 +428,11 @@ class InternalApp:def cell_manager(self) -> CellManager:return self._app._cell_manager+ @property+ def runner(self) -> dataflow.Runner:+ self._app._maybe_initialize()+ return self._app._runner+def update_config(self, updates: dict[str, Any]) -> _AppConfig:return self.config.update(updates)@@ -433,3 +456,13 @@ class InternalApp:)self._app._cell_manager = new_cell_managerreturn self++ async def run_cell_async(+ self, cell: Cell, kwargs: dict[str, Any]+ ) -> tuple[Any, _Namespace]:+ return await self._app._run_cell_async(cell, kwargs)++ def run_cell_sync(+ self, cell: Cell, kwargs: dict[str, Any]+ ) -> tuple[Any, _Namespace]:+ return self._app._run_cell_sync(cell, kwargs)diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 67461f1d2e..8daf3d5cae 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -3,25 +3,20 @@ from __future__ import annotationsimport astimport dataclasses-import functoolsimport inspect+from collections.abc import Awaitablefrom types import CodeType-from typing import (- Any,- Callable,- Literal,- Optional,- Protocol,- Tuple,- TypeVar,- cast,-)+from typing import TYPE_CHECKING, Any, Callable, Literal, Mapping, Optionalfrom marimo._ast.visitor import Name, VariableDatafrom marimo._utils.deep_merge import deep_mergeCellId_t = str+if TYPE_CHECKING:+ from marimo._ast.app import InternalApp+ from marimo._output.hypertext import Html+@dataclasses.dataclassclass CellConfig:@@ -54,13 +49,14 @@ CellConfigKeys = frozenset({field.name for field in dataclasses.fields(CellConfig)})-"""-idle: cell has run with latest inputs-queued: cell is queued to run-running: cell is running-stale: cell hasn't run with latest inputs, and can't run (disabled)-disabled-transitively: cell is disabled because a parent is disabled-"""++# Cell Statuses+#+# idle: cell has run with latest inputs+# queued: cell is queued to run+# running: cell is running+# stale: cell hasn't run with latest inputs, and can't run (disabled)+# disabled-transitively: cell is disabled because a parent is disabledCellStatusType = Literal["idle", "queued", "running", "stale", "disabled-transitively"]@@ -78,7 +74,7 @@ def _is_coroutine(code: Optional[CodeType]) -> bool:@dataclasses.dataclass(frozen=True)-class Cell:+class CellImpl:# hash of codekey: intcode: str@@ -99,7 +95,7 @@ class Cell:# status: status, inferred at runtime_status: CellStatus = dataclasses.field(default_factory=CellStatus)- def configure(self, update: dict[str, Any] | CellConfig) -> Cell:+ def configure(self, update: dict[str, Any] | CellConfig) -> CellImpl:"""Update the cel config.`update` can be a partial config.@@ -148,111 +144,233 @@ class Cell:CellOp.broadcast_status(cell_id=self.cell_id, status=status)-CellFuncType = Callable[..., Optional[Tuple[Any, ...]]]-# Cumbersome, but used to ensure function types don't get erased in decorators-# or creation of CellFunction-CellFuncTypeBound = TypeVar(- "CellFuncTypeBound",- bound=Callable[..., Optional[Tuple[Any, ...]]],-)+class Cell:+ """An executable notebook cell+ `A Cell` object can be executed as a function via its `run()` method, which+ returns the cell's last expression (output) and a mapping from its defined+ names to its values.-class CellFunction(Protocol[CellFuncTypeBound]):- """Wraps a function from which a Cell object was created."""+ Cells can be named via the marimo editor in the browser, or by+ changing the cell's function name in the notebook file. Named+ cells can then be executed for use in other notebooks, or to test+ in unit tests.- cell: Cell- # function name- __name__: str- # function code- code: str- # arg names of wrapped function- args: set[str]- __call__: CellFuncTypeBound+ For example:++ ```python+ from my_notebook import my_cell++ output, definitions = my_cell.run()+ ```++ See the documentation of `run` for info and examples.+ """++ # Function from which this cell was created+ _f: Callable[..., Any]++ # Internal cell representation+ _cell: CellImpl++ # App to which this cell belongs+ _app: InternalApp | None = None++ @property+ def name(self) -> str:+ return self._f.__name__++ @property+ def refs(self) -> set[str]:+ """The references that this cell takes as input"""+ return self._cell.refs++ @property+ def defs(self) -> set[str]:+ """The definitions made by this cell"""+ return self._cell.defs++ def _is_coroutine(self) -> bool:+ """Whether this cell is a coroutine function.++ If True, then this cell's `run` method returns an awaitable.+ """+ if hasattr(self, "_is_coro_cached"):+ return self._is_coro_cached+ assert self._app is not None+ self._is_coro_cached: bool = self._app.runner.is_coroutine(+ self._cell.cell_id+ )+ return self._is_coro_cached++ def _help(self) -> Html:+ from marimo._output.formatting import as_html+ from marimo._output.md import md++ signature_prefix = "Async " if self._is_coroutine() else ""+ execute_str_refs = (+ f"output, defs = await {self.name}.run(**refs)"+ if self._is_coroutine()+ else f"output, defs = {self.name}.run(**refs)"+ )+ execute_str_no_refs = (+ f"output, defs = await {self.name}.run()"+ if self._is_coroutine()+ else f"output, defs = {self.name}.run()"+ )++ return md(+ f"""+ **{signature_prefix}Cell `{self.name}`**++ You can execute this cell using++ `{execute_str_refs}`++ where `refs` is a dictionary mapping a subset of the+ cell's references to values. Missing refs will be automatically+ computed. To automatically compute all refs, simply run with++ `{execute_str_no_refs}`+ **References:**-def cell_function(- cell: Cell, args: set[str], code: str, f: CellFuncTypeBound-) -> CellFunction[CellFuncTypeBound]:- signature = inspect.signature(f)+ {as_html(list(self.refs))}- n_args = 0- defaults = {}- for name, value in signature.parameters.items():- if value.default != inspect.Parameter.empty:- defaults[name] = value.default+ **Definitions:**++ {as_html(list(self.defs))}+ """+ )++ def _register_app(self, app: InternalApp) -> None:+ self._app = app++ def run(+ self, **refs: Any+ ) -> (+ tuple[Any, Mapping[str, Any]]+ | Awaitable[tuple[Any, Mapping[str, Any]]]+ ):+ """Run this cell and return its visual output and definitions++ Use this method to run **named cells** and retrieve their output and+ definitions.++ This lets you use reuse cells defined in one notebook in another+ notebook or Python file. It also makes it possible to write and execute+ unit tests for notebook cells using a test framework like `pytest`.++ **Example.** marimo cells can be given names either through the+ editor cell menu or by manually changing the function name in the+ notebook file. For example, consider a notebook `notebook.py`:++ ```python+ import marimo++ app = marimo.App()++ @app.cell+ def __():+ import marimo as mo+ return (mo,)++ @app.cell+ def __():+ x = 0+ y = 1+ return (x, y)++ @app.cell+ def add(mo, x, y):+ z = x + y+ mo.md(f"The value of z is {z}")+ return (z,)++ if __name__ == "__main__":+ app.run()+ ```++ To reuse the `add` cell in another notebook, you'd simply write++ ```python+ from notebook import add++ # `output` is the markdown rendered by `add`+ # defs["z"] == `1`+ output, defs = add.run()+ ```++ When `run` is called without arguments, it automatically computes the+ values that the cell depends on (in this case, `mo`, `x`, and `y`). You+ can override these values by providing any subset of them as keyword+ arguments. For example,++ ```python+ # defs["z"] == 4+ output, defs = add.run(x=2, y=2)+ ```++ **Defined UI Elements.** If the cell's `output` has UI elements+ that are in `defs`, interacting with the output in the frontend will+ trigger reactive execution of cells that reference the `defs` object.+ For example, if `output` has a slider defined by the cell, then+ scrubbing the slider will cause cells that reference `defs` to run.++ **Async cells.** If this cell is a coroutine function (starting with+ `async`), or if any of its ancestors are coroutine functions, then+ you'll need to `await` the result: `output, defs = await cell.run()`.+ You can check whether the result is an awaitable using:++ ```python+ from collections.abc import Awaitable++ ret = cell.run()+ if isinstance(ret, Awaitable):+ output, defs = await retelse:- n_args += 1-- parameters = list(signature.parameters.keys())- return_names = sorted(defn for defn in cell.defs)-- def _prepare_args(*args: Any, **kwargs: Any) -> dict[Any, Any]:- glbls = {}- glbls.update(defaults)- pos = 0- for arg in args:- glbls[parameters[pos]] = arg- pos += 1- if pos < n_args:- raise TypeError(- f.__name__- + f"() missing {n_args - pos} required arguments: "- + " and ".join(f"'{p}'" for p in parameters[pos:n_args])- )-- for kwarg, value in kwargs.items():- if kwarg not in parameters:- raise TypeError(- f.__name__- + "() got an unexpected keyword argument '{kwarg}'"- )- else:- glbls[kwarg] = value- return glbls-- def _returns(glbls: dict[Any, Any]) -> tuple[Any, ...]:- return tuple(glbls[name] for name in return_names)-- # Wrapper for executing cell using the function's signature.- #- # Alternative for passing a globals dict- #- # we use execute_cell instead of calling `f` directly because- # we want to obtain the cell's HTML output, which is the last- # expression in the cell body.- #- # TODO: stash output if mo.collect_outputs() context manager is active- # ... or just make cell execution return the output in addition- # to the defs, which might be weird because that doesn't- # match the function signature- if inspect.iscoroutinefunction(f):-- @functools.wraps(f)- async def func(*args: Any, **kwargs: Any) -> tuple[Any, ...]:- glbls = _prepare_args(*args, **kwargs)- _ = await execute_cell_async(cell, glbls)- return _returns(glbls)+ output, defs = ret+ ```- else:+ **Arguments**:++ - You may pass values for any of this cell's references as keyword+ arguments. marimo will automatically compute values for any refs+ that are not provided by executing the parent cells that compute+ them.- @functools.wraps(f)- def func(*args: Any, **kwargs: Any) -> tuple[Any, ...]:- glbls = _prepare_args(*args, **kwargs)- _ = execute_cell(cell, glbls)- return _returns(glbls)+ **Returns**:- cell_func = cast(CellFunction[CellFuncTypeBound], func)- cell_func.cell = cell- cell_func.args = args- cell_func.code = code- return cell_func+ - a tuple `(output, defs)`, or an awaitable of the same, where `output`+ is the cell's last expression and `defs` is a `Mapping` from the+ cell's defined names to their values.+ """+ assert self._app is not None+ if self._is_coroutine():+ return self._app.run_cell_async(cell=self, kwargs=refs)+ else:+ return self._app.run_cell_sync(cell=self, kwargs=refs)++ def __call__(self, *args: Any, **kwargs: Any) -> None:+ del args+ del kwargs+ if self._is_coroutine():+ call_str = f"`outputs, defs = await {self.name}.run()`"+ else:+ call_str = f"`outputs, defs = {self.name}.run()`"++ raise RuntimeError(+ f"Calling marimo cells using `{self.name}()` is not supported. "+ f"Use {call_str} instead. "+ )def is_ws(char: str) -> bool:return char == " " or char == "\n" or char == "\t"-async def execute_cell_async(cell: Cell, glbls: dict[Any, Any]) -> Any:+async def execute_cell_async(cell: CellImpl, glbls: dict[Any, Any]) -> Any:if cell.body is None:return Noneassert cell.last_expr is not None@@ -268,7 +386,7 @@ async def execute_cell_async(cell: Cell, glbls: dict[Any, Any]) -> Any:return eval(cell.last_expr, glbls)-def execute_cell(cell: Cell, glbls: dict[Any, Any]) -> Any:+def execute_cell(cell: CellImpl, glbls: dict[Any, Any]) -> Any:if cell.body is None:return Noneassert cell.last_expr is not Nonediff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 9d4e1d746c..4549fb70da 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -11,7 +11,7 @@ from typing import Any, List, Optional, Union, castfrom marimo import __version__from marimo._ast.app import App, _AppConfig-from marimo._ast.cell import Cell, CellConfig+from marimo._ast.cell import CellConfig, CellImplfrom marimo._ast.compiler import compile_cellfrom marimo._ast.visitor import Name@@ -56,7 +56,7 @@ def _to_decorator(config: Optional[CellConfig]) -> str:def to_functiondef(- cell: Cell, name: str, unshadowed_builtins: Optional[set[Name]] = None+ cell: CellImpl, name: str, unshadowed_builtins: Optional[set[Name]] = None) -> str:# unshadowed builtins is the set of builtins that haven't been# overridden (shadowed) by other cells in the app. These names@@ -150,7 +150,7 @@ def generate_filecontents(config: Optional[_AppConfig] = None,) -> str:"""Translates a sequences of codes (cells) to a Python file"""- cell_function_data: list[Union[Cell, tuple[str, CellConfig]]] = []+ cell_data: list[Union[CellImpl, tuple[str, CellConfig]]] = []defs: set[Name] = set()cell_id = 0@@ -160,15 +160,15 @@ def generate_filecontents(cell_config)defs |= cell.defs- cell_function_data.append(cell)+ cell_data.append(cell)except SyntaxError:- cell_function_data.append((code, cell_config))+ cell_data.append((code, cell_config))cell_id += 1unshadowed_builtins = set(builtins.__dict__.keys()) - defsfndefs: list[str] = []- for data, name in zip(cell_function_data, names):- if isinstance(data, Cell):+ for data, name in zip(cell_data, names):+ if isinstance(data, CellImpl):fndefs.append(to_functiondef(data, name, unshadowed_builtins))else:fndefs.append(diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 3178269eba..240c217867 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -10,14 +10,12 @@ import textwrapimport token as token_typesfrom collections.abc import Iteratorfrom tokenize import TokenInfo, tokenize-from typing import Optional, Set, Union, cast+from typing import Any, Callable, Optional, Unionfrom marimo._ast.cell import (Cell,- CellFunction,- CellFuncTypeBound,CellId_t,- cell_function,+ CellImpl,)from marimo._ast.visitor import ScopedVisitor, is_localfrom marimo._utils.tmpdir import get_tmpdir@@ -51,7 +49,7 @@ def cache(filename: str, code: str) -> None:)-def compile_cell(code: str, cell_id: CellId_t) -> Cell:+def compile_cell(code: str, cell_id: CellId_t) -> CellImpl:module = compile(code,"<unknown>",@@ -60,7 +58,7 @@ def compile_cell(code: str, cell_id: CellId_t) -> Cell:)if not module.body:# either empty code or just comments- return Cell(+ return CellImpl(key=hash(""),code=code,mod=module,@@ -98,7 +96,7 @@ def compile_cell(code: str, cell_id: CellId_t) -> Cell:last_expr = compile(expr, last_expr_filename, mode="eval", flags=flags)glbls = {name for name in v.defs if not is_local(name)}- return Cell(+ return CellImpl(# keyed by original (user) code, for cache lookupskey=code_key(code),code=code,@@ -118,9 +116,9 @@ def compile_cell(code: str, cell_id: CellId_t) -> Cell:def cell_factory(- f: CellFuncTypeBound,+ f: Callable[..., Any],cell_id: CellId_t,-) -> CellFunction[CellFuncTypeBound]:+) -> Cell:"""Creates a cell from a function.The signature and returns of the function are not used@@ -220,13 +218,4 @@ def cell_factory(# handle return written on same line as last statement in cellcell_code += "\n" + lines[end_line][:return_offset]- arg_names = set(p.arg for p in tree.body[0].args.args) # type: ignore- # TODO(akshayka): use the name of the function as the basename (if not __)- # for parse_cell- ret = cell_function(- compile_cell(cell_code, cell_id=cell_id),- cast(Set[str], arg_names),- function_code,- f,- )- return ret+ return Cell(_f=f, _cell=compile_cell(cell_code, cell_id=cell_id))diff --git a/marimo/_output/formatters/cell.py b/marimo/_output/formatters/cell.pynew file mode 100644index 0000000000..c161d949bc--- /dev/null+++ b/marimo/_output/formatters/cell.py@@ -0,0 +1,18 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._ast.cell import Cell+from marimo._messaging.mimetypes import KnownMimeType+from marimo._output import formatting+from marimo._output.formatters.formatter_factory import FormatterFactory+++class CellFormatter(FormatterFactory):+ @staticmethod+ def package_name() -> None:+ return None++ def register(self) -> None:+ @formatting.formatter(Cell)+ def _format_cell(cell: Cell) -> tuple[KnownMimeType, str]:+ return cell._help()._mime_()diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 2015087acf..0999a12d10 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -6,6 +6,7 @@ from typing import Any, Callable, Sequencefrom marimo._output.formatters.altair_formatters import AltairFormatterfrom marimo._output.formatters.bokeh_formatters import BokehFormatter+from marimo._output.formatters.cell import CellFormatterfrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._output.formatters.holoviews_formatters import HoloViewsFormatterfrom marimo._output.formatters.leafmap_formatters import LeafmapFormatter@@ -33,6 +34,7 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {# third-party module import. These formatters' register methods need to be# fast: we don't want their registration to noticeably delay program start-up.NATIVE_FACTORIES: Sequence[FormatterFactory] = [+ CellFormatter(),StructuresFormatter(),]@@ -118,7 +120,7 @@ def register_formatters() -> None:# Use the __get__ descriptor to bind find_spec to this finder object,# to make sure self/cls gets passed- finder.find_spec = find_spec.__get__(finder) # type: ignore[method-assign]+ finder.find_spec = find_spec.__get__(finder) # type: ignore[method-assign] # noqa: E501# These factories are for builtins or other things that don't require a# package import. So we can register them at program start-up.diff --git a/marimo/_output/md_extensions/external_links.py b/marimo/_output/md_extensions/external_links.pyindex 6c3a2d2f9f..c15d43b602 100644--- a/marimo/_output/md_extensions/external_links.py+++ b/marimo/_output/md_extensions/external_links.py@@ -4,10 +4,10 @@ from xml.etree.ElementTree import Elementfrom markdown import Extension, Markdown, treeprocessors # type: ignore-# Adapted from https://github.com/squidfunk/mkdocs-material/discussions/3660#discussioncomment-6725823+# Adapted from https://github.com/squidfunk/mkdocs-material/discussions/3660#discussioncomment-6725823 # noqa: E501-class ExternalLinksTreeProcessor(treeprocessors.Treeprocessor): # type: ignore[misc]+class ExternalLinksTreeProcessor(treeprocessors.Treeprocessor): # type: ignore[misc] # noqa: E501"""Adds target="_blank" and rel="noopener" to external links."""diff --git a/marimo/_plugins/ui/_core/registry.py b/marimo/_plugins/ui/_core/registry.pyindex 5ed848ea50..92bfa35a19 100644--- a/marimo/_plugins/ui/_core/registry.py+++ b/marimo/_plugins/ui/_core/registry.py@@ -3,13 +3,14 @@ from __future__ import annotationsimport sysimport weakref-from typing import Any, Dict, Iterable, TypeVar, Union+from typing import Any, Dict, Iterable, Mapping, TypeVar, Unionif sys.version_info < (3, 10):from typing_extensions import TypeAliaselse:from typing import TypeAlias+from marimo._ast.app import _Namespacefrom marimo._ast.cell import CellId_tfrom marimo._plugins.ui._core.ui_element import UIElementfrom marimo._runtime.context import get_context@@ -71,22 +72,32 @@ class UIElementRegistry:return self._has_parent_id(element, parent_id)return False- def _register_bindings(self, object_id: UIElementId) -> None:- kernel = get_context().kernel+ def _find_bindings_in_namespace(+ self, object_id: UIElementId, glbls: Mapping[str, Any]+ ) -> set[str]:# Get all variable names that are either:# 1. bound to this UI element, or# 2. bound to a view (child) of this element- names = set(- [- name- for name in kernel.globals- if (- isinstance(kernel.globals[name], UIElement)- and self._has_parent_id(kernel.globals[name], object_id)- )- ]+ #+ # Also introspects _Namespace objects, including the name of the+ # _Namespace if it contains `object_id`+ bindings: set[str] = set()+ for name, value in glbls.items():+ if isinstance(value, UIElement) and self._has_parent_id(+ value, object_id+ ):+ bindings.add(name)+ elif isinstance(+ value, _Namespace+ ) and self._find_bindings_in_namespace(object_id, value):+ bindings.add(name)+ return bindings++ def _register_bindings(self, object_id: UIElementId) -> None:+ kernel = get_context().kernel+ self._bindings[object_id] = self._find_bindings_in_namespace(+ object_id, kernel.globals)- self._bindings[object_id] = namesdef get_object(self, object_id: UIElementId) -> UIElement[Any, Any]:if object_id not in self._objects:diff --git a/marimo/_plugins/ui/_impl/dataframes/handlers.py b/marimo/_plugins/ui/_impl/dataframes/handlers.pyindex 4181276831..3f3460ed63 100644--- a/marimo/_plugins/ui/_impl/dataframes/handlers.py+++ b/marimo/_plugins/ui/_impl/dataframes/handlers.py@@ -182,7 +182,7 @@ class TransformHandlers:# Pandas type-checking doesn't like the fact that the values# are lists of strings (function names), even though the docs permit# such a value- return cast("pd.DataFrame", df.agg(dict_of_aggs)) # type: ignore[arg-type]+ return cast("pd.DataFrame", df.agg(dict_of_aggs)) # type: ignore[arg-type] # noqa: E501@staticmethoddef handle_select_columns(diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.pyindex bf87bc9d0e..d6d91b878e 100644--- a/marimo/_runtime/dataflow.py+++ b/marimo/_runtime/dataflow.py@@ -4,10 +4,15 @@ from __future__ import annotationsimport threadingfrom collections.abc import Collectionfrom dataclasses import dataclass, field-from typing import Optional, Tuple+from typing import Any, Optional, Tuplefrom marimo import _loggers-from marimo._ast.cell import Cell, CellId_t+from marimo._ast.cell import (+ CellId_t,+ CellImpl,+ execute_cell,+ execute_cell_async,+)from marimo._ast.compiler import code_keyfrom marimo._ast.visitor import Name@@ -21,7 +26,7 @@ LOGGER = _loggers.marimo_logger()@dataclass(frozen=True)class DirectedGraph:# Nodes in the graph- cells: dict[CellId_t, Cell] = field(default_factory=dict)+ cells: dict[CellId_t, CellImpl] = field(default_factory=dict)# Edge (u, v) means v is a child of u, i.e., v has a reference# to something defined in u@@ -85,7 +90,7 @@ class DirectedGraph:queue.append((cid, next_path))return []- def register_cell(self, cell_id: CellId_t, cell: Cell) -> None:+ def register_cell(self, cell_id: CellId_t, cell: CellImpl) -> None:"""Add a cell to the graph.Mutates the graph, acquiring `self.lock`.@@ -281,17 +286,24 @@ class DirectedGraph:def transitive_closure(- graph: DirectedGraph, cell_ids: set[CellId_t]+ graph: DirectedGraph, cell_ids: set[CellId_t], children: bool = True) -> set[CellId_t]:- """Return a set of the passed-in cells and their descendants."""+ """Return a set of the passed-in cells and their descendants or ancestors++ If children is True, returns descendants; otherwise, returns ancestors+ """cells = set()queue = list(cell_ids)++ def relatives(cid: CellId_t) -> set[CellId_t]:+ return graph.children[cid] if children else graph.parents[cid]+while queue:cid = queue.pop(0)cells.add(cid)- for child_id in graph.children[cid]:- if child_id not in cells:- queue.append(child_id)+ for relative in relatives(cid):+ if relative not in cells:+ queue.append(relative)return cells@@ -337,3 +349,133 @@ def topological_sort(roots.append(child)# TODO make sure parents for each id is empty, otherwise cyclereturn sorted_cell_ids+++class Runner:+ """Utility for running individual cells in a graph++ This class provides methods to a run a cell in the graph and obtain its+ output (last expression) and the values of its defs.++ If needed, the runner will recursively compute the values of the cell's+ refs by executing its ancestors. Refs can also be substituted by the+ caller.++ TODO(akshayka): Add an API for caching defs across cell runs.+ """++ def __init__(self, graph: DirectedGraph) -> None:+ self._graph = graph++ @staticmethod+ def _returns(cell_impl: CellImpl, glbls: dict[str, Any]) -> dict[str, Any]:+ return {name: glbls[name] for name in cell_impl.defs if name in glbls}++ @staticmethod+ def _substitute_refs(+ cell_impl: CellImpl,+ glbls: dict[str, Any],+ kwargs: dict[str, Any],+ ) -> None:+ for argname, argvalue in kwargs.items():+ if argname in cell_impl.refs:+ glbls[argname] = argvalue+ else:+ raise ValueError(+ f"Cell got unexpected argument {argname}"+ f"The allowed arguments are {cell_impl.refs}."+ )++ def _get_ancestors(+ self, cell_impl: CellImpl, kwargs: dict[str, Any]+ ) -> set[CellId_t]:+ # Get the transitive closure of parents defining unsubstituted refs+ graph = self._graph+ substitutions = set(kwargs.values())+ unsubstituted_refs = cell_impl.refs - substitutions+ parent_ids = set(+ [+ parent_id+ for parent_id in graph.parents[cell_impl.cell_id]+ if graph.cells[parent_id].defs.intersection(unsubstituted_refs)+ ]+ )+ return transitive_closure(graph, parent_ids, children=False)++ @staticmethod+ def _validate_kwargs(cell_impl: CellImpl, kwargs: dict[str, Any]) -> None:+ for argname in kwargs:+ if argname not in cell_impl.refs:+ raise ValueError(+ f"Cell got unexpected argument {argname}"+ f"The allowed arguments are {cell_impl.refs}."+ )++ def is_coroutine(self, cell_id: CellId_t) -> bool:+ return self._graph.cells[cell_id].is_coroutine() or any(+ self._graph.cells[cid].is_coroutine()+ for cid in self._get_ancestors(+ self._graph.cells[cell_id], kwargs={}+ )+ )++ async def run_cell_async(+ self, cell_id: CellId_t, kwargs: dict[str, Any]+ ) -> tuple[Any, dict[str, Any]]:+ """Run a possibly async cell and its ancestors++ Substitutes kwargs as refs for the cell, omitting ancestors that+ whose refs are substituted.+ """+ graph = self._graph+ cell_impl = graph.cells[cell_id]+ Runner._validate_kwargs(cell_impl, kwargs)+ ancestor_ids = self._get_ancestors(cell_impl, kwargs)++ glbls: dict[str, Any] = {}+ for cid in topological_sort(graph, ancestor_ids):+ await execute_cell_async(graph.cells[cid], glbls)++ Runner._substitute_refs(cell_impl, glbls, kwargs)+ output = await execute_cell_async(+ graph.cells[cell_impl.cell_id], glbls+ )+ defs = Runner._returns(cell_impl, glbls)+ return output, defs++ def run_cell_sync(+ self, cell_id: CellId_t, kwargs: dict[str, Any]+ ) -> tuple[Any, dict[str, Any]]:+ """Run a synchronous cell and its ancestors++ Substitutes kwargs as refs for the cell, omitting ancestors that+ whose refs are substituted.++ Raises a `RuntimeError` if the cell or any of its unsubstituted+ ancestors are coroutine functions.+ """+ graph = self._graph+ cell_impl = graph.cells[cell_id]+ if cell_impl.is_coroutine():+ raise RuntimeError(+ "A coroutine function can't be run synchronously. "+ "Use `run_async()` instead"+ )++ Runner._validate_kwargs(cell_impl, kwargs)+ ancestor_ids = self._get_ancestors(cell_impl, kwargs)++ if any(graph.cells[cid].is_coroutine() for cid in ancestor_ids):+ raise RuntimeError(+ "Cell has an ancestor that is a "+ "coroutine (async) cell. Use `run_async()` instead"+ )++ glbls: dict[str, Any] = {}+ for cid in topological_sort(graph, ancestor_ids):+ execute_cell(graph.cells[cid], glbls)++ self._substitute_refs(cell_impl, glbls, kwargs)+ output = execute_cell(graph.cells[cell_impl.cell_id], glbls)+ defs = Runner._returns(cell_impl, glbls)+ return output, defsdiff --git a/marimo/_server/models/base.py b/marimo/_server/models/base.pyindex 09c25b13c2..663c299beb 100644--- a/marimo/_server/models/base.py+++ b/marimo/_server/models/base.py@@ -18,7 +18,7 @@ def to_camel_case(snake_str: str) -> str:def deep_to_camel_case(snake_dict: Any) -> dict[str, Any]:if isinstance(snake_dict, list):- return [deep_to_camel_case(item) for item in snake_dict] # type: ignore+ return [deep_to_camel_case(item) for item in snake_dict] # type: ignore # noqa: E501if isinstance(snake_dict, str):return to_camel_case(snake_dict) # type: ignorediff --git a/marimo/_smoke_tests/import_named_cells.py b/marimo/_smoke_tests/import_named_cells.pynew file mode 100644index 0000000000..7d6062464d--- /dev/null+++ b/marimo/_smoke_tests/import_named_cells.py@@ -0,0 +1,73 @@+# Copyright 2024 Marimo. All rights reserved.++import marimo++__generated_with = "0.2.8"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def __():+ from named_cells import display_slider, display_element+ return display_element, display_slider+++def __(mo):+ mo.md("**A cell that creates and shows a slider**")+ return+++def __(display_slider):+ slider_output, slider_defs = display_slider.run()+ slider_output+ return slider_defs, slider_output+++def __(mo):+ mo.md("_Notice that set-ui-element value requests make it into the defs_")+ return+++def __(slider_defs):+ slider_defs+ return+++def __(slider_defs):+ slider_defs["slider"].value+ return+++def __(mo):+ mo.md("**A cell that shows a parametrizable UI element**")+ return+++def __(display_element, mo):+ text = mo.ui.text(placeholder="custom input")+ _o, _ = display_element.run(element=text)+ _o+ return text,+++def __(text):+ text.value+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_smoke_tests/named_cells.py b/marimo/_smoke_tests/named_cells.pynew file mode 100644index 0000000000..895c2b4875--- /dev/null+++ b/marimo/_smoke_tests/named_cells.py@@ -0,0 +1,34 @@+# Copyright 2024 Marimo. All rights reserved.+import marimo++__generated_with = "0.2.8"+app = marimo.App()+++def __():+ import marimo as mo+ return mo,+++def display_slider(mo):+ slider = mo.ui.slider(1, 10)+ mo.md(f"Here is a slider: {slider}")+ return slider,+++def __(mo):+ element = mo.ui.checkbox(False)+ return element,+++def display_element(element, mo):+ mo.md(f"Here is an element: {element}")+ return+++if __name__ == "__main__":+ app.run()diff --git a/pyproject.toml b/pyproject.tomlindex 95dc930c3a..3aa5e0cc1c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -132,7 +132,9 @@ exclude = ["marimo/_test_utils/codegen_data","marimo/_test_utils/_tutorials","tests/_ast/codegen_data",+ "tests/_ast/cell_data","tests/_cli/ipynb_data",+ "tests/_runtime/runtime_data","frontend","docs","build",@@ -171,7 +173,9 @@ extend-exclude = """(^/examples/*| ^/tests/_ast/codegen_data/*+ | ^/tests/_ast/cell_data/*| ^/tests/_cli/ipynb_data/*+ | ^/tests/_runtime/runtime_data/*| ^/marimo/_tutorials/*| ^/marimo/_smoke_tests/*)@@ -182,7 +186,9 @@ strict = trueexclude = ['examples','tests/_ast/codegen_data',+ 'tests/_ast/cell_data','tests/_cli/ipynb_data',+ 'tests/_runtime/runtime_data','marimo/_tutorials/','marimo/_smoke_tests/',]diff --git a/tests/_ast/cell_data/named_cells.py b/tests/_ast/cell_data/named_cells.pynew file mode 100644index 0000000000..0fdb11dce0--- /dev/null+++ b/tests/_ast/cell_data/named_cells.py@@ -0,0 +1,27 @@+import marimo++__generated_with = "0.2.8"+app = marimo.App()+++def f():+ x = 0+ return (x,)+++def g(x):+ y = x + 1+ return (y,)+++def h(y):+ z = y + 1+ z+ return (z,)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_ast/test_app_cell.py b/tests/_ast/test_app_cell.pyindex 9f71e4c0b3..ca45997f0a 100644--- a/tests/_ast/test_app_cell.py+++ b/tests/_ast/test_app_cell.py@@ -2,97 +2,90 @@from __future__ import annotationsimport inspect+from collections.abc import Awaitablefrom marimo._ast.app import App-from marimo._ast.cell import CellFunction, CellFuncType--# Arg capture-cell_function: CellFunction[CellFuncType] = None # type: ignore[assignment]---def mock_register_cell(cf: CellFunction[CellFuncType]) -> None:- global cell_function- cell_function = cf---app = App()-app._cell_manager._register_cell_function = mock_register_cell # type: ignore[method-assign, assignment] # noqa: E501def test_decorator_called() -> None:- # Decorator called- @app.cell()def mock_func1() -> tuple[int]:x = 2 + 2return (x,)- assert cell_function.cell.code == "x = 2 + 2"- assert cell_function.cell.config.disabled is False- assert len(cell_function.args) == 0- assert cell_function.__name__ == "mock_func1"- assert cell_function.__call__ is not None- assert cell_function.__call__() == (4,)+ app = App()+ cell = app.cell()(mock_func1)+ assert cell is not None+ assert cell._cell.code == "x = 2 + 2"+ assert cell._cell.config.disabled is False+ assert cell.name == "mock_func1"+ assert cell.run() == (None, {"x": 4})def test_decorator_uncalled() -> None:- # Decorator uncalled- @app.celldef __() -> tuple[int]:z = 3 + 3return (z,)- assert cell_function.cell.code == "z = 3 + 3"- assert cell_function.cell.config.disabled is False- assert len(cell_function.args) == 0- assert cell_function.__name__ == "__"- assert cell_function.__call__ is not None- assert cell_function.__call__() == (6,)+ app = App()+ cell = app.cell(__)+ assert cell is not None+ assert cell._cell.code == "z = 3 + 3"+ assert cell._cell.config.disabled is False+ assert cell.name == "__"+ assert cell.run() == (None, {"z": 6})def test_decorator_with_args() -> None:- # Decorator with args- @app.cell(disabled=True)def mock_func3(x: int) -> tuple[int]:y = x + 2return (y,)- assert cell_function.cell.code == "y = x + 2"- assert cell_function.cell.config.disabled is True- assert cell_function.args == {"x"}- assert cell_function.__name__ == "mock_func3"- assert cell_function.__call__ is not None- assert cell_function.__call__(2) == (4,)+ app = App()+ cell = app.cell(disabled=True)(mock_func3)+ assert cell is not None++ assert cell._cell.code == "y = x + 2"+ assert cell._cell.config.disabled is True+ assert cell.name == "mock_func3"+ assert cell.run(x=1) == (None, {"y": 3})def test_decorator_with_unknown_args() -> None:# Decorator with unknown args- @app.cell(foo=True)def __() -> tuple[int]:x = 2 + 2return (x,)- assert cell_function.cell.code == "x = 2 + 2"- assert cell_function.cell.config.disabled is False- assert len(cell_function.args) == 0- assert cell_function.__name__ == "__"- assert cell_function.__call__ is not None- assert cell_function.__call__() == (4,)+ app = App()+ cell = app.cell(foo=True)(__)+ assert cell is not None++ assert cell._cell.code == "x = 2 + 2"+ assert cell._cell.config.disabled is False+ assert cell.name == "__"+ assert cell.run() == (None, {"x": 4})async def test_decorator_async() -> None:# Decorator uncalled- @app.cellasync def __(asyncio) -> tuple[int]:await asyncio.sleep(0.1)z = 3 + 3return (z,)- assert inspect.iscoroutinefunction(cell_function)- assert cell_function.cell.config.disabled is False- assert len(cell_function.args) == 1- assert cell_function.__name__ == "__"- assert cell_function.__call__ is not None+ app = App()+ cell = app.cell(__)+ assert cell is not None++ assert inspect.iscoroutinefunction(cell._f)+ assert cell._cell.config.disabled is False+ assert cell.name == "__"import asyncio- assert (await cell_function(asyncio)) == (6,)+ result = cell.run(asyncio=asyncio)+ assert isinstance(result, Awaitable)+ assert await result == (None, {"z": 6})+++# TODO(akshayka): test cell.run() with multiple cells in graph, outputs, ...diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.pynew file mode 100644index 0000000000..f926fa8110--- /dev/null+++ b/tests/_ast/test_cell.py@@ -0,0 +1,204 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from collections.abc import Awaitable++import pytest++from marimo._ast.app import App+++class TestCellRun:+ @staticmethod+ def test_cell_basic() -> None:+ def f() -> tuple[int]:+ x = 2 + 2+ "output"+ return (x,)++ app = App()+ cell = app.cell(f)+ assert cell.name == "f"+ assert not cell.refs+ assert cell.defs == set(["x"])+ assert not cell._is_coroutine()+ assert cell.run() == ("output", {"x": 4})++ @staticmethod+ async def test_async_cell_basic() -> None:+ async def f(asyncio) -> tuple[int]:+ await asyncio.sleep(0)++ x = 2 + 2+ "output"+ return (x,)++ app = App()+ cell = app.cell(f)+ assert cell.name == "f"+ assert cell.refs == {"asyncio"}+ assert cell.defs == {"x"}+ assert cell._is_coroutine()++ import asyncio++ ret = cell.run(asyncio=asyncio)+ assert isinstance(ret, Awaitable)+ assert await ret == ("output", {"x": 4})++ @staticmethod+ def test_unknown_ref_raises() -> None:+ def f() -> None:+ ...++ app = App()+ cell = app.cell(f)+ with pytest.raises(ValueError) as einfo:+ cell.run(foo=1)+ assert "unexpected argument" in str(einfo.value)++ @staticmethod+ def test_substituted_ref_basic() -> None:+ app = App()++ @app.cell+ def g():+ x = 0+ y = 1+ return (x, y)++ @app.cell+ def h(x, y):+ z = x + y+ return (z,)++ assert h.run() == (None, {"z": 1})+ assert h.run(x=1) == (None, {"z": 2})+ assert h.run(y=0) == (None, {"z": 0})+ assert h.run(x=1, y=2) == (None, {"z": 3})++ @staticmethod+ def test_substituted_ref_chain() -> None:+ app = App()++ @app.cell+ def f():+ x = 0+ return (x,)++ @app.cell+ def g(x):+ y = x + 1+ return (y,)++ @app.cell+ def h(y):+ z = 2 * y+ return (z,)++ assert h.run() == (None, {"z": 2})+ assert h.run(y=0) == (None, {"z": 0})++ with pytest.raises(ValueError) as e:+ h.run(x=1)+ assert "unexpected argument" in str(e.value)++ @staticmethod+ def test_async_parent() -> None:+ app = App()++ @app.cell+ async def g(arg):+ await arg+ x = 0+ return (x,)++ @app.cell+ def h(x):+ y = x+ return (y,)++ assert g._is_coroutine()+ # h is a coroutine because it depends on the execution of an async+ # function+ assert h._is_coroutine()++ @staticmethod+ def test_async_chain() -> None:+ app = App()++ @app.cell+ async def f(arg):+ await arg+ x = 0+ return (x,)++ @app.cell+ def g(x):+ y = x+ return (y,)++ @app.cell+ def h(y):+ z = y+ return (z,)++ assert f._is_coroutine()+ assert g._is_coroutine()+ assert h._is_coroutine()++ @staticmethod+ def test_empty_cell() -> None:+ app = App()++ @app.cell+ def f():+ return++ assert f.run() == (None, {})++ @staticmethod+ def test_conditional_def() -> None:+ app = App()++ @app.cell+ def f():+ if False:+ x = 0+ return (x,)++ # "x" was statically declared+ assert f.defs == {"x"}+ # "x" should not be in returns because it wasn't defined at runtime+ assert f.run() == (None, {})++ @staticmethod+ def test_import() -> None:+ from cell_data.named_cells import f, g, h++ assert f.name == "f"+ assert g.name == "g"+ assert h.name == "h"++ assert f.run() == (None, {"x": 0})+ assert g.run() == (None, {"y": 1})+ assert h.run() == (2, {"z": 2})++ assert g.run(x=1) == (None, {"y": 2})+ assert h.run(y=2) == (3, {"z": 3})+++def help_smoke() -> None:+ app = App()++ @app.cell+ async def f(x):+ await x+ return++ @app.cell+ def g():+ return++ assert "Async" in f._help().text+ assert "Async" not in g._help().textdiff --git a/tests/_ast/test_compiler.py b/tests/_ast/test_compiler.pyindex 7df0d67bf6..2ae9700519 100644--- a/tests/_ast/test_compiler.py+++ b/tests/_ast/test_compiler.py@@ -84,9 +84,9 @@ class TestCellFactory:x = 10 # noqa: F841y = 20 # noqa: F841- cf = compiler.cell_factory(f, cell_id="0")- assert cf.cell.defs == {"x", "y"}- assert not cf.cell.refs+ cell = compiler.cell_factory(f, cell_id="0")+ assert cell._cell.defs == {"x", "y"}+ assert not cell._cell.refs@staticmethoddef test_refs() -> None:@@ -95,9 +95,9 @@ class TestCellFactory:def f() -> None:x = y # noqa: F841 F821- cf = compiler.cell_factory(f, cell_id="0")- assert cf.cell.defs == {"x"}- assert cf.cell.refs == {"y"}+ cell = compiler.cell_factory(f, cell_id="0")+ assert cell._cell.defs == {"x"}+ assert cell._cell.refs == {"y"}def test_cell_id_from_filename() -> None:diff --git a/tests/_plugins/ui/_impl/test_altair_chart.py b/tests/_plugins/ui/_impl/test_altair_chart.pyindex 5150912ce6..54bb8be322 100644--- a/tests/_plugins/ui/_impl/test_altair_chart.py+++ b/tests/_plugins/ui/_impl/test_altair_chart.py@@ -9,7 +9,7 @@ from marimo._plugins.ui._impl.altair_chart import (_filter_dataframe,)from marimo._runtime.runtime import Kernel-from tests.conftest import ExecReqProvider, MockedKernel+from tests.conftest import ExecReqProviderHAS_DEPS = DependencyManager.has_pandas() and DependencyManager.has_altair()diff --git a/tests/_runtime/runtime_data/cell_ui_element.py b/tests/_runtime/runtime_data/cell_ui_element.pynew file mode 100644index 0000000000..820d5326cd--- /dev/null+++ b/tests/_runtime/runtime_data/cell_ui_element.py@@ -0,0 +1,17 @@+import marimo++__generated_with = "0.2.8"+app = marimo.App()+++def make_slider():+ import marimo as mo++ slider = mo.ui.slider(0, 10)+ slider+ return (mo, slider)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.pyindex 769dc2d0be..41fb2e482b 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -830,6 +830,35 @@ async def test_pickle(k: Kernel, exec_req: ExecReqProvider) -> None:assert k.globals["pickle_output"] is not None+async def test_set_ui_element_value_with_cell_run(+ k: Kernel, exec_req: ExecReqProvider+) -> None:+ # This test imports a cell from another notebook that defines a UI element+ # It then sets a value on the UI element, and makes sure that reactivity+ # flows through the defs mapping that is returned+ await k.run(+ [+ exec_req.get(+ "from runtime_data.cell_ui_element import make_slider"+ ),+ exec_req.get("_, defs = make_slider.run()"),+ exec_req.get("_, second_defs = make_slider.run()"),+ exec_req.get("counter = [0]"),+ exec_req.get("slider_value = defs['slider'].value + 1"),+ exec_req.get("second_defs; counter[0] += 1"),+ ]+ )+ assert k.globals["defs"]["slider"].value == 0+ assert k.globals["counter"][0] == 1+ element_id = k.globals["defs"]["slider"]._id+ await k.set_ui_element_value(SetUIElementValueRequest([(element_id, 5)]))+ assert k.globals["defs"]["slider"].value == 5+ assert k.globals["slider_value"] == 6+ # reactive execution on the slider in `defs` shouldn't trigger reactive+ # execution on `second_defs`+ assert k.globals["counter"][0] == 1++class TestAsyncIO:@staticmethodasync def test_toplevel_await_allowed(