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: Provide toplevel/ NameError explanations for private variables (#7524)
Dylan Madisettida26818af04c
diff --git a/docs/guides/reusing_functions.md b/docs/guides/reusing_functions.mdindex 12a9d8fb47..3c1d7608f2 100644--- a/docs/guides/reusing_functions.md+++ b/docs/guides/reusing_functions.md@@ -118,6 +118,7 @@ print(stats)- Functions cannot depend on variables defined in regular cells- Like other cells, cyclic dependencies between functions are not allowed+- Local variables (variables starting with `_`) cannot be made reusable- Functions cannot be exported from notebooks in [marimo's markdown format](editor_features/watching.md#as-markdown).## Learn morediff --git a/marimo/_ast/cell.py b/marimo/_ast/cell.pyindex 0ba2fb5f15..e579bc78a1 100644--- a/marimo/_ast/cell.py+++ b/marimo/_ast/cell.py@@ -302,7 +302,8 @@ class CellImpl:except SyntaxError:return None- if len(self.defs) != 1:+ variables = self.defs | self.temporaries+ if len(variables) != 1:return Noneif not (@@ -314,12 +315,22 @@ class CellImpl:):return None+ # Depends on cell, JIT import+ from marimo._ast.variables import unmangle_local+# Check that def matches the single definitionname = tree.body[0].name- if not (name == list(self.defs)[0] and name in self.variable_data):+ ast_name = unmangle_local(variables.pop()).name+ if not (name == ast_name):return None- if len(variable_data := self.variable_data[name]) != 1:+ if name.startswith("_"):+ return VariableData("temporary")++ if (+ name not in self.variable_data+ or len(variable_data := self.variable_data[name]) != 1+ ):return Nonereturn list(variable_data)[0]diff --git a/marimo/_ast/toplevel.py b/marimo/_ast/toplevel.pyindex 228327809c..ed830fa66d 100644--- a/marimo/_ast/toplevel.py+++ b/marimo/_ast/toplevel.py@@ -38,6 +38,7 @@ TopLevelInvalidHints = Literal["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.",+ "Definitions starting with `_` are local to a cell.",](HINT_UNPARSABLE,@@ -47,6 +48,7 @@ TopLevelInvalidHints = Literal[HINT_HAS_REFS,HINT_HAS_CLOSE_REFS,HINT_HAS_COMMENT,+ HINT_NO_PRIVATES,) = get_args(TopLevelInvalidHints)TopLevelHints = Union[Literal["Valid"], TopLevelInvalidHints]@@ -139,6 +141,10 @@ class TopLevelStatus:self.demote(HINT_NOT_SINGLE)return+ if var.kind == "temporary":+ self.demote(HINT_NO_PRIVATES)+ return+(self.name,) = self._cell.defsif self.name in ("app", "__generated_with", "__name__"):self.demote(HINT_BAD_NAME)diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.pyindex eb5a083bee..f73eba551b 100644--- a/marimo/_ast/visitor.py+++ b/marimo/_ast/visitor.py@@ -68,6 +68,9 @@ class VariableData:"class","import","variable",+ # NB: only used when there's a need to stub. not generally carried+ # on cell.+ "temporary",],SQLKind,] = "variable"diff --git a/marimo/_runtime/executor.py b/marimo/_runtime/executor.pyindex 96ce453453..d79d0d6861 100644--- a/marimo/_runtime/executor.py+++ b/marimo/_runtime/executor.py@@ -9,7 +9,7 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Optionalfrom marimo._ast.cell import CellImpl, _is_coroutine-from marimo._ast.variables import is_mangled_local, unmangle_local+from marimo._ast.variables import is_mangled_localfrom marimo._entrypoints.registry import EntryPointRegistryfrom marimo._runtime.copy import (CloneError,@@ -66,8 +66,8 @@ def _raise_name_error(if graph is None:raise MarimoRuntimeException from name_error(missing_name,) = re.findall(r"'([^']*)'", str(name_error))- _, private_cell_id = unmangle_local(missing_name)- if missing_name in graph.definitions or private_cell_id:+ # Will miss "locals" by default since not in the graph defs.+ if missing_name in graph.definitions:raise MarimoRuntimeException from MarimoMissingRefError(missing_name, name_error)diff --git a/tests/_ast/test_toplevel.py b/tests/_ast/test_toplevel.pyindex 2dc2ab0ced..6c3d8524cf 100644--- a/tests/_ast/test_toplevel.py+++ b/tests/_ast/test_toplevel.py@@ -572,6 +572,17 @@ class TestTopLevelClasses:TopLevelType.TOPLEVEL,] == [s.type for s in extraction], [s.hint for s in extraction]+ @staticmethod+ def test_private_var(app) -> None:+ @app.cell+ def cell():+ def _private():+ return 1++ status = TopLevelStatus.from_cell(cell._cell, BUILTINS)+ assert status.type == TopLevelType.CELL, status.hint+ assert status.hint == toplevel.HINT_NO_PRIVATES+@staticmethod@pytest.mark.skipif(sys.version_info < (3, 12),