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: single line magic conversion (#3527)
Akshay Agrawalac2c54631a64
diff --git a/marimo/_convert/ipynb.py b/marimo/_convert/ipynb.pyindex 232e4bb9f5..123ae6e035 100644--- a/marimo/_convert/ipynb.py+++ b/marimo/_convert/ipynb.py@@ -86,6 +86,26 @@ def transform_magic_commands(sources: List[str]) -> List[str]:"""Transform Jupyter magic commands to their marimo equivalentsor comment them out.++ In the transformer helper methods, command is the magic command+ starting with either % or %%; source is the args of the command+ for a single line magic or the entire cell source for a double line magic++ For example:++ %load_ext autoreload++ yields command == "%load_ext", source = "autoreload", but++ %%sql+ SELECT * FROM TABLE (+ ...+ )++ yields command == "%%sql", source ==+ SELECT * FROM TABLE (+ ...+ )"""def magic_sql(source: str, command: str) -> str:@@ -132,7 +152,7 @@ def transform_magic_commands(sources: List[str]) -> List[str]:"""double = command.startswith("%%")if not double:- return f"# {(command + ' ' + source)!r} command supported automatically in marimo" # noqa: E501+ return f"# {(command + ' ' + source)!r} command supported automatically in marimo"result = [f"# {command!r} command supported automatically in marimo",@@ -153,7 +173,7 @@ def transform_magic_commands(sources: List[str]) -> List[str]:os.makedirs('path/to/directory', exist_ok=True)"""del command- return f"import os\nos.makedirs({source!r}, exist_ok"+ return f"import os\nos.makedirs({source!r}, exist_ok=True)"def magic_cd(source: str, command: str) -> str:"""@@ -238,17 +258,26 @@ def transform_magic_commands(sources: List[str]) -> List[str]:"bash": magic_bash,"!": magic_bash,"ls": magic_ls,- "load_ext": magic_already_supported,+ "load_ext": magic_remove,"env": magic_env,# Already supported in marimo, can just comment out the magic"pip": magic_already_supported,"matplotlib": magic_already_supported,+ "autoreload": magic_already_supported,# Remove the magic, but keep the code as is"timeit": magic_remove,"time": magic_remove,# Everything else is not supported and will be commented out}+ def transform_single_line_magic(line: str) -> str:+ pieces = line.strip().lstrip("%").split()+ magic_cmd, args = pieces[0], pieces[1:]+ rest = " ".join(args)+ if magic_cmd in magics:+ return magics[magic_cmd](rest, "%" + magic_cmd)+ return magic_remove(rest, "%" + magic_cmd)+def transform(cell: str) -> str:stripped = cell.strip()@@ -261,14 +290,18 @@ def transform_magic_commands(sources: List[str]) -> List[str]:return magic_remove(comment_out_code(rest), magic)# Single-line magic- elif stripped.startswith("%"):- magic, rest = stripped.split(" ", 1)- magic_cmd = magic.strip().lstrip("%")- if magic_cmd in magics:- return magics[magic_cmd](rest, magic)- return magic_remove(comment_out_code(rest), magic)-- return cell+ lines = stripped.split("\n")+ result = []+ if not any(line.startswith("%") for line in lines):+ return cell++ for line in lines:+ result.append(+ transform_single_line_magic(line)+ if line.startswith("%")+ else line+ )+ return "\n".join(result)return [transform(cell) for cell in sources]diff --git a/tests/_convert/test_ipynb.py b/tests/_convert/test_ipynb.pyindex f7c481e3b2..7a142c9c60 100644--- a/tests/_convert/test_ipynb.py+++ b/tests/_convert/test_ipynb.py@@ -136,6 +136,7 @@ def test_transform_magic_commands():"%%sql\nSELECT * FROM table","%%sql\nSELECT * \nFROM table","%cd /path/to/dir",+ "%mkdir /path/to/dir","%matplotlib inline",]result = transform_magic_commands(sources)@@ -143,10 +144,57 @@ def test_transform_magic_commands():'_df = mo.sql("""\nSELECT * FROM table\n""")','_df = mo.sql("""\nSELECT * \nFROM table\n""")',"import os\nos.chdir('/path/to/dir')",+ "import os\nos.makedirs('/path/to/dir', exist_ok=True)","# '%matplotlib inline' command supported automatically in marimo",]+def test_transform_magic_command_with_code():+ sources = dd(+ [+ """+ %matplotlib inline+ import numpy as np+ import matplotlib.pyplot as plt+ plt.style.use('seaborn-whitegrid')+ """+ ]+ )+ result = transform_magic_commands(sources)+ expected = dd(+ [+ """# '%matplotlib inline' command supported automatically in marimo+import numpy as np+import matplotlib.pyplot as plt+plt.style.use('seaborn-whitegrid')"""+ ]+ )+ assert result == expected+++def test_transform_magic_command_multiple_args_with_code():+ sources = dd(+ [+ """+ %matplotlib inline foo+ import numpy as np+ import matplotlib.pyplot as plt+ plt.style.use('seaborn-whitegrid')+ """+ ]+ )+ result = transform_magic_commands(sources)+ expected = dd(+ [+ """# '%matplotlib inline foo' command supported automatically in marimo+import numpy as np+import matplotlib.pyplot as plt+plt.style.use('seaborn-whitegrid')"""+ ]+ )+ assert result == expected++def test_transform_exclamation_mark():sources = ["!pip install package",@@ -269,7 +317,7 @@ def test_transform_magic_commands_complex():"%env MY_VAR=value",]result = transform_magic_commands(sources)- assert result == [+ expected = ['_df = mo.sql("""\nSELECT *\nFROM table\nWHERE condition\n""")',("# magic command not supported in marimo; please file an issue to add support\n" # noqa: E501@@ -277,10 +325,13 @@ def test_transform_magic_commands_complex():" pass"),(- "# '%load_ext autoreload\\n%autoreload 2' command supported automatically in marimo" # noqa: E501+ "# magic command not supported in marimo; please file an issue to add support\n" # noqa: E501+ "# %load_ext autoreload\n"+ "# '%autoreload 2' command supported automatically in marimo"),"import os\nos.environ['MY_VAR'] = 'value'",]+ assert result == expecteddef test_transform_exclamation_mark_complex():@@ -372,7 +423,7 @@ def test_transform_magic_commands_unsupported():]result = transform_magic_commands(sources)assert result == [- "# magic command not supported in marimo; please file an issue to add support\n# %custom_magic # arg1 arg2", # noqa: E501+ "# magic command not supported in marimo; please file an issue to add support\n# %custom_magic arg1 arg2", # noqa: E501"# magic command not supported in marimo; please file an issue to add support\n# %%custom_cell_magic\n# some\n# content", # noqa: E501]