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: recursive private function not detected (#8762)

Dylan Madisettib43927be9d03
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 9c98ba27dd..8423b2ab87 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -968,10 +968,19 @@ class ScopedVisitor(ast.NodeVisitor):
node.id, ignore_scope=True
)
for block in reversed(self.block_stack):
- if block == self.block_stack[0] and block.is_defined(
- mangled_name
- ):
- node.id = mangled_name
+ if block == self.block_stack[0]:
+ # At top-level scope: mangle only if the mangled name is
+ # already defined. When called from a nested scope
+ # (len > 1), also mangle even if the top-level block
+ # doesn't define it yet — this handles recursive calls to
+ # underscore-prefixed functions, where the function name
+ # isn't registered in the top-level block until after its
+ # body is visited.
+ if (
+ block.is_defined(mangled_name)
+ or len(self.block_stack) > 1
+ ):
+ node.id = mangled_name
elif block.is_defined(node.id):
break
else:
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 76387d0dd5..f36b9e1316 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1773,6 +1773,60 @@ except NameError:
await k.run([ExecuteCellCommand(er.cell_id, "None")])
assert f"_cell_{er.cell_id}_x" not in k.globals
+ async def test_private_recursive_function(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """Regression test for MO-5426: underscore-prefixed recursive function
+ should be able to call itself within the same cell."""
+ k = any_kernel
+ await k.run(
+ [
+ er := exec_req.get(
+ """
+ def _recurse(n):
+ if n > 0:
+ return 1 + _recurse(n - 1)
+ else:
+ return 0
+
+ result = _recurse(3)
+ """
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert cell.exception is None
+ assert k.globals["result"] == 3
+
+ async def test_private_recursive_function_local_shadow(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ """A local reassignment inside the function body should shadow the
+ outer definition. Result must differ from the real fib to confirm
+ the shadow is actually used."""
+ k = any_kernel
+ await k.run(
+ [
+ er := exec_req.get(
+ """
+ def _recurse(n):
+ _recurse = lambda x: x
+ if n <= 1:
+ return n
+ return _recurse(n - 1) + _recurse(n - 2)
+
+ result = _recurse(5)
+ """
+ )
+ ]
+ )
+ cell = k.graph.cells[er.cell_id]
+ assert cell.exception is None
+ # _recurse = lambda x: x (identity) shadows the recursive definition,
+ # so _recurse(n-1) + _recurse(n-2) = (n-1) + (n-2) = 2n-3
+ # _recurse(5) = (5-1) + (5-2) = 4 + 3 = 7, not fib(5)=5
+ assert k.globals["result"] == 7
+
async def test_has_run_id(
self, mocked_kernel: MockedKernel, exec_req: ExecReqProvider
) -> None: