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.

Relax validation of args/returns on cells (#502)

Akshay Agrawalc8cac3cfcdfd
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 1279502264..cd469e7800 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -1,9 +1,6 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-import builtins
-import itertools
-import textwrap
from collections.abc import Sequence
from dataclasses import asdict, dataclass
from typing import Any, Callable, Iterable, Literal, Optional, Union, cast
@@ -189,39 +186,6 @@ class App:
cell_data.cell_function for cell_data in self._cell_data.values()
)
- def _validate_args(self) -> None:
- """Validate the args of each cell function.
-
- Args should match cell.refs, excluding builtins that haven't been
- shadowed by other cells.
-
- This function must be called after all cells have been parsed, because
- it's only then that we know the set of unshadowed builtins.
-
- Raises: ValueError if a cell has an invalid arg set.
- """
- defs = set(
- itertools.chain.from_iterable(
- f.cell.defs for f in self._cell_functions() if f is not None
- )
- )
- unshadowed_builtins = set(builtins.__dict__.keys()).difference(defs)
- for f in self._cell_functions():
- if f is None:
- continue
- expected_args = f.cell.refs - unshadowed_builtins
- if f.args != expected_args:
- suggested_sig = (
- f"def {f.__name__}({', '.join(sorted(expected_args))}):"
- )
- raise ValueError(
- "A cell must take all its refs as args. "
- "This rule is violated by the following function:\n\n"
- + textwrap.indent(f.code, prefix=" ")
- + "\n"
- f"Fix: Make '{suggested_sig}' this function's signature."
- )
-
def _unparsable_cell(
self,
code: str,
diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.py
index 1ba313eff1..9055bd40dc 100644
--- a/marimo/_ast/cell.py
+++ b/marimo/_ast/cell.py
@@ -269,6 +269,12 @@ def is_ws(char: str) -> bool:
def cell_factory(f: CellFuncTypeBound) -> CellFunction[CellFuncTypeBound]:
+ """Creates a cell from a function.
+
+ The signature and returns of the function are not used
+ to generate refs and defs. If the user introduced errors to the
+ signature, marimo will autofix them on save.
+ """
function_code = textwrap.dedent(inspect.getsource(f))
# tokenize to find the start of the function body, including
@@ -355,7 +361,7 @@ def cell_factory(f: CellFuncTypeBound) -> CellFunction[CellFuncTypeBound]:
first_line = lines[start_line][start_col:]
cell_code = textwrap.dedent(
"\n".join([first_line] + lines[start_line + 1 : end_line])
- )
+ ).strip()
if end_line is not None and not lines[end_line].strip().startswith(
"return"
):
@@ -366,70 +372,6 @@ def cell_factory(f: CellFuncTypeBound) -> CellFunction[CellFuncTypeBound]:
ret = cell_function(
parse_cell(cell_code), cast(Set[str], arg_names), function_code, f
)
- cell = ret.cell
-
- # signature validation: we make sure that all defs are returned, and all
- # refs are taken as inputs, so that the function code is consistent
- # with its representation as a marimo app.
- if cell.defs and return_node is None:
- suggested_return = "return " + ", ".join(sorted(cell.defs))
- raise ValueError(
- "The following function is missing a return statement:\n\n"
- + textwrap.indent(function_code, prefix=" ")
- + "\n"
- + f"Fix: Make '{suggested_return}' its last line.\n\n"
- )
- elif cell.defs and return_node is not None:
- if not isinstance(return_node.value, ast.Tuple):
- raise ValueError(
- "A cell must return a tuple of defs. "
- "This rule is violated by the following function:\n\n"
- + textwrap.indent(function_code, prefix=" ")
- + "\n"
- + "Fix: Change the return type to be a tuple."
- )
- names = set(elt.id for elt in return_node.value.elts) # type: ignore
- local_names = tuple(name for name in names if _is_local(name))
- if local_names:
- raise ValueError(
- "Names starting with underscores should not be returned by "
- "a cell. This rule is violated by the following function:\n\n"
- + textwrap.indent(function_code, prefix=" ")
- + "\n"
- + f"Fix: Remove {local_names} from this function's returns."
- )
-
- if names != cell.defs:
- suggested_return = "return " + ", ".join(sorted(cell.defs))
- raise ValueError(
- "A cell must return a tuple of all its "
- "defs. This rule is violated by the following function:\n\n"
- + textwrap.indent(function_code, prefix=" ")
- + "\n"
- + f"Fix: Make '{suggested_return}' this function's last line."
- )
- elif not cell.defs and return_node is not None:
- if return_node.value is not None:
- raise ValueError(
- "The following function shouldn't return anything, since "
- "it doesn't define any variables:\n\n"
- + textwrap.indent(function_code, prefix=" ")
- + "\n"
- + "Fix: Don't return anything from this function."
- )
-
- local_names = tuple(name for name in arg_names if _is_local(name))
- if local_names:
- raise ValueError(
- "Names starting with underscores should not be taken as "
- "parameters. This rule is violated by the following function:\n\n"
- + textwrap.indent(function_code, prefix=" ")
- + "\n"
- + f"Fix: Remove {local_names} from this function's argument list."
- )
-
- # NB: args can't be validated here, because we need to know which builtins
- # have been shadowed by other cells, if any.
return ret
diff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.py
index a4bd98416f..600304d390 100644
--- a/marimo/_ast/codegen.py
+++ b/marimo/_ast/codegen.py
@@ -202,7 +202,6 @@ def get_app(filename: Optional[str]) -> Optional[App]:
raise MarimoFileError("`app` attribute must be of type `marimo.App`.")
app = marimo_app.app
- app._validate_args()
return app
diff --git a/tests/_ast/codegen_data/test_get_codes_with_incorrect_args_rets.py b/tests/_ast/codegen_data/test_get_codes_with_incorrect_args_rets.py
new file mode 100644
index 0000000000..a20bc5553f
--- /dev/null
+++ b/tests/_ast/codegen_data/test_get_codes_with_incorrect_args_rets.py
@@ -0,0 +1,38 @@
+import marimo
+
+__generated_with = "0.1.0"
+app = marimo.App()
+
+
+def one():
+ import numpy as np
+
+
+def two():
+ x = 0
+ xx = 1
+ return x,
+
+
+def three():
+ y = x + 1
+
+
+def four(y):
+ # comment
+ z = np.array(x + y)
+ return z,
+
+
+def five():
+ # just a comment
+ ...
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index bb31acdcac..f1c938452b 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -74,6 +74,21 @@ class TestApp:
with pytest.raises(CycleError):
app.run()
+ @staticmethod
+ def test_cycle_missing_args_rets() -> None:
+ app = App()
+
+ @app.cell
+ def one():
+ x = y # noqa
+
+ @app.cell
+ def two():
+ y = x # noqa
+
+ with pytest.raises(CycleError):
+ app.run()
+
@staticmethod
def test_multiple_definitions() -> None:
app = App()
@@ -92,18 +107,31 @@ class TestApp:
app.run()
@staticmethod
- def test_delete_nonlocal() -> None:
+ def test_multiple_definitions_missing_args_rets() -> None:
app = App()
@app.cell
- def one() -> tuple[int]:
- x = 0
- return (x,)
+ def one():
+ x = 0 # noqa
@app.cell
- def two(x: int) -> None:
- del x
- return
+ def two():
+ x = 0 # noqa
+
+ with pytest.raises(MultipleDefinitionError):
+ app.run()
+
+ @staticmethod
+ def test_delete_nonlocal_missing_args_rets() -> None:
+ app = App()
+
+ @app.cell
+ def one():
+ x = 0 # noqa
+
+ @app.cell
+ def two():
+ del x # noqa
with pytest.raises(DeleteNonlocalError):
app.run()
diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.py
index 911f8de7db..880cb77c39 100644
--- a/tests/_ast/test_cell.py
+++ b/tests/_ast/test_cell.py
@@ -1,9 +1,6 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-import pytest
-
-from marimo._ast.app import App
from marimo._ast.cell import cell_factory, parse_cell
@@ -60,86 +57,24 @@ class TestParseCell:
class TestCellFactory:
@staticmethod
- def test_missing_return() -> None:
- def f() -> None:
- x = 10 # noqa: F841
-
- with pytest.raises(ValueError) as e:
- cell_factory(f)
+ def test_defs() -> None:
+ """defs inferred from function code, not returns"""
- assert "missing a return statement" in str(e.value)
-
- @staticmethod
- def test_not_tuple() -> None:
- def f() -> int:
+ def f() -> None:
x = 10 # noqa: F841
- return x
+ y = 20 # noqa: F841
- with pytest.raises(ValueError) as e:
- cell_factory(f) # type: ignore[type-var]
-
- assert "must return a tuple" in str(e.value)
+ cf = cell_factory(f)
+ assert cf.cell.defs == {"x", "y"}
+ assert not cf.cell.refs
@staticmethod
- def test_missing_some_defs() -> None:
- def f() -> tuple[int]:
- x = 10
- y = x # noqa: F841
- return (x,)
-
- with pytest.raises(ValueError) as e:
- cell_factory(f)
-
- assert "must return a tuple of all its defs" in str(e.value)
-
- @staticmethod
- def test_missing_some_refs() -> None:
- z = 0
-
- app = App()
-
- @app.cell
- def f(y: int) -> tuple[int]:
- x = y + z
- return (x,)
+ def test_refs() -> None:
+ """refs inferred from function code, not args"""
- with pytest.raises(ValueError) as e:
- app._validate_args()
-
- assert "must take all its refs as args" in str(e.value)
-
- @staticmethod
- def test_extra_returns() -> None:
- def f() -> tuple[int]:
- return (1,)
-
- with pytest.raises(ValueError) as e:
- cell_factory(f)
-
- assert "shouldn't return anything" in str(e.value)
-
- @staticmethod
- def return_local_variable() -> None:
- def f() -> tuple[int]:
- _x = 0
- return (_x,)
-
- with pytest.raises(ValueError) as e:
- cell_factory(f)
-
- assert "Names starting with underscores should not be returned" in str(
- e.value
- )
-
- @staticmethod
- def local_variable_as_arg() -> None:
- def f(_x: int) -> None:
- return
-
- with pytest.raises(ValueError) as e:
- cell_factory(f)
+ def f() -> None:
+ x = y # noqa: F841 F821
- assert (
- "Names starting with underscores should not be taken as "
- "parameters" in str(e.value)
- )
+ cf = cell_factory(f)
+ assert cf.cell.defs == {"x"}
+ assert cf.cell.refs == {"y"}
diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.py
index dc27a9d1e6..b8c6aaf79c 100644
--- a/tests/_ast/test_codegen.py
+++ b/tests/_ast/test_codegen.py
@@ -154,6 +154,21 @@ class TestGetCodes:
"# just a comment",
]
+ @staticmethod
+ def test_get_codes_with_incorrect_args_rets() -> None:
+ app = codegen.get_app(
+ get_filepath("test_get_codes_with_incorrect_args_rets")
+ )
+ assert app is not None
+ assert list(app._names()) == ["one", "two", "three", "four", "five"]
+ assert list(app._codes()) == [
+ "import numpy as np",
+ "x = 0\nxx = 1",
+ "y = x + 1",
+ "# comment\nz = np.array(x + y)",
+ "# just a comment\n...",
+ ]
+
@staticmethod
def test_get_codes_with_name_error() -> None:
# name mo is not defined --- make sure this file is still parseable