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.

fix: Expand checks around decorated functions to enable functools usage (#5582)

Dylan Madisetticf54b17a7745
diff --git a/marimo/_ast/cell_manager.py b/marimo/_ast/cell_manager.py
index b0157e21e7..0a8d3c40ba 100644
--- a/marimo/_ast/cell_manager.py
+++ b/marimo/_ast/cell_manager.py
@@ -139,13 +139,31 @@ class CellManager:
factory: Callable[..., Cell] = (
toplevel_cell_factory if top_level else cell_factory
)
- cell = factory(
- obj,
- cell_id=self.create_cell_id(),
- anonymous_file=app._app._anonymous_file if app else False,
- test_rewrite=is_top_level_pytest
- or (app is not None and app._app._pytest_rewrite),
- )
+ try:
+ cell = factory(
+ obj,
+ cell_id=self.create_cell_id(),
+ anonymous_file=app._app._anonymous_file if app else False,
+ test_rewrite=is_top_level_pytest
+ or (app is not None and app._app._pytest_rewrite),
+ )
+ except TypeError as e:
+ LOGGER.debug(
+ f"Failed to register cell: {e}. Expected class or function,"
+ f"got {type(obj)}."
+ )
+ # Top level definitions can wrap non-functions or classes.
+ # Since static parsing makes it possible to load and create a
+ # notebook like this, importing the notebooks shouldn't fail
+ # either.
+ if top_level:
+ return obj
+ # If it is not a top-level definition, something is very wrong
+ raise ValueError(
+ "Unexpected failure. Please report this error to "
+ "github.com/marimo-team/marimo/issues."
+ ) from e
+
cell._cell.configure(cell_config)
self._register_cell(cell, app=app)
@@ -447,6 +465,21 @@ class CellManager:
return None
return self._cell_data[cell_id]
+ def get_cell_data_by_name(self, name: str) -> Optional[CellData]:
+ """Find a cell ID by its name.
+
+ Args:
+ name: The name to search for
+
+ Returns:
+ Optional[CellData]: The data of the first cell with matching name,
+ or None if no match is found
+ """
+ for cell_data in self._cell_data.values():
+ if cell_data.name.strip("*") == name:
+ return cell_data
+ return None
+
def get_cell_id_by_code(self, code: str) -> Optional[CellId_t]:
"""Find a cell ID by its code content.
diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.py
index 076939dc82..02f875a99d 100644
--- a/marimo/_ast/compiler.py
+++ b/marimo/_ast/compiler.py
@@ -298,8 +298,15 @@ def get_source_position(
# Fallback won't capture embedded scripts
if inspect.isclass(f):
is_script = f.__module__ == "__main__"
- else:
+ # Larger catch all than if inspect.isfunction(f):
+ elif hasattr(f, "__globals__"):
is_script = f.__globals__["__name__"] == "__main__" # type: ignore
+ # Could be something wrapped in a decorator, like
+ # functools._lru_cache_wrapper.
+ elif hasattr(f, "__wrapped__"):
+ return get_source_position(f.__wrapped__, lineno, col_offset)
+ else:
+ return None
# TODO: spec is None for markdown notebooks, which is fine for now
if module := inspect.getmodule(f):
spec = module.__spec__
diff --git a/tests/_ast/codegen_data/test_with_bad_decorator.py b/tests/_ast/codegen_data/test_with_bad_decorator.py
new file mode 100644
index 0000000000..57d4c8e217
--- /dev/null
+++ b/tests/_ast/codegen_data/test_with_bad_decorator.py
@@ -0,0 +1,18 @@
+import marimo
+
+__generated_with = "0.0.0"
+app = marimo.App()
+
+
+def wrap(f) -> int:
+ return 100
+
+@wrap
+def hundred(a: int, b: int) -> int:
+ return a + b
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/test_cell.py b/tests/_ast/test_cell.py
index 124042961d..e1a7639b63 100644
--- a/tests/_ast/test_cell.py
+++ b/tests/_ast/test_cell.py
@@ -378,6 +378,26 @@ class TestReusableCell:
assert defs == {"z": -1}
+class TestDecoratedCells:
+ @staticmethod
+ def test_functool_wrapped(app) -> None:
+ with app.setup:
+ from functools import cache
+
+ @app.function
+ @cache
+ def add(a: int, b: int) -> int:
+ return a + b
+
+ assert add(1, 2) == 3
+ assert add.cache_info().hits == 0
+ assert add(1, 2) == 3
+ assert add.cache_info().hits == 1
+ assert app._cell_manager.get_cell_data_by_name("add").cell.defs == {
+ "add"
+ }
+
+
def help_smoke() -> None:
app = App()
diff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.py
index 3f2343a12b..4267a6476c 100644
--- a/tests/_ast/test_load.py
+++ b/tests/_ast/test_load.py
@@ -271,3 +271,17 @@ class TestGetCodes:
else:
assert len(caplog.records) == 1
assert "kwarg_that_doesnt_exist" in caplog.text
+
+ @staticmethod
+ def test_get_app_with_bad_decorator(static_load) -> None:
+ app = static_load(get_filepath("test_with_bad_decorator"))
+ assert app is not None
+ assert app._cell_manager.get_cell_data_by_name("wrap").cell.defs == {
+ "wrap"
+ }
+ assert app._cell_manager.get_cell_data_by_name(
+ "hundred"
+ ).cell.defs == {"hundred"}
+ from codegen_data.test_with_bad_decorator import hundred
+
+ assert hundred == 100