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.

feat: make cells runnable with full arguments (#3251)

Dylan Madisetti4df5ca785efb
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 1bd04805e3..d91bbacb9d 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import functools
import inspect
+import os
import random
import string
from dataclasses import asdict, dataclass, field
@@ -29,6 +30,7 @@ from marimo._ast.errors import (
UnparsableError,
)
from marimo._ast.names import DEFAULT_CELL_NAME
+from marimo._ast.pytest import wrap_fn_for_pytest
from marimo._config.config import WidthType
from marimo._messaging.mimetypes import KnownMimeType
from marimo._output.hypertext import Html
@@ -465,6 +467,14 @@ class CellManager:
)
cell._cell.configure(cell_config)
self._register_cell(cell, app=app)
+ # Manually set the signature for pytest.
+ # Use PYTEST_VERSION here, opposed to PYTEST_CURRENT_TEST, in
+ # order to allow execution during test collection.
+ if (
+ "PYTEST_VERSION" in os.environ
+ and "PYTEST_CURRENT_TEST" not in os.environ
+ ):
+ func = wrap_fn_for_pytest(func, cell)
# NB. in place metadata update.
functools.wraps(func)(cell)
return cell
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 51b6467525..863f0abcb8 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -4,16 +4,19 @@ from __future__ import annotations
import ast
import dataclasses
import inspect
+import os
+from collections.abc import Awaitable
from typing import TYPE_CHECKING, Any, Literal, Mapping, Optional
from marimo._ast.sql_visitor import SQLVisitor
from marimo._ast.visitor import ImportData, Language, Name, VariableData
+from marimo._runtime.exceptions import MarimoRuntimeException
from marimo._utils.deep_merge import deep_merge
CellId_t = str
if TYPE_CHECKING:
- from collections.abc import Awaitable, Iterable
+ from collections.abc import Iterable
from types import CodeType
from marimo._ast.app import InternalApp
@@ -348,6 +351,9 @@ class Cell:
# App to which this cell belongs
_app: InternalApp | None = None
+ # Number of reserved arguments for pytest
+ _pytest_reserved: set[str] = dataclasses.field(default_factory=set)
+
@property
def name(self) -> str:
return self._name
@@ -525,22 +531,72 @@ class Cell:
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()`"
+ try:
+ 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)
+ except MarimoRuntimeException as e:
+ raise e.__cause__ from None # type: ignore
+
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
+ # TODO: Expand for top level modules when/ if the time comes.
+ arg_names = sorted(
+ self._cell.refs - set(globals()["__builtins__"].keys())
+ )
+ argc = len(arg_names)
+
+ call_args = {name: arg for name, arg in zip(arg_names, args)}
+ call_args.update(kwargs)
+ call_argc = len(call_args.keys()) + len(self._pytest_reserved)
+
+ is_pytest = "PYTEST_CURRENT_TEST" in os.environ
+ # Capture pytest case, where arguments don't match the references.
+ if self._pytest_reserved - set(arg_names):
+ raise TypeError(
+ "A mismatch in expected argument names likely means you should "
+ "resave the notebook in the marimo editor."
+ )
+
+ # If all the arguments are provided, then run as if it were a normal
+ # function call. An incorrect number of arguments will raise a
+ # TypeError (the same as a normal function call).
+ #
+ # pytest is an exception here, since it enables testing directly on
+ # notebooks, and the graph will be executed if needed.
+ if argc == call_argc and (
+ is_pytest or all(name in call_args for name in arg_names)
+ ):
+ # Note, run returns a tuple of (output, defs)-
+ # so stripped defs is required.
+ ret = self.run(**call_args)
+ if isinstance(ret, Awaitable):
+
+ async def await_and_return() -> Any:
+ output, _ = await ret
+ return output
+
+ return await_and_return()
+ else:
+ output, _ = ret
+ return output
+
+ if is_pytest:
+ call_str = (
+ "A mismatch in arguments likely means you should "
+ "resave the notebook in the marimo editor."
+ )
else:
- call_str = f"`outputs, defs = {self.name}.run()`"
+ await_str = "await " if self._is_coroutine else ""
+ call_str = (
+ "Consider calling with `outputs, defs = "
+ f"{await_str}{self.name}.run()`"
+ )
- raise RuntimeError(
- f"Calling marimo cells using `{self.name}()` is not supported. "
- f"Use {call_str} instead. "
+ raise TypeError(
+ f"{self.name}() takes {argc} positional arguments but "
+ f"{call_argc} were given. {call_str}"
)
diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.py
new file mode 100644
index 0000000000..e5c322c086
--- /dev/null
+++ b/marimo/_ast/pytest.py
@@ -0,0 +1,80 @@
+# Copyright 2024 Marimo. All rights reserved.
+import ast
+import copy
+import inspect
+from typing import Any, Callable, cast
+
+from marimo._ast.cell import Cell
+
+
+# Python definition used as the ast bones for constructing a pytest function.
+def _pytest_scaffold(stub: Any) -> Any:
+ return stub(stub=stub)
+
+
+PYTEST_BASE = ast.parse(inspect.getsource(_pytest_scaffold))
+
+
+def wrap_fn_for_pytest(
+ func: Callable[..., Any], cell: Cell
+) -> Callable[..., Any]:
+ # We modify the signature of the cell function such that pytest
+ # does not attempt to use the arguments as fixtures.
+
+ func_ast = ast.parse(inspect.getsource(func))
+ func_body = func_ast.body[0]
+ assert isinstance(func_body, (ast.FunctionDef, ast.AsyncFunctionDef))
+
+ args = {arg.arg: arg for arg in func_body.args.args}
+ fixtures = [arg for arg in args.keys() if arg.endswith("_fixture")]
+ reserved = set(args.keys()) - set(fixtures)
+ name = func.__name__
+
+ # Typing checks for mypy
+ fn = copy.deepcopy(PYTEST_BASE)
+ body = fn.body[0]
+ assert isinstance(body, ast.FunctionDef)
+ returned = body.body[-1]
+ assert isinstance(returned, ast.Return)
+ call = returned.value
+ assert isinstance(call, ast.Call)
+
+ # Using _pytest_scaffold as a template, the resultant function will look
+ # like:
+ #
+ # ```python
+ # def name_of_fn_passed(vars_ending_in_fixture, ...) -> Any:
+ # return cell(vars_ending_in_fixture=vars_ending_in_fixture)
+ # ```
+ #
+ # Which is sufficient to fool pytest.
+ body.args.args[:] = [
+ ast.arg(arg, lineno=args[arg].lineno, col_offset=args[arg].col_offset)
+ for arg in fixtures
+ ]
+ (call_stub,) = call.keywords
+ call.keywords = [
+ ast.keyword(
+ arg=arg,
+ value=ast.Name(
+ arg,
+ ctx=ast.Load(),
+ lineno=args[arg].lineno,
+ col_offset=args[arg].col_offset,
+ ),
+ lineno=args[arg].lineno,
+ col_offset=args[arg].col_offset,
+ )
+ for arg in fixtures
+ ]
+ body.name = name
+ local = {"stub": cell.__call__, "Any": Any}
+ eval(compile(fn, inspect.getfile(func), "exec"), local)
+
+ # The remaining expected attributes is needed to ensure attribute count
+ # matches.
+ cell._pytest_reserved = reserved
+
+ response = cast(Callable[..., Any], local[name])
+ assert callable(response)
+ return response
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index 8db6fcf06e..76d8a15bd9 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -13,9 +13,11 @@ from marimo._runtime.context.types import (
runtime_context_installed,
teardown_context,
)
-from marimo._runtime.executor import (
+from marimo._runtime.exceptions import (
MarimoMissingRefError,
MarimoRuntimeException,
+)
+from marimo._runtime.executor import (
execute_cell,
execute_cell_async,
)
diff --git a/marimo/_runtime/app_meta.py b/marimo/_runtime/app_meta.py
index ff13c52d31..2e39a8c20a 100644
--- a/marimo/_runtime/app_meta.py
+++ b/marimo/_runtime/app_meta.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Literal, Optional
+from typing import Optional
from marimo._config.config import DEFAULT_CONFIG
from marimo._output.rich_help import mddoc
@@ -9,7 +9,7 @@ from marimo._runtime.context.types import (
ContextNotInitializedError,
get_context,
)
-from marimo._runtime.context.utils import get_mode
+from marimo._runtime.context.utils import RunMode, get_mode
@mddoc
@@ -53,7 +53,7 @@ class AppMeta:
return theme
@property
- def mode(self) -> Optional[Literal["edit", "run", "script"]]:
+ def mode(self) -> Optional[RunMode]:
"""
The execution mode of the app.
@@ -69,6 +69,7 @@ class AppMeta:
- "edit": The notebook is being edited in the marimo editor
- "run": The notebook is being run as an app
- "script": The notebook is being run as a script
+ - "test": The cell has been invoked by a test
- None: The mode could not be determined
"""
return get_mode()
diff --git a/marimo/_runtime/context/utils.py b/marimo/_runtime/context/utils.py
index 67b20636ba..10982b145c 100644
--- a/marimo/_runtime/context/utils.py
+++ b/marimo/_runtime/context/utils.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import os
from typing import Literal, Optional
from marimo._output.rich_help import mddoc
@@ -8,6 +9,8 @@ from marimo._runtime.context import ContextNotInitializedError, get_context
from marimo._server.model import SessionMode
from marimo._utils.assert_never import assert_never
+RunMode = Literal["run", "edit", "script", "test"]
+
@mddoc
def running_in_notebook() -> bool:
@@ -23,11 +26,11 @@ def running_in_notebook() -> bool:
return isinstance(ctx, KernelRuntimeContext)
-def get_mode() -> Optional[Literal["run", "edit", "script"]]:
+def get_mode() -> Optional[RunMode]:
"""Returns the current mode of the marimo app.
Returns:
- Optional[Literal["run", "edit", "script"]]: The current mode,
+ Optional[Literal["run", "edit", "script", "test"]]: The current mode,
or None if marimo has no context initialized.
"""
try:
@@ -47,4 +50,10 @@ def get_mode() -> Optional[Literal["run", "edit", "script"]]:
return "script"
except ContextNotInitializedError:
pass
+
+ # This is a fallback, it's possible to be in pytest mode and have a context,
+ # as in native marimo tests.
+ if "PYTEST_CURRENT_TEST" in os.environ:
+ return "test"
+
return None
diff --git a/marimo/_runtime/dataflow.py b/marimo/_runtime/dataflow.py
index cd74deddf7..8eb232b89f 100644
--- a/marimo/_runtime/dataflow.py
+++ b/marimo/_runtime/dataflow.py
@@ -617,7 +617,7 @@ class Runner:
for argname in kwargs:
if argname not in cell_impl.refs:
raise ValueError(
- f"Cell got unexpected argument {argname}"
+ f"Cell got unexpected argument {argname}; "
f"The allowed arguments are {cell_impl.refs}."
)
diff --git a/marimo/_runtime/exceptions.py b/marimo/_runtime/exceptions.py
new file mode 100644
index 0000000000..c3207c4deb
--- /dev/null
+++ b/marimo/_runtime/exceptions.py
@@ -0,0 +1,25 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Optional
+
+
+class MarimoRuntimeException(BaseException):
+ """Wrapper for all marimo runtime exceptions."""
+
+
+class MarimoNameError(NameError):
+ """Wrap a name error to rethrow later."""
+
+ def __init__(self, msg: str, ref: str) -> None:
+ super().__init__(msg)
+ self.ref = ref
+
+
+class MarimoMissingRefError(BaseException):
+ def __init__(
+ self, ref: str, name_error: Optional[NameError] = None
+ ) -> None:
+ super(MarimoMissingRefError, self).__init__(ref)
+ self.ref = ref
+ self.name_error = name_error
diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.py
index 0023cbe0fa..2f90ab9cf1 100644
--- a/marimo/_runtime/executor.py
+++ b/marimo/_runtime/executor.py
@@ -14,6 +14,11 @@ from marimo._runtime.copy import (
ZeroCopy,
shallow_copy,
)
+from marimo._runtime.exceptions import (
+ MarimoMissingRefError,
+ MarimoNameError,
+ MarimoRuntimeException,
+)
from marimo._runtime.primitives import (
CLONE_PRIMITIVES,
build_ref_predicate_for_primitives,
@@ -29,27 +34,6 @@ if TYPE_CHECKING:
EXECUTION_TYPES: dict[str, Type[Executor]] = {}
-class MarimoRuntimeException(BaseException):
- """Wrapper for all marimo runtime exceptions."""
-
-
-class MarimoNameError(NameError):
- """Wrap a name error to rethrow later."""
-
- def __init__(self, msg: str, ref: str) -> None:
- super().__init__(msg)
- self.ref = ref
-
-
-class MarimoMissingRefError(BaseException):
- def __init__(
- self, ref: str, name_error: Optional[NameError] = None
- ) -> None:
- super(MarimoMissingRefError, self).__init__(ref)
- self.ref = ref
- self.name_error = name_error
-
-
def raise_name_error(
graph: Optional[DirectedGraph], name_error: NameError
) -> None:
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index 19b8bdedd6..c085823939 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -23,10 +23,12 @@ from marimo._messaging.errors import (
from marimo._messaging.tracebacks import write_traceback
from marimo._runtime import dataflow
from marimo._runtime.control_flow import MarimoInterrupt, MarimoStopError
-from marimo._runtime.executor import (
+from marimo._runtime.exceptions import (
MarimoMissingRefError,
MarimoNameError,
MarimoRuntimeException,
+)
+from marimo._runtime.executor import (
execute_cell,
execute_cell_async,
)
diff --git a/tests/_ast/test_pytest.py b/tests/_ast/test_pytest.py
new file mode 100644
index 0000000000..750e4c4185
--- /dev/null
+++ b/tests/_ast/test_pytest.py
@@ -0,0 +1,83 @@
+from __future__ import annotations
+
+import pytest
+
+import marimo
+
+app = marimo.App()
+
+
+def imports():
+ import marimo as mo
+
+ # Suffixed with _fixture should have corresponding definitions in conftest.py
+ mo_fixture = None
+
+ return mo, mo_fixture
+
+
+def test_cell_is_invoked():
+ assert True
+
+
+async def test_async_cell():
+ assert True
+
+
+def test_cell_has_builtin_refs():
+ assert len([print, sum, list]) == 3
+
+
+ reason=("Ensure correct errors are propagated through a failing cell."),
+ raises=ZeroDivisionError,
+ strict=True,
+)
+def test_cell_fails_correctly():
+ z = 1 / 0
+ return z
+
+
+def test_cell_deps_work(mo):
+ assert mo.app_meta().mode == "test"
+
+
+def test_cell_fixtures_work(mo_fixture):
+ assert mo_fixture.app_meta().mode == "test"
+
+
+ reason="Function actually expects 1 argument, but 0 are provided.",
+ raises=TypeError,
+ strict=True,
+)
+def test_cell_missing_refs_fail():
+ assert mo.app_meta().mode == "test" # noqa: F821
+
+
+ reason="Function actually expects 0 argument, but 1 is provided.",
+ raises=TypeError,
+ strict=True,
+)
+def test_cell_extra_refs_fail(mo): # noqa: ARG001
+ assert True
+
+
+ reason="Provided argument is not the expected argument.",
+ raises=TypeError,
+ strict=True,
+)
+def test_cell_args_resolved_by_name(mo): # noqa: ARG001
+ assert x # noqa: F821
diff --git a/tests/_runtime/test_app_mode.py b/tests/_runtime/test_app_mode.py
index aae5cc2b72..3a6f5c57b9 100644
--- a/tests/_runtime/test_app_mode.py
+++ b/tests/_runtime/test_app_mode.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import os
from unittest.mock import Mock, patch
from marimo._runtime.context import (
@@ -43,10 +44,21 @@ def test_get_mode_script():
assert get_mode() == "script"
+def test_get_mode_test():
+ """Test get_mode() returns 'test' when testing with no context"""
+ with patch(
+ "marimo._runtime.context.utils.get_context",
+ side_effect=ContextNotInitializedError,
+ ):
+ assert get_mode() == "test"
+
+
def test_get_mode_no_context():
- """Test get_mode() returns None when context is not initialized"""
+ """Test get_mode() returns 'test' when testing with no context"""
+ previous = os.environ.pop("PYTEST_CURRENT_TEST", None)
with patch(
"marimo._runtime.context.utils.get_context",
side_effect=ContextNotInitializedError,
):
assert get_mode() is None
+ os.environ["PYTEST_CURRENT_TEST"] = previous
diff --git a/tests/_runtime/test_pytest.py b/tests/_runtime/test_pytest.py
deleted file mode 100644
index ff77103657..0000000000
--- a/tests/_runtime/test_pytest.py
+++ /dev/null
@@ -1,21 +0,0 @@
-from __future__ import annotations
-
-import pytest
-
-import marimo
-
-app = marimo.App()
-
-
- reason=(
- "Invoking a cell is not directly supported, and as such should fail "
- "until #2293. However, the decorated function _should_ be picked up "
- "by pytest. The hook in conftest.py ensures this."
- ),
- raises=RuntimeError,
- strict=True,
-)
-def test_cell_is_invoked():
- assert True
diff --git a/tests/conftest.py b/tests/conftest.py
index 9504445334..c7b5c980a5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -8,7 +8,7 @@ import re
import sys
import textwrap
from tempfile import TemporaryDirectory
-from typing import Any, Generator
+from typing import TYPE_CHECKING, Any, Generator
import pytest
from _pytest import runner
@@ -35,6 +35,9 @@ from marimo._runtime.runtime import Kernel
from marimo._server.model import SessionMode
from marimo._utils.parse_dataclass import parse_raw
+if TYPE_CHECKING:
+ from types import ModuleType
+
# register import hooks for third-party module formatters
register_formatters()
@@ -494,7 +497,15 @@ def exec_req() -> ExecReqProvider:
return ExecReqProvider()
-# # A pytest hook to fail when raw marimo cells are not collected.
+# Library fixtures for direct marimo integration with pytest.
+def mo_fixture() -> ModuleType:
+ import marimo as mo
+
+ return mo
+
+
+# A pytest hook to fail when raw marimo cells are not collected.
@pytest.hookimpl
def pytest_make_collect_report(collector):
report = runner.pytest_make_collect_report(collector)
@@ -502,7 +513,7 @@ def pytest_make_collect_report(collector):
# for the test_pytest specific file here.
if "test_pytest" in str(collector.path):
collected = {fn.name: fn for fn in collector.collect()}
- from tests._runtime.test_pytest import app
+ from tests._ast.test_pytest import app
invalid = []
for name in app._cell_manager.names():