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: mangle node.asname for imports (#2452)

Akshay Agrawal9eb1072d20b5
diff --git a/marimo/_ast/visitor.py b/marimo/_ast/visitor.py
index 84d7cc28ff..6c9087b40d 100644
--- a/marimo/_ast/visitor.py
+++ b/marimo/_ast/visitor.py
@@ -189,7 +189,9 @@ class ScopedVisitor(ast.NodeVisitor):
return name
def _get_alias_name(self, node: ast.alias) -> str:
- """Get the string name of an imported alias
+ """Get the string name of an imported alias.
+
+ Mangles the "as" name if it's a local variable.
NB: We disallow `import *` because Python only allows
star imports at module-level, but we store cells as functions.
@@ -214,7 +216,8 @@ class ScopedVisitor(ast.NodeVisitor):
)
return basename
else:
- return self._if_local_then_mangle(node.asname)
+ node.asname = self._if_local_then_mangle(node.asname)
+ return node.asname
def _is_defined(self, identifier: str) -> bool:
"""Check if `identifier` is defined in any block."""
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index f180bdabab..75f3365c01 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -541,6 +541,23 @@ class TestExecution:
assert k.globals["z"] == 2
assert not k.errors
+ async def test_import_module_as_local_var(
+ self, any_kernel: Kernel
+ ) -> None:
+ # Tests that imported names are mangled but still usable
+ k = any_kernel
+ await k.run(
+ [
+ ExecutionRequest(
+ cell_id="0",
+ code="import sys as _sys; msize = _sys.maxsize",
+ ),
+ ]
+ )
+ # _sys mangled, should not be in globals
+ assert "_sys" not in k.globals
+ assert k.globals["msize"] == sys.maxsize
+
async def test_defs_with_no_definers_are_removed_from_cell(
self, any_kernel: Kernel
) -> None: