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 duplicate `import marimo as mo` in .ipynb conversion. (#5019)
Alex Ford24ee11f0f7af
diff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.pyindex 9ee088e5ef..23e2cfa867 100644--- a/marimo/_convert/ipynb.py+++ b/marimo/_convert/ipynb.py@@ -77,7 +77,15 @@ def transform_add_marimo_import(sources: list[str]) -> list[str]:def contains_mo(cell: str) -> bool:return cell.startswith("mo.md(") or "mo.sql(" in cell- if any(contains_mo(cell) for cell in sources):+ def imports_mo(cell: str) -> bool:+ # TODO this is a quick heuristic and will fail if mo is defined in other ways+ # however detecting arbitrary definitions would require an AST parse+ # which isn't being performed during this pass+ return "import marimo as mo" in cell++ if any(contains_mo(cell) for cell in sources) and not any(+ imports_mo(cell) for cell in sources+ ):return sources + ["import marimo as mo"]return sourcesdiff --git a/tests/_convert/test_ipynb.py b/tests/_convert/test_ipynb.pyindex 7a142c9c60..138ea908ed 100644--- a/tests/_convert/test_ipynb.py+++ b/tests/_convert/test_ipynb.py@@ -127,9 +127,26 @@ def test_transform_add_marimo_import():"print('World')","mo.sql('SELECT * FROM table')",]+ expected = [+ "mo.md('# Hello')",+ "print('World')",+ "mo.sql('SELECT * FROM table')",+ "import marimo as mo",+ ]result = transform_add_marimo_import(sources)- assert "import marimo as mo" in result+ assert result == expected++ # if `import marimo as mo` is already present+ # it should not be added again+ assert transform_add_marimo_import(expected) == expected+ existing = [+ # slight support for different import orders+ # but must use canonical "import marimo as mo" form+ "import antigravity; import marimo as mo",+ "mo.md('# Hello')",+ ]+ assert transform_add_marimo_import(existing) == existingdef test_transform_magic_commands():sources = [