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: missing defs at runtime in app.run() (#604)

Akshay Agrawald9ef6d3ed2a2
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 7be1869845..d317bd8e0b 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -297,5 +297,10 @@ class App:
# exclude unparsable cells
if cid in outputs
),
- {name: glbls[name] for name in self._defs},
+ # omit defs that were never defined at runtime, eg due to
+ # conditional definitions like
+ #
+ # if cond:
+ # x = 0
+ {name: glbls[name] for name in self._defs if name in glbls},
)
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index d6896ed912..70280e7a97 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -293,3 +293,35 @@ class TestApp:
configs = tuple(app._configs())
assert configs[0].disabled
assert configs[1].hide_code
+
+ @staticmethod
+ def test_conditional_definition() -> None:
+ app = App()
+
+ @app.cell
+ def _() -> tuple[int]:
+ if False:
+ x = 0
+ y = 1
+ return (x, y)
+
+ _, defs = app.run()
+
+ # x should not be in the defs dictionary
+ assert defs == {"y": 1}
+
+ @staticmethod
+ def test_empty_iteration_conditional_definition() -> None:
+ app = App()
+
+ @app.cell
+ def _() -> tuple[int]:
+ objects = iter([])
+ for obj in objects:
+ pass
+ return (obj, objects)
+
+ _, defs = app.run()
+
+ # obj should not be in the defs dictionary
+ assert "obj" not in defs