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: top level functions (#3755)
Dylan Madisetti74d33dfa86c6
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.pyindex a6ea2dfba7..c086eed5cc 100644--- a/marimo/_ast/app.py+++ b/marimo/_ast/app.py@@ -18,6 +18,9 @@ from typing import (Literal,Mapping,Optional,+ TypeVar,+ Union,+ cast,)from uuid import uuid4@@ -54,6 +57,8 @@ if TYPE_CHECKING:from marimo._plugins.core.web_component import JSONTypefrom marimo._runtime.context.types import ExecutionContext++Fn = TypeVar("Fn", bound=Callable[..., Any])LOGGER = _loggers.marimo_logger()@@ -82,6 +87,9 @@ class _AppConfig:default_factory=list)+ # Experimental top-level cell support+ _toplevel_fn: bool = False+@staticmethoddef from_untrusted_dict(updates: dict[str, Any]) -> _AppConfig:config = _AppConfig()@@ -95,7 +103,10 @@ class _AppConfig:return configdef asdict(self) -> dict[str, Any]:- return asdict(self)+ # Used for experimental hooks which start with _+ return {+ k: v for (k, v) in asdict(self).items() if not k.startswith("_")+ }def update(self, updates: dict[str, Any]) -> _AppConfig:config_dict = asdict(self)@@ -255,13 +266,13 @@ class App:def cell(self,- func: Callable[..., Any] | None = None,+ func: Fn | None = None,*,column: Optional[int] = None,disabled: bool = False,hide_code: bool = False,**kwargs: Any,- ) -> Cell | Callable[[Callable[..., Any]], Cell]:+ ) -> Cell | Callable[[Fn], Cell]:"""A decorator to add a cell to the app.This decorator can be called with or without parentheses. Each of the@@ -290,8 +301,62 @@ class App:"""del kwargs- return self._cell_manager.cell_decorator(- func, column, disabled, hide_code, app=InternalApp(self)+ return cast(+ Union[Cell, Callable[[Fn], Cell]],+ self._cell_manager.cell_decorator(+ func, column, disabled, hide_code, app=InternalApp(self)+ ),+ )++ def function(+ self,+ func: Fn | None = None,+ *,+ column: Optional[int] = None,+ disabled: bool = False,+ hide_code: bool = False,+ **kwargs: Any,+ ) -> Fn | Callable[[Fn], Fn]:+ """A decorator to wrap a callable function into a cell in the app.++ This decorator can be called with or without parentheses. Each of the+ following is valid:++ ```+ @app.function+ def add(a: int, b: int) -> int:+ return a + b+++ @app.function()+ def subtract(a: int, b: int):+ return a - b+++ @app.function(disabled=True)+ def multiply(a: int, b: int) -> int:+ return a * b+ ```++ Args:+ func: The decorated function.+ column: The column number to place this cell in.+ disabled: Whether to disable the cell.+ hide_code: Whether to hide the cell's code.+ **kwargs: For forward-compatibility with future arguments.+ """+ del kwargs++ return cast(+ Union[Fn, Callable[[Fn], Fn]],+ self._cell_manager.cell_decorator(+ func,+ column,+ disabled,+ hide_code,+ app=InternalApp(self),+ top_level=True,+ ),)def _unparsable_cell(diff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex f2fb2acb68..ecced9c243 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -289,6 +289,45 @@ class CellImpl:def is_coroutine(self) -> bool:return _is_coroutine(self.body) or _is_coroutine(self.last_expr)+ @property+ def is_toplevel_acceptable(self) -> bool:+ # Check no defs aside from the single function+ if len(self.defs) != 1:+ return False++ # Must be parsable+ try:+ tree = ast.parse(self.code)+ except SyntaxError:+ return False++ # Must be a bare function.+ if not (+ len(tree.body) == 1+ and isinstance(+ tree.body[0], (ast.FunctionDef, ast.AsyncFunctionDef)+ )+ ):+ return False++ # Check that def matches the single definition+ name = tree.body[0].name+ if not (name == list(self.defs)[0] and name in self.variable_data):+ return False++ # No required_refs are allowed for now+ # TODO: Allow imports and other toplevel functions+ refs = set().union(+ *[v.required_refs for v in self.variable_data[name]]+ )+ refs -= set(globals()["__builtins__"].keys())+ # Allow recursion+ refs -= {name}+ if refs:+ return False++ return True+def set_runtime_state(self, status: RuntimeStateType, stream: Stream | None = None) -> None:diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.pyindex 37b443bfe0..dbd7287019 100644--- a/marimo/_ast/cell_manager.py+++ b/marimo/_ast/cell_manager.py@@ -11,10 +11,11 @@ from typing import (Callable,Iterable,Optional,+ TypeVar,)from marimo._ast.cell import Cell, CellConfig, CellId_t-from marimo._ast.compiler import cell_factory+from marimo._ast.compiler import cell_factory, toplevel_cell_factoryfrom marimo._ast.models import CellDatafrom marimo._ast.names import DEFAULT_CELL_NAMEfrom marimo._ast.pytest import wrap_fn_for_pytest@@ -22,6 +23,8 @@ from marimo._ast.pytest import wrap_fn_for_pytestif TYPE_CHECKING:from marimo._ast.app import InternalApp+ Fn = TypeVar("Fn", bound=Callable[..., Any])+class CellManager:"""A manager for cells in a marimo notebook.@@ -71,25 +74,28 @@ class CellManager:# TODO: maybe remove this, it is leakydef cell_decorator(self,- func: Callable[..., Any] | None,+ func: Fn | None,column: Optional[int],disabled: bool,hide_code: bool,app: InternalApp | None = None,- ) -> Cell | Callable[..., Cell]:+ *,+ top_level: bool = False,+ ) -> Cell | Fn | Callable[[Fn], Cell | Fn]:"""Create a cell decorator for marimo notebook cells."""cell_config = CellConfig(column=column, disabled=disabled, hide_code=hide_code)- def _register(func: Callable[..., Any]) -> Cell:+ def _register(func: Fn) -> Cell | Fn:# Use PYTEST_VERSION here, opposed to PYTEST_CURRENT_TEST, in# order to allow execution during test collection.is_top_level_pytest = ("PYTEST_VERSION" in os.environand "PYTEST_CURRENT_TEST" not in os.environ)- cell = cell_factory(+ factory = toplevel_cell_factory if top_level else cell_factory+ cell = factory(func,cell_id=self.create_cell_id(),anonymous_file=app._app._anonymous_file if app else False,@@ -98,9 +104,14 @@ class CellManager:)cell._cell.configure(cell_config)self._register_cell(cell, app=app)++ # Top level functions are exposed as the function itself.+ if top_level:+ return func+# Manually set the signature for pytest.if is_top_level_pytest:- func = wrap_fn_for_pytest(func, cell)+ func = wrap_fn_for_pytest(func, cell) # type: ignore# NB. in place metadata update.functools.wraps(func)(cell)return cell@@ -109,7 +120,7 @@ class CellManager:# 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: Callable[..., Any]) -> Cell:+ def decorator(func: Fn) -> Cell | Fn:return _register(func)return decoratordiff --git a/marimo/_ast/codegen.py b/marimo/_ast/codegen.pyindex 16c31663f8..28417c294a 100644--- a/marimo/_ast/codegen.py+++ b/marimo/_ast/codegen.py@@ -6,7 +6,7 @@ import builtinsimport importlib.utilimport jsonimport os-from typing import TYPE_CHECKING, Any, List, Optional, Union, cast+from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union, castfrom marimo import __version__from marimo._ast.app import App, _AppConfig@@ -35,9 +35,11 @@ def _multiline_tuple(elems: Sequence[str]) -> str:return "()"-def _to_decorator(config: Optional[CellConfig]) -> str:+def _to_decorator(+ config: Optional[CellConfig], fn: Literal["cell", "function"] = "cell"+) -> str:if config is None:- return "@app.cell"+ return f"@app.{fn}"# Removed defaults. If the cell's config is the default config,# don't include it in the decorator.@@ -49,10 +51,10 @@ def _to_decorator(config: Optional[CellConfig]) -> str:del config.columnif config == CellConfig():- return "@app.cell"+ return f"@app.{fn}"else:return (- "@app.cell("+ f"@app.{fn}("+ ", ".join(f"{key}={value}" for key, value in config.__dict__.items())@@ -101,6 +103,16 @@ def to_functiondef(return fndef+def to_top_functiondef(cell: CellImpl) -> str:+ # For the top-level function criteria to be satisfied,+ # the cell, it must pass basic checks in the cell impl.+ assert cell.is_toplevel_acceptable, "Cell is not a top-level function"+ if cell.code:+ decorator = _to_decorator(cell.config, fn="function")+ return "\n".join([decorator, cell.code.strip()])+ return ""++def generate_unparsable_cell(code: str, name: Optional[str], config: CellConfig) -> str:@@ -158,6 +170,10 @@ def generate_filecontents(header_comments: Optional[str] = None,) -> str:"""Translates a sequences of codes (cells) to a Python file"""+ # Until an appropriate means of controlling top-level functions exists,+ # Let's keep it disabled by default.+ toplevel_fn = config is not None and config._toplevel_fn+cell_data: list[Union[CellImpl, tuple[str, CellConfig]]] = []defs: set[Name] = set()@@ -183,7 +199,10 @@ def generate_filecontents(for data, name in zip(cell_data, names):if isinstance(data, CellImpl):- fndefs.append(to_functiondef(data, name, unshadowed_builtins))+ if toplevel_fn and data.is_toplevel_acceptable:+ fndefs.append(to_top_functiondef(data))+ else:+ fndefs.append(to_functiondef(data, name, unshadowed_builtins))else:fndefs.append(generate_unparsable_cell(diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 4a66431cfa..907928992e 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -229,6 +229,73 @@ def compile_cell()+def get_source_position(+ f: Callable[..., Any], lineno: int, col_offset: int+) -> Optional[SourcePosition]:+ # Fallback won't capture embedded scripts+ is_script = f.__globals__["__name__"] == "__main__"+ # TODO: spec is None for markdown notebooks, which is fine for now+ if module := inspect.getmodule(f):+ spec = module.__spec__+ is_script = spec is None or spec.name != "marimo_app"++ if not is_script:+ return None++ return SourcePosition(+ filename=f.__code__.co_filename,+ lineno=lineno,+ col_offset=col_offset,+ )+++def toplevel_cell_factory(+ f: Callable[..., Any],+ cell_id: CellId_t,+ anonymous_file: bool = False,+ test_rewrite: bool = False,+) -> Cell:+ """Creates a cell containing a function.++ NB: Unlike cell_factory, this utilizes the function itself as the cell+ definition. As such, signature and return type are important.+ """+ code, lnum = inspect.getsourcelines(f)+ function_code = textwrap.dedent("".join(code))++ # We need to scrub through the initial decorator. Since we don't care about+ # indentation etc, easiest just to use AST.++ tree = ast.parse(function_code, type_comments=True)+ try:+ decorator = tree.body[0].decorator_list.pop(0) # type: ignore+ # NB. We don't unparse from the AST because it strips comments.+ cell_code = textwrap.dedent(+ "".join(code[decorator.end_lineno :])+ ).strip()+ except (IndexError, AttributeError) as e:+ raise ValueError(+ "Unexpected usage (expected decorated function)"+ ) from e++ source_position = None+ if not anonymous_file:+ source_position = get_source_position(+ f,+ lnum + decorator.end_lineno - 1, # Scrub the decorator+ 0,+ )+ return Cell(+ _name=f.__name__,+ _cell=compile_cell(+ cell_code,+ cell_id=cell_id,+ source_position=source_position,+ test_rewrite=test_rewrite,+ ),+ )++def cell_factory(f: Callable[..., Any],cell_id: CellId_t,@@ -344,24 +411,11 @@ def cell_factory(cell_code += "\n" + lines[end_line][:return_offset]# anonymous file is required for deterministic testing.+ source_position = Noneif not anonymous_file:- # Fallback won't capture embedded scripts- is_script = f.__globals__["__name__"] == "__main__"- # TODO: spec is None for markdown notebooks, which is fine for now- if module := inspect.getmodule(f):- spec = module.__spec__- is_script = spec is None or spec.name != "marimo_app"- else:- is_script = False- source_position = (- SourcePosition(- filename=f.__code__.co_filename,- lineno=lnum + start_line - 1,- col_offset=col_offset,+ source_position = get_source_position(+ f, lnum + start_line - 1, col_offset)- if is_script- else None- )return Cell(_name=f.__name__,diff --git a/marimo/_ast/pytest.py b/marimo/_ast/pytest.pyindex ad7d4dcfb1..bf8fcdac02 100644--- a/marimo/_ast/pytest.py+++ b/marimo/_ast/pytest.py@@ -2,10 +2,12 @@import astimport copyimport inspect-from typing import Any, Callable, cast+from typing import Any, Callable, TypeVar, castfrom marimo._ast.cell import Cell+Fn = TypeVar("Fn", bound=Callable[..., Any])+# Python definition used as the ast bones for constructing a pytest function.def _pytest_scaffold(stub: Any) -> Any:@@ -15,9 +17,7 @@ def _pytest_scaffold(stub: Any) -> Any:PYTEST_BASE = ast.parse(inspect.getsource(_pytest_scaffold))-def wrap_fn_for_pytest(- func: Callable[..., Any], cell: Cell-) -> Callable[..., Any]:+def wrap_fn_for_pytest(func: Fn, cell: Cell) -> Callable[..., Any]:# We modify the signature of the cell function such that pytest# does not attempt to use the arguments as fixtures.diff --git a/marimo/_smoke_tests/app_fn.py b/marimo/_smoke_tests/app_fn.pynew file mode 100644index 0000000000..7f8e776de6--- /dev/null+++ b/marimo/_smoke_tests/app_fn.py@@ -0,0 +1,85 @@+import marimo++__generated_with = "0.11.2"+app = marimo.App(_toplevel_fn=True)++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ # @app.function smoke test++ See [2293 for discussion](https://github.com/marimo-team/marimo/issues/2293)[^2293]++ [^2293]: https://github.com/marimo-team/marimo/issues/2293+ """+ )+ return+++def self_ref_fib(n: int) -> int:+ if n == 0:+ return 0+ if n == 1:+ return 1+ return self_ref_fib(n - 1) + self_ref_fib(n - 2)++[email protected](disabled=True, hide_code=True)+def divide(x, y):+ return y / x+++def subtraction(a: "int", b: "int") -> "int":+ return a - b+++# Comments inbetween+def multiply(a, b) -> "int":+ return a * b+++def addition(a: int, b: int) -> int:+ # int is considered no good, re-eval+ return a + b+++def bad_divide_curry(divide):+ # Has an external ref currently does not work+ def bad_divide_curry(x):+ # Filler line+ # To push the error+ return divide(0, x)+ # With lines below+ return (bad_divide_curry,)+++def _(addition, multiply, self_ref_fib):+ # Should be be a regular cell+ print(addition(21, 56))+ print(multiply(21, 56))+ print(self_ref_fib(10))+ return+++def _(bad_divide_curry):+ a = bad_divide_curry(1)+ return (a,)+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.pyindex 45198ed335..a879f1525d 100644--- a/marimo/_utils/parse_dataclass.py+++ b/marimo/_utils/parse_dataclass.py@@ -111,7 +111,9 @@ class DataclassParser:types = get_type_hints(cls)- snake_cased_values = {to_snake(k): v for k, v in values.items()}+ snake_cased_values = {+ to_snake(k): v for k, v in values.items() if not k.startswith("_")+ }if (not self.allow_unknown_keysand not snake_cased_values.keys() <= types.keys()diff --git a/openapi/api.yaml b/openapi/api.yamlindex d025b293aa..fe04d9d338 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -931,6 +931,8 @@ components:properties:app_config:properties:+ _toplevel_fn:+ type: booleanapp_title:nullable: truetype: string@@ -960,6 +962,7 @@ components:required:- width- auto_download+ - _toplevel_fntype: objectcapabilities:properties:diff --git a/tests/_ast/test_app_cell.py b/tests/_ast/test_app_cell.pyindex f3d4a46f08..0a00a2432a 100644--- a/tests/_ast/test_app_cell.py+++ b/tests/_ast/test_app_cell.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import textwrap+import typesfrom collections.abc import Awaitablefrom marimo._ast.app import App@@ -87,4 +89,71 @@ async def test_decorator_async() -> None:assert await result == (None, {"z": 6})+def test_function_decorator_called() -> None:+ app = App()++ @app.function()+ def mock_func(x) -> tuple[int]:+ return x + x++ assert isinstance(mock_func, types.FunctionType)++ (cell,) = app._cell_manager.cells()+ assert not isinstance(cell, types.FunctionType)++ assert cell.name == "mock_func"+ assert (+ cell.run()[1]["mock_func"].__code__.co_code+ == mock_func.__code__.co_code+ )+++def test_function_decorator_uncalled() -> None:+ app = App()++ @app.function+ def mock_func(x) -> tuple[int]:+ return x + x++ assert isinstance(mock_func, types.FunctionType)++ (cell,) = app._cell_manager.cells()+ assert not isinstance(cell, types.FunctionType)++ assert cell.name == "mock_func"+ assert (+ cell.run()[1]["mock_func"].__code__.co_code+ == mock_func.__code__.co_code+ )+++def test_function_decorator_with_args() -> None:+ app = App()++ @app.function(disabled=True)+ def mock_func(x: int) -> int:+ y = x + 2+ return y++ assert isinstance(mock_func, types.FunctionType)++ (cell,) = app._cell_manager.cells()+ assert cell is not None++ assert (+ cell._cell.code+ == textwrap.dedent("""+ def mock_func(x: int) -> int:+ y = x + 2+ return y+ """).strip()+ )+ assert cell._cell.config.disabled is True+ assert cell.name == "mock_func"+ assert (+ cell.run()[1]["mock_func"].__code__.co_code+ == mock_func.__code__.co_code+ )++# TODO(akshayka): test cell.run() with multiple cells in graph, outputs, ...diff --git a/tests/_ast/test_codegen.py b/tests/_ast/test_codegen.pyindex ac7e6e5d55..96344235f1 100644--- a/tests/_ast/test_codegen.py+++ b/tests/_ast/test_codegen.py@@ -7,7 +7,7 @@ import tempfilefrom functools import partialfrom inspect import cleandocfrom textwrap import dedent-from typing import Optional+from typing import Any, Optionalimport codegen_data.test_main as modimport pytest@@ -48,7 +48,7 @@ def wrap_generate_filecontents(codes: list[str],names: list[str],cell_configs: Optional[list[CellConfig]] = None,- config: Optional[_AppConfig] = None,+ **kwargs: Any,) -> str:"""Wraps codegen.generate_filecontents to make the@@ -58,7 +58,7 @@ def wrap_generate_filecontents(else:resolved_configs = cell_configsreturn codegen.generate_filecontents(- codes, names, cell_configs=resolved_configs, config=config+ codes, names, cell_configs=resolved_configs, **kwargs)@@ -565,6 +565,22 @@ class TestToFunctionDef:)assert fndef == expected+ def test_fn_with_empty_config(self) -> None:+ code = "\n".join(["def foo():", " x = 0", " return (x,)"])+ cell = compile_cell(code)+ cell = cell.configure(CellConfig())+ fndef = codegen.to_top_functiondef(cell)+ expected = "@app.function\n" + code+ assert fndef == expected++ def test_fn_with_all_config(self) -> None:+ code = "\n".join(["def foo():", " x = 0", " return (x,)"])+ cell = compile_cell(code)+ cell = cell.configure(CellConfig(disabled=True, hide_code=True))+ fndef = codegen.to_top_functiondef(cell)+ expected = "@app.function(disabled=True, hide_code=True)\n" + code+ assert fndef == expected+def test_recover() -> None:cells = {diff --git a/tests/_ast/test_pytest.py b/tests/_ast/test_pytest.pyindex 1005957470..68499401ec 100644--- a/tests/_ast/test_pytest.py+++ b/tests/_ast/test_pytest.py@@ -27,6 +27,21 @@ async def test_async_cell():assert True+def test_top_level_function():+ assert True+++ reason=("To ensure this doesn't just eval as a cell defining a function."),+ raises=AssertionError,+ strict=True,+)+def test_top_level_function_fails():+ raise AssertionError("Function called")++@app.celldef test_cell_has_builtin_refs():assert len([print, sum, list]) == 3diff --git a/tests/_runtime/script_data/fn_exception.py b/tests/_runtime/script_data/fn_exception.pynew file mode 100644index 0000000000..6a268aaab0--- /dev/null+++ b/tests/_runtime/script_data/fn_exception.py@@ -0,0 +1,37 @@+import marimo++__generated_with = "0.11.1"+app = marimo.App()+++ # Filler Lines+ # Filler Lines+)+def bad_divide(x, y):+ # Filler line+ # To push the error+ return y / x+ superfluous_expression = 1+++# Also a check for no call+# Technically legal, but messy+def bad_divide_curry(x):+ # Filler line+ # To push the error+ # Even further+ superfluous_expression = 1+ return bad_divide(0, x)+ # With lines below+++def _(bad_divide_curry): # TODO: Consider removing from signature?+ a = bad_divide_curry(1)+ return a+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/test_trace.py b/tests/_runtime/test_trace.pyindex c1625c5868..33d2b22c9b 100644--- a/tests/_runtime/test_trace.py+++ b/tests/_runtime/test_trace.py@@ -12,6 +12,32 @@ from marimo._runtime.runtime import Kernelclass TestScriptTrace:+ @staticmethod+ def test_function_script_trace() -> None:+ p = subprocess.run(+ [sys.executable, "tests/_runtime/script_data/fn_exception.py"],+ capture_output=True,+ )+ assert p.returncode == 1++ result = p.stderr.decode()+ assert "ZeroDivisionError: division by zero" in result+ assert ('fn_exception.py", line 14') in result+ assert ('fn_exception.py", line 26') in result+ assert "bad_divide(0, x)" in result+ assert "y / x" in result+ # Test col_offset+ # Expected output:+ # y = y / x+ # ~~^~~+ # exact line numbers differ by python version+ if sys.version_info >= (3, 11):+ assert (+ result.split("y / x")[1]+ .split("\n")[1]+ .startswith(" ~~^~~")+ )+@staticmethoddef test_script_trace() -> None:p = subprocess.run(