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
fix: Address mep feedback (#4557)
Dylan Madisettia61221489112
diff --git a/frontend/src/components/editor/Cell.tsx b/frontend/src/components/editor/Cell.tsxindex ccc39d9b25..01cfd4ba4b 100644--- a/frontend/src/components/editor/Cell.tsx+++ b/frontend/src/components/editor/Cell.tsx@@ -738,6 +738,10 @@ const EditableCellComponent = ({return undefined;};+ const isToplevel = !!(+ serialization && serialization.toLowerCase() === "valid"+ );+return (<TooltipProvider><CellActionsContextMenu@@ -847,11 +851,35 @@ const EditableCellComponent = ({</div>{cellOutput === "below" && outputArea}{serialization && (- <div className="py-1 px-2 flex justify-end gap-2 last:rounded-b">+ <a+ href="https://links.marimo.app/reusable-definitions"+ target="_blank"+ className="hover:underline py-1 px-2 flex items-center justify-end gap-2 last:rounded-b"+ >+ {isToplevel && (+ <span className="text-muted-foreground text-xs font-bold">+ reusable+ </span>+ )}<Tooltip- content={<span className="max-w-16">{serialization}</span>}+ content={+ <span className="max-w-16 text-xs">+ {(isToplevel &&+ "This function or class can be imported into other Python notebooks or modules.") || (+ <>+ This definition can't be reused in other Python+ modules:+ <br />+ <br />+ <pre>{serialization}</pre>+ <br />+ Click this icon to learn more.+ </>+ )}+ </span>+ }>- {(serialization.toLowerCase() === "valid" && (+ {(isToplevel && (<SquareFunctionIconsize={16}strokeWidth={1.5}@@ -865,7 +893,7 @@ const EditableCellComponent = ({/>)}</Tooltip>- </div>+ </a>)}<ConsoleOutputconsoleOutputs={consoleOutputs}diff --git a/marimo/_ast/compiler.py b/marimo/_ast/compiler.pyindex 6675f4e8be..bb69c34f22 100644--- a/marimo/_ast/compiler.py+++ b/marimo/_ast/compiler.py@@ -21,11 +21,11 @@ from marimo._ast.cell import (ImportWorkspace,SourcePosition,)-from marimo._ast.names import SETUP_CELL_NAME+from marimo._ast.names import SETUP_CELL_NAME, TOPLEVEL_CELL_PREFIXfrom marimo._ast.transformers import ContainedExtractWithBlockfrom marimo._ast.variables import is_localfrom marimo._ast.visitor import ImportData, Name, ScopedVisitor-from marimo._schemas.serialization import CellDef, ClassCell+from marimo._schemas.serialization import CellDef, ClassCell, FunctionCellfrom marimo._types.ids import CellId_tfrom marimo._utils.tmpdir import get_tmpdir@@ -200,7 +200,7 @@ def compile_cell(expr.lineno = final_expr.lineno # type: ignore[attr-defined]else:const = ast.Constant(value=None)- const.col_offset = final_expr.end_col_offset+ const.col_offset = final_expr.end_col_offset or 0const.end_col_offset = final_expr.end_col_offsetexpr = ast.Expression(const)# use code over body since lineno corresponds to source@@ -407,22 +407,23 @@ def toplevel_cell_factory(is_test = obj.__name__.startswith("Test")else:is_test = obj.__name__.startswith("test_")+ # NB. Give top level function an invalid name- such that if they thrash the+ # result of the resultant cells can be pushed to default.return Cell(- _name=obj.__name__,+ _name=f"{TOPLEVEL_CELL_PREFIX}{obj.__name__}",_cell=cell,_test_allowed=cell._test or is_test,)def ir_cell_factory(cell_def: CellDef, cell_id: CellId_t) -> Cell:- test_name = isinstance(cell_def, ClassCell) and cell_def.name.startswith(- "Test"- )- test_name |= not isinstance(- cell_def, ClassCell- ) and cell_def.name.startswith("test_")+ # NB. no need for test rewrite, anonymous file, etc.+ # Because this is never invoked in script mode.+ prefix = ""+ if isinstance(cell_def, (FunctionCell, ClassCell)):+ prefix = TOPLEVEL_CELL_PREFIXreturn Cell(- _name=cell_def.name,+ _name=f"{prefix}{cell_def.name}",_cell=compile_cell(cell_def.code,cell_id=cell_id,diff --git a/marimo/_ast/names.py b/marimo/_ast/names.pyindex f05f3f5429..40dc06af41 100644--- a/marimo/_ast/names.py+++ b/marimo/_ast/names.py@@ -1,6 +1,8 @@# Copyright 2024 Marimo. All rights reserved.DEFAULT_CELL_NAME = "_"SETUP_CELL_NAME = "setup"+# Intentionally an invalid name character+TOPLEVEL_CELL_PREFIX = "*"def is_internal_cell_name(name: str) -> bool:diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.pyindex c5fe9b0481..e5bf273dc8 100644--- a/marimo/_ast/toplevel.py+++ b/marimo/_ast/toplevel.py@@ -11,7 +11,11 @@ from typing import TYPE_CHECKING, Literal, Optional, Union, get_argsfrom marimo._ast.app import InternalAppfrom marimo._ast.cell import CellConfig, CellImplfrom marimo._ast.compiler import compile_cell-from marimo._ast.names import SETUP_CELL_NAME+from marimo._ast.names import (+ DEFAULT_CELL_NAME,+ SETUP_CELL_NAME,+ TOPLEVEL_CELL_PREFIX,+)from marimo._ast.visitor import Namefrom marimo._runtime.dataflow import DirectedGraphfrom marimo._types.ids import CellId_t@@ -19,17 +23,19 @@ from marimo._types.ids import CellId_tif TYPE_CHECKING:from collections.abc import Iterator-# Constant for easy reuse in tests+# Constant for easy reuse in tests.+# The formatting here affects how the error is rendered in the frontend.+# This is a hack but fine for now ...TopLevelInvalidHints = Literal["Cannot parse cell.",(- "Top level definitions cannot be named 'app', '__name__' or "+ "Reusable definitions cannot be named 'app', '__name__' or ""'__generated_with'"),"Cell must contain exactly one function definition","Signature and decorators depend on {} defined out of correct cell order",- "Function contains references to variables {} which are not top level.",- "Function contains references to variables {} which failed to be toplevel.",+ "This function depends on variables defined by other cells:\n\n{}\n\nTo make this function importable from other Python modules,\nmove these variables to the setup cell.",+ "Function contains references to variables {} which were unable to become reusable.","Cell cannot contain non-indented trailing comments.",](@@ -84,7 +90,7 @@ class TopLevelStatus:):self.cell_id = cell_idself.name = name- self._name = name+ self.previous_name = nameself._type: TopLevelType = TopLevelType.UNPARSABLEself.dependencies: set[Name] = set()self._cell: Optional[CellImpl] = None@@ -285,7 +291,10 @@ class TopLevelExtraction:self._resolve_dependencies()# Don't change names of objects that are not toplevel.for status in self.cells.values():- status.name = status._name+ status.name = status.previous_name+ # For something that used to be top level, revert to default name.+ if status.name.startswith(TOPLEVEL_CELL_PREFIX):+ status.name = DEFAULT_CELL_NAME# Set the hint of all valid cells to HINT_VALIDfor status in self.toplevel.values():status.hint = HINT_VALIDdiff --git a/marimo/_ast/transformers.py b/marimo/_ast/transformers.pyindex 986d4d9ce4..988e592429 100644--- a/marimo/_ast/transformers.py+++ b/marimo/_ast/transformers.py@@ -218,7 +218,7 @@ class ExtractWithBlock(ast.NodeTransformer):) -> None:super().__init__(*arg, **kwargs)self.target_line = line- if allowed_types is None:+ if not allowed_types:allowed_types = (ast.With,)self.allowed_types = allowed_typesself.name = name@@ -235,6 +235,7 @@ class ExtractWithBlock(ast.NodeTransformer):previous = Noneassert isinstance(node, list), "Unexpected block structure."+ parent = Nonefor n in node:# There's a chance that the block is first evaluated somewhere in a# multiline line expression, for instance:@@ -244,7 +245,6 @@ class ExtractWithBlock(ast.NodeTransformer):# 4 >>> ]# so check that the "target" line is in the interval# (i.e. 1 <= 3 <= 4)- parent = Noneif n.lineno < self.target_line:pre_block.append(n)previous = ndiff --git a/tests/_ast/test_app_cell.py b/tests/_ast/test_app_cell.pyindex 0a00a2432a..2bf7f5ad42 100644--- a/tests/_ast/test_app_cell.py+++ b/tests/_ast/test_app_cell.py@@ -6,6 +6,7 @@ import typesfrom collections.abc import Awaitablefrom marimo._ast.app import App+from marimo._ast.cell import Celldef test_decorator_called() -> None:@@ -100,8 +101,9 @@ def test_function_decorator_called() -> None:(cell,) = app._cell_manager.cells()assert not isinstance(cell, types.FunctionType)+ assert isinstance(cell, Cell)- assert cell.name == "mock_func"+ assert cell.name == "*mock_func"assert (cell.run()[1]["mock_func"].__code__.co_code== mock_func.__code__.co_code@@ -119,8 +121,9 @@ def test_function_decorator_uncalled() -> None:(cell,) = app._cell_manager.cells()assert not isinstance(cell, types.FunctionType)+ assert isinstance(cell, Cell)- assert cell.name == "mock_func"+ assert cell.name == "*mock_func"assert (cell.run()[1]["mock_func"].__code__.co_code== mock_func.__code__.co_code@@ -139,6 +142,7 @@ def test_function_decorator_with_args() -> None:(cell,) = app._cell_manager.cells()assert cell is not None+ assert isinstance(cell, Cell)assert (cell._cell.code@@ -149,7 +153,7 @@ def test_function_decorator_with_args() -> None:""").strip())assert cell._cell.config.disabled is True- assert cell.name == "mock_func"+ assert cell.name == "*mock_func"assert (cell.run()[1]["mock_func"].__code__.co_code== mock_func.__code__.co_codediff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.pyindex 1a22df0927..4d5c0a6eb3 100644--- a/tests/_ast/test_load.py+++ b/tests/_ast/test_load.py@@ -126,7 +126,7 @@ class TestGetCodes:app = load_app(get_filepath("test_get_setup"))assert app is not Nonecell_manager = app._cell_manager- assert list(cell_manager.names()) == ["setup", "fn"]+ assert list(cell_manager.names()) == ["setup", "*fn"]assert list(cell_manager.codes()) == ["variable = 1",textwrap.dedent(@@ -141,7 +141,7 @@ class TestGetCodes:app = load_app(get_filepath("test_get_setup_blank"))assert app is not Nonecell_manager = app._cell_manager- assert list(cell_manager.names()) == ["setup", "fn"]+ assert list(cell_manager.names()) == ["setup", "*fn"]assert list(cell_manager.codes()) == ["# Only comments\n# and a pass",textwrap.dedent(@@ -156,7 +156,7 @@ class TestGetCodes:app = load_app(get_filepath("test_get_codes_messy_toplevel"))assert app is not Nonecell_manager = app._cell_manager- assert list(cell_manager.names()) == ["fn", "wrapped"]+ assert list(cell_manager.names()) == ["*fn", "wrapped"]assert list(cell_manager.codes()) == ["def fn(a,\n b, # hello,\n c, # again\n d,) -> int:\n"+ " # comment\n # another comment\n\n # yet another comment\n"@@ -232,17 +232,17 @@ class TestGetCodes:assert list(cell_manager.names()) == ["setup","_",- "addition",- "shadow_case",+ "*addition",+ "*shadow_case","_","_",- "fun_that_uses_mo",- "fun_that_uses_another_but_out_of_order",- "fun_that_uses_another",+ "*fun_that_uses_mo",+ "*fun_that_uses_another_but_out_of_order",+ "*fun_that_uses_another","cell_with_ref_and_def","_",- "ExampleClass",- "SubClass",+ "*ExampleClass",+ "*SubClass",]@staticmethoddiff --git a/tests/_ast/test_toplevel.py b/tests/_ast/test_toplevel.pyindex 526b6a8cec..9aef615150 100644--- a/tests/_ast/test_toplevel.py+++ b/tests/_ast/test_toplevel.py@@ -469,6 +469,25 @@ class TestTopLevelClasses:TopLevelType.TOPLEVEL,] == [s.type for s in extraction], [s.hint for s in extraction]+ @staticmethod+ def test_name_is_not_propagated(app) -> None:+ @app.cell+ def cell():+ value = 1++ @app.function+ def to_be_demoted():+ return value + 1 # type: ignore # noqa: F821++ extraction = TopLevelExtraction.from_app(InternalApp(app))+ assert [+ TopLevelType.CELL,+ TopLevelType.CELL,+ ] == [s.type for s in extraction], [s.hint for s in extraction]+ assert ["cell", "_"] == [s.name for s in extraction], [+ s.hint for s in extraction+ ]+class TestTopLevelHook:@staticmethod