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: conversion of ipynb files with multiple definitions (#3458)

Akshay Agrawalede87f5d05c5
diff --git a/marimo/_ast/transformers.py b/marimo/_ast/transformers.py
index fc5452adb6..c6e58e1bab 100644
--- a/marimo/_ast/transformers.py
+++ b/marimo/_ast/transformers.py
@@ -7,11 +7,18 @@ from typing import Any
class NameTransformer(ast.NodeTransformer):
def __init__(self, name_substitutions: dict[str, str]) -> None:
+ """Remaps names in an AST.
+
+ Naively remaps all occurrences of names in an AST, given a substitution
+ dict mapping old names to new names. In particular does not take
+ scoping into account.
+ """
self._name_substitutions = name_substitutions
self.made_changes = False
super().__init__()
def visit_Name(self, node: ast.Name) -> ast.Name:
+ self.generic_visit(node)
if node.id in self._name_substitutions:
self.made_changes = True
return ast.Name(
@@ -20,6 +27,7 @@ class NameTransformer(ast.NodeTransformer):
return node
def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
+ self.generic_visit(node)
if node.name in self._name_substitutions:
self.made_changes = True
return ast.FunctionDef(
@@ -31,6 +39,7 @@ class NameTransformer(ast.NodeTransformer):
return node
def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
+ self.generic_visit(node)
if node.name in self._name_substitutions:
self.made_changes = True
return ast.ClassDef(
@@ -42,6 +51,7 @@ class NameTransformer(ast.NodeTransformer):
return node
def visit_Assign(self, node: ast.Assign) -> ast.Assign:
+ self.generic_visit(node)
new_targets: list[Any] = []
for target in node.targets:
if (
diff --git a/tests/_ast/test_transformers.py b/tests/_ast/test_transformers.py
index b00f098b86..c2483754ca 100644
--- a/tests/_ast/test_transformers.py
+++ b/tests/_ast/test_transformers.py
@@ -12,7 +12,10 @@ from marimo._ast.transformers import NameTransformer
sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
)
def test_name_transformer() -> None:
- # Test code
+ # Name transformer should naively remap all occurrences of names in an AST,
+ # without taking scoping into account.
+ #
+ # It does not transform attributes.
code = """
def old_function():
old_variable = 42
@@ -47,8 +50,8 @@ old_global = "world"
# Expected transformed code
expected_code = """
def new_function():
- old_variable = 42
- return old_variable
+ new_variable = 42
+ return new_variable
class NewClass:
diff --git a/tests/_convert/test_ipynb.py b/tests/_convert/test_ipynb.py
index adf39460c0..f7c481e3b2 100644
--- a/tests/_convert/test_ipynb.py
+++ b/tests/_convert/test_ipynb.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import ast
-import sys
from textwrap import dedent
import pytest
@@ -36,9 +35,6 @@ def assert_sources_equal(transformed: list[str], expected: list[str]) -> None:
assert transformed == expected
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_fixup_multiple_definitions():
# Makes everything private to avoid conflicts.
# Comments are removed, unfortunately.
@@ -53,9 +49,65 @@ def test_transform_fixup_multiple_definitions():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
+def test_transform_fixup_multiple_definitions_multiline():
+ # Makes everything private to avoid conflicts.
+ # Comments are removed, unfortunately.
+ sources = dd(
+ [
+ """K = 2\n
+nearest_partition = np.argpartition(dist_sq_1, K + 1, axis=1)
+""",
+ """
+plt.scatter(X_1[:, 0], X_1[:, 1], s=100)
+K = 2
+for i_1 in range(X_1.shape[0]):
+ for j in nearest_partition[i_1, :K + 1]:
+ plt.plot(*zip(X_1[j], X_1[i_1]), color='black')
+""",
+ ]
+ )
+ result = transform_fixup_multiple_definitions(sources)
+ expected = [
+ """_K = 2\n
+nearest_partition = np.argpartition(dist_sq_1, _K + 1, axis=1)
+""",
+ """
+plt.scatter(X_1[:, 0], X_1[:, 1], s=100)
+_K = 2
+for i_1 in range(X_1.shape[0]):
+ for j in nearest_partition[i_1, :_K + 1]:
+ plt.plot(*zip(X_1[j], X_1[i_1]), color='black')
+""",
+ ]
+ assert_sources_equal(result, expected)
+
+
+def test_transform_fixup_multiple_definitions_scope():
+ # Makes everything private to avoid conflicts.
+ # Comments are removed, unfortunately.
+ sources = dd(
+ [
+ """K = 2\n
+def foo():
+ K
+ K = 1
+""",
+ "K = 1",
+ ]
+ )
+ result = transform_fixup_multiple_definitions(sources)
+ expected = [
+ """_K = 2\n
+def foo():
+ _K
+ _K = 1
+""",
+ "_K = 1",
+ ]
+
+ assert_sources_equal(result, expected)
+
+
def test_transform_fixup_multiple_definitions_when_not_encapsulated():
# Since the definitions are not encapsulated in a single cell, they should
# not be transformed.
@@ -69,9 +121,6 @@ def test_transform_fixup_multiple_definitions_when_not_encapsulated():
assert result == sources
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_add_marimo_import():
sources = [
"mo.md('# Hello')",
@@ -82,9 +131,6 @@ def test_transform_add_marimo_import():
assert "import marimo as mo" in result
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_magic_commands():
sources = [
"%%sql\nSELECT * FROM table",
@@ -101,9 +147,6 @@ def test_transform_magic_commands():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_exclamation_mark():
sources = [
"!pip install package",
@@ -116,9 +159,6 @@ def test_transform_exclamation_mark():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions():
sources = [
"a = 1",
@@ -139,9 +179,6 @@ def test_transform_duplicate_definitions():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_cell_metadata():
sources = [
"print('Hello')",
@@ -158,9 +195,6 @@ def test_transform_cell_metadata():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_remove_duplicate_imports():
sources = [
"import numpy as np\nimport pandas as pd\nimport numpy as np",
@@ -175,9 +209,6 @@ def test_transform_remove_duplicate_imports():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_remove_duplicate_imports_single_line():
sources = [
"import polars as pl",
@@ -190,9 +221,6 @@ def test_transform_remove_duplicate_imports_single_line():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_fixup_multiple_definitions_complex():
sources = [
"x = 1\ny = 2\nprint(x, y)",
@@ -207,9 +235,6 @@ def test_transform_fixup_multiple_definitions_complex():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_fixup_multiple_definitions_with_functions():
sources = [
"def func():\n x = 1\n return x\nfunc()",
@@ -226,9 +251,6 @@ def test_transform_fixup_multiple_definitions_with_functions():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_add_marimo_import_edge_cases():
sources = [
"# mo.md('# Hello')",
@@ -239,9 +261,6 @@ def test_transform_add_marimo_import_edge_cases():
assert "import marimo as mo" not in result
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_magic_commands_complex():
sources = [
"%%sql\nSELECT *\nFROM table\nWHERE condition",
@@ -264,9 +283,6 @@ def test_transform_magic_commands_complex():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_exclamation_mark_complex():
sources = [
"!pip install package1 package2",
@@ -284,9 +300,6 @@ def test_transform_exclamation_mark_complex():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_complex():
sources = [
"x = 1 # comment unaffected",
@@ -305,9 +318,6 @@ def test_transform_duplicate_definitions_complex():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_cell_metadata_complex():
sources = [
"print('Cell 1')",
@@ -327,9 +337,6 @@ def test_transform_cell_metadata_complex():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_remove_duplicate_imports_complex():
sources = [
"import numpy as np\nfrom pandas import DataFrame\nimport matplotlib.pyplot as plt", # noqa: E501
@@ -344,9 +351,6 @@ def test_transform_remove_duplicate_imports_complex():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_fixup_multiple_definitions_with_classes():
sources = [
"class MyClass:\n x = 1\n def method(self):\n return self.x", # noqa: E501
@@ -361,9 +365,6 @@ def test_transform_fixup_multiple_definitions_with_classes():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_magic_commands_unsupported():
sources = [
"%custom_magic arg1 arg2",
@@ -376,9 +377,6 @@ def test_transform_magic_commands_unsupported():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_exclamation_mark_with_variables():
sources = [
"package = 'numpy'\n!pip install {package}",
@@ -391,9 +389,6 @@ def test_transform_exclamation_mark_with_variables():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_comprehensions():
sources = [
"[x for x in range(10)]",
@@ -410,9 +405,6 @@ def test_transform_duplicate_definitions_with_comprehensions():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_reference_to_previous():
sources = [
"x = 1",
@@ -427,9 +419,6 @@ def test_transform_duplicate_definitions_with_reference_to_previous():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_cell_metadata_with_complex_metadata():
sources = [
"print('Complex metadata')",
@@ -448,9 +437,6 @@ def test_transform_cell_metadata_with_complex_metadata():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_remove_duplicate_imports_with_aliases():
sources = [
"import numpy as np\nimport pandas as pd",
@@ -465,9 +451,6 @@ def test_transform_remove_duplicate_imports_with_aliases():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_remove_duplicate_imports_single():
sources = [
"import polars as pl",
@@ -482,9 +465,21 @@ def test_transform_remove_duplicate_imports_single():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
+# This test currently fails because import deduplication doesn't handle
+# multiple imports on one line
+ reason="import deduplication doesn't handle multiple imports on one line"
)
+def test_transform_remove_duplicate_imports_with_multiple_on_one_line():
+ sources = ["import getpass\nimport os", "import os, import getpass"]
+
+ result = transform_remove_duplicate_imports(sources)
+ assert result == [
+ "import getpass\nimport os",
+ "",
+ ]
+
+
def test_transform_duplicate_definitions_with_re_def():
sources = [
"x = 1",
@@ -505,9 +500,6 @@ def test_transform_duplicate_definitions_with_re_def():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_multiple_variables():
sources = [
"x, y = 1, 2",
@@ -529,56 +521,53 @@ def test_transform_duplicate_definitions_with_multiple_variables():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_function_and_global():
sources = dd(
[
"x = 10",
"""
- def func():
- global x
- x_1 = x + 1
- return x
- """,
+def func():
+ global x
+ x_1 = x + 1
+ return x
+""",
"""
- x = func()
- print(x)
- """,
+x = func()
+print(x)
+""",
"""
- def another_func():
- x = 20
- return x
- """,
+def another_func():
+ x = 20
+ return x
+""",
"""
- x = another_func()
- print(x)
- """,
+x = another_func()
+print(x)
+""",
]
)
expected = dd(
[
"x = 10",
"""
- def func():
- global x
- x_1 = x + 1
- return x
- """,
+def func():
+ global x
+ x_1 = x + 1
+ return x
+""",
"""
- x_1 = func()
- print(x_1)
- """,
+x_1 = func()
+print(x_1)
+""",
"""
- def another_func():
- x = 20
- return x
- """,
+def another_func():
+ x = 20
+ return x
+""",
"""
- x_2 = another_func()
- print(x_2)
- """,
+x_2 = another_func()
+print(x_2)
+""",
]
)
@@ -586,9 +575,6 @@ def test_transform_duplicate_definitions_with_function_and_global():
assert_sources_equal(result, expected)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_comprehensions_and_lambdas():
sources = [
"x = [i for i in range(5)]",
@@ -610,9 +596,6 @@ def test_transform_duplicate_definitions_with_comprehensions_and_lambdas():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_simple_lambda():
sources = [
"x = 0",
@@ -630,9 +613,6 @@ def test_transform_duplicate_definitions_with_simple_lambda():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_simple_redefinition() -> None:
sources = [
"x = 0",
@@ -649,9 +629,6 @@ def test_transform_simple_redefinition() -> None:
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_with_simple_function():
sources = [
"x = 0",
@@ -666,9 +643,6 @@ def test_transform_duplicate_definitions_with_simple_function():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_attrs():
sources = [
"x = 0",
@@ -685,9 +659,6 @@ def test_transform_duplicate_definitions_attrs():
]
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definition_shadowed_definition():
sources = dd(
[
@@ -715,9 +686,6 @@ def test_transform_duplicate_definition_shadowed_definition():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definition_kwarg():
sources = dd(
[
@@ -745,9 +713,6 @@ def test_transform_duplicate_definition_kwarg():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definition_nested():
sources = dd(
[
@@ -781,9 +746,6 @@ def test_transform_duplicate_definition_nested():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_function_definitions():
sources = dd(
[
@@ -805,9 +767,6 @@ def test_transform_duplicate_function_definitions():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_classes():
sources = dd(
[
@@ -829,9 +788,6 @@ def test_transform_duplicate_classes():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_numbered_no_conflict():
sources = dd(
[
@@ -851,9 +807,6 @@ def test_transform_duplicate_definitions_numbered_no_conflict():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_numbered():
# handle the user defining variables like df_1
sources = dd(
@@ -880,9 +833,6 @@ def test_transform_duplicate_definitions_numbered():
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_and_aug_assign() -> None:
sources = dd(
[
@@ -904,9 +854,6 @@ def test_transform_duplicate_definitions_and_aug_assign() -> None:
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_read_before_write() -> None:
sources = dd(
[
@@ -928,9 +875,6 @@ def test_transform_duplicate_definitions_read_before_write() -> None:
)
- sys.version_info < (3, 9), reason="Feature not supported in python 3.8"
-)
def test_transform_duplicate_definitions_syntax_error() -> None:
sources = dd(
[