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
Prevent accidental overwrites and converter for non-marimo Python scripts (#5686)
Trevor Manz997d7d5554b8
diff --git a/marimo/_ast/load.py b/marimo/_ast/load.pyindex ab49e4c10a..8f1d37f78c 100644--- a/marimo/_ast/load.py+++ b/marimo/_ast/load.py@@ -8,7 +8,11 @@ from typing import Literal, Optional, Unionfrom marimo import _loggersfrom marimo._ast.app import App, InternalApp-from marimo._ast.parse import MarimoFileError, parse_notebook+from marimo._ast.parse import (+ MarimoFileError,+ is_non_marimo_python_script,+ parse_notebook,+)from marimo._schemas.serialization import NotebookSerialization, UnparsableCellLOGGER = _loggers.marimo_logger()@@ -64,9 +68,18 @@ def _static_load(filepath: Path) -> Optional[App]:contents = _maybe_contents(filepath)if not contents:return None+notebook = parse_notebook(contents)++ if notebook and is_non_marimo_python_script(notebook):+ # Should fail instead of overriding contents+ raise MarimoFileError(+ f"Python script {filepath} is not a marimo notebook."+ )+if notebook is None or not notebook.valid:return None+app = App(**notebook.app.options, _filename=str(filepath))for cell in notebook.cells:if isinstance(cell, UnparsableCell):@@ -149,8 +162,7 @@ def load_app(filename: Optional[str]) -> Optional[App]:from marimo._convert.markdown.markdown import convert_from_md_to_appreturn convert_from_md_to_app(contents) if contents else None-- if not path.suffix == ".py":+ elif not path.suffix == ".py":raise MarimoFileError("File must end with .py or .md")try:diff --git a/marimo/_ast/parse.py b/marimo/_ast/parse.pyindex 09f779626b..fb0ad48333 100644--- a/marimo/_ast/parse.py+++ b/marimo/_ast/parse.py@@ -838,6 +838,17 @@ def parse_notebook(contents: str) -> Optional[NotebookSerialization]:lineno=1,))++ remaining = parser.extractor.contents[len(header.value) :]+ if remaining.strip():+ # just a header is fine, anything else we would ignore and override+ violations.append(+ Violation(+ _non_marimo_python_script_violation_description,+ lineno=header.end_lineno + 2 if header.value else 1,+ )+ )+return NotebookSerialization(header=Header(lineno=0,@@ -893,3 +904,15 @@ def parse_notebook(contents: str) -> Optional[NotebookSerialization]:cells=cells,violations=violations,)+++_non_marimo_python_script_violation_description = (+ "non-marimo Python content beyond header"+)+++def is_non_marimo_python_script(notebook: NotebookSerialization) -> bool:+ return any(+ (v.description == _non_marimo_python_script_violation_description)+ for v in notebook.violations+ )diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.pyindex f7fec8e584..0f6b2deb04 100644--- a/marimo/_cli/cli.py+++ b/marimo/_cli/cli.py@@ -71,6 +71,19 @@ def check_app_correctness(filename: str) -> None:click.echo(f"Failed to parse notebook: {filename}\n", err=True)raise click.ClickException(traceback.format_exc(limit=0)) from None+ if status == "invalid" and filename.endswith(".py"):+ # fail for python scripts, almost certainly do not want to override contents+ import os++ stem = os.path.splitext(os.path.basename(filename))[0]+ raise click.ClickException(+ f"Python script not recognized as a marimo notebook.\n\n"+ f" {green('Tip:')} Try converting with"+ "\n\n"+ f" marimo convert {filename} -o {stem}_nb.py\n\n"+ f" then open with marimo edit {stem}_nb.py"+ ) from None+# Only show the tip if we're in an interactive terminalif status == "invalid" and sys.stdin.isatty():click.echo(@@ -88,6 +101,7 @@ def check_app_correctness(filename: str) -> None:default=False,abort=True,)+if status == "has_errors":# Provide a warning, but allow the user to open the notebook_loggers.marimo_logger().warning(diff --git a/marimo/_cli/convert/commands.py b/marimo/_cli/convert/commands.pyindex b136e85965..ab1d927ea5 100644--- a/marimo/_cli/convert/commands.py+++ b/marimo/_cli/convert/commands.py@@ -28,10 +28,27 @@ def convert(filename: str,output: Optional[Path],) -> None:- r"""Convert a Jupyter notebook or Markdown file to a marimo notebook.+ r"""Convert a Jupyter notebook, Markdown file, or Python script to a marimo notebook.- The argument may be either a path to a local .ipynb/.md file,- or an .ipynb/.md file hosted on GitHub.+ Supported input formats:+ - `.ipynb` (local or GitHub-hosted)+ - `.md` files with `{python}` code fences+ - `.py` scripts in py:percent format++ Behavior:+ - Jupyter notebooks: outputs are stripped.++ - Markdown files: only `{python}` fenced code blocks are converted.++ Example:+ ```{python}+ x = 1 + 2+ print(x)+ ```+ - Python scripts:+ - If already a valid marimo notebook, no conversion is performed.+ - Otherwise, marimo attempts to convert using py:percent formatting,+ preserving top-level comments and docstrings.Example usage:@@ -41,27 +58,65 @@ def convert(marimo convert your_nb.md -o your_nb.py- Jupyter notebook conversion will strip out all outputs. Markdown cell- conversion with occur on the presence of `{python}` code fences.- After conversion, you can open the notebook in the editor:+ or++ marimo convert script.py -o your_nb.py++ After conversion:marimo edit your_nb.py- Since marimo is different from traditional notebooks, once in the editor,- you may need to fix errors like multiple definition errors or cycle- errors.+ Note:+ Since marimo's reactive execution differs from traditional notebooks,+ you may need to refactor code that mutates variables across cells+ (e.g., modifying a dataframe in multiple cells), which can lead to+ unexpected behavior."""ext = Path(filename).suffix- if ext not in (".ipynb", ".md", ".qmd"):- raise click.UsageError("File must be an .ipynb or .md file")+ if ext not in (".ipynb", ".md", ".qmd", ".py"):+ raise click.UsageError("File must be an .ipynb, .md, or .py file")text = load_external_file(filename, ext)if ext == ".ipynb":notebook = MarimoConvert.from_ipynb(text).to_py()- else:- assert ext in (".md", ".qmd")+ elif ext in (".md", ".qmd"):notebook = MarimoConvert.from_md(text).to_py()+ else:+ assert ext == ".py"+ # First check if it's already a valid marimo notebook+ from marimo._ast.parse import parse_notebook++ try:+ parsed = parse_notebook(text)+ except SyntaxError:+ # File has syntax errors+ echo("File cannot be converted. It may have syntax errors.")+ return++ if parsed and parsed.valid:+ # Already a valid marimo notebook+ echo("File is already a valid marimo notebook.")+ return++ try:+ notebook = MarimoConvert.from_non_marimo_python_script(+ text+ ).to_py()+ except ImportError as e:+ # Check if jupytext is the missing module in the cause chain+ if (+ e.__cause__+ and getattr(e.__cause__, "name", None) == "jupytext"+ ):+ from marimo._cli.print import green++ raise click.ClickException(+ f"{e}\n\n"+ f" {green('Tip:')} If you're using uv, run:\n\n"+ f" uvx --with=jupytext marimo convert {filename}"+ ) from e+ raiseif output:output_path = Path(output)diff --git a/marimo/_cli/file_path.py b/marimo/_cli/file_path.pyindex bfb1eafb24..ed33c66f1f 100644--- a/marimo/_cli/file_path.py+++ b/marimo/_cli/file_path.py@@ -257,7 +257,7 @@ class LocalFileHandler(FileHandler):f"Invalid NAME - {name} is not a Python file.\n\n"f" {green('Tip:')} Convert {name} to a marimo notebook with""\n\n"- f" marimo convert {name} > {prefix}.py\n\n"+ f" marimo convert {name} -o {prefix}.py\n\n"f" then open with marimo edit {prefix}.py")diff --git a/marimo/_convert/converters.py b/marimo/_convert/converters.pyindex 8fbc467e69..1612571132 100644--- a/marimo/_convert/converters.py+++ b/marimo/_convert/converters.py@@ -49,6 +49,26 @@ class MarimoConvert:ir = parse_notebook(source) or EMPTY_NOTEBOOK_SERIALIZATIONreturn MarimoConverterIntermediate(ir)+ @staticmethod+ def from_non_marimo_python_script(+ source: str,+ ) -> MarimoConverterIntermediate:+ """Convert from a non-marimo Python script to marimo notebook.++ This should only be used when the .py file is not already a valid+ marimo notebook.++ Args:+ source: Unknown Python script source code string+ """+ from marimo._convert.non_marimo_python_script import (+ convert_non_marimo_python_script_to_notebook_ir,+ )++ return MarimoConvert.from_ir(+ convert_non_marimo_python_script_to_notebook_ir(source)+ )+@staticmethoddef from_md(source: str) -> MarimoConverterIntermediate:"""Convert from markdown source code.diff --git a/marimo/_convert/non_marimo_python_script.py b/marimo/_convert/non_marimo_python_script.pynew file mode 100644index 0000000000..c8559c8f0d--- /dev/null+++ b/marimo/_convert/non_marimo_python_script.py@@ -0,0 +1,56 @@+# Copyright 2024 Marimo. All rights reserved.+"""Convert non-marimo Python scripts to marimo notebooks."""++from __future__ import annotations++import json++from marimo._convert.ipynb import convert_from_ipynb_to_notebook_ir+from marimo._schemas.serialization import NotebookSerialization+++def convert_non_marimo_python_script_to_notebook_ir(+ source: str,+) -> NotebookSerialization:+ """Convert a Python script that isn't in the notebook format into marimo notebook IR.++ This should only be called after verifying the file is not already+ a valid marimo notebook. It converts by:+ 1. If pypercent format is detected (# %%), use jupytext for conversion+ 2. Otherwise, puts all content into a single cell+ 3. Preserves PEP 723 inline script metadata if present+ """+ if "# %%" in source:+ try:+ import jupytext # type: ignore[import-untyped]+ except ImportError as e:+ raise ImportError(+ "Converting py:percent format requires jupytext"+ ) from e+ notebook = jupytext.reads(source, fmt="py:percent")+ else:+ notebook = {"cells": [{"source": source, "cell_type": "code"}]}++ notebook_str = json.dumps(notebook)++ ir = convert_from_ipynb_to_notebook_ir(notebook_str)+ _transform_main_blocks(ir)+ return ir+++def _transform_main_blocks(ir: NotebookSerialization) -> None:+ """Transform if __name__ == "__main__": blocks in cells to marimo-compatible functions."""+ main_pattern = 'if __name__ == "__main__":'++ for cell in ir.cells:+ if main_pattern in cell.code:+ parts = cell.code.split(main_pattern, 1)+ before_main = parts[0].strip()++ # replace the if __name__ == "__main__": with def _main_():+ main_block = "def _main_():" + parts[1] + "\n\n_main_()"++ if before_main:+ cell.code = before_main + "\n\n" + main_block+ else:+ cell.code = main_blockdiff --git a/pyproject.toml b/pyproject.tomlindex 7fb770aa5d..a92a651107 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -266,8 +266,9 @@ extra-dependencies = ["boto3>=1.38.46","litellm>=1.70.0",# exporting as ipynb- "nbformat >=5.10.4",+ "nbformat>=5.10.4","sympy>=1.13.3",+ "jupytext>=1.17.2",# For standard scientific computing/ ML"jax>=0.4.0; python_version == '3.12'","torch>=2.4.0; python_version == '3.12'",diff --git a/tests/_ast/codegen_data/test_get_codes_non_marimo_python_script.py b/tests/_ast/codegen_data/test_get_codes_non_marimo_python_script.pynew file mode 100644index 0000000000..c248050792--- /dev/null+++ b/tests/_ast/codegen_data/test_get_codes_non_marimo_python_script.py@@ -0,0 +1,11 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "altair==5.4.1",+# "duckdb==1.1.3",+# "marimo",+# ]+# ///++def hello():+ print("hello, world")diff --git a/tests/_ast/test_load.py b/tests/_ast/test_load.pyindex 3730efa58f..2a5013fe4f 100644--- a/tests/_ast/test_load.py+++ b/tests/_ast/test_load.py@@ -9,6 +9,7 @@ import pytestfrom marimo import _loggersfrom marimo._ast import load+from marimo._ast.parse import MarimoFileErrorDIR_PATH = os.path.dirname(os.path.realpath(__file__))@@ -216,6 +217,13 @@ class TestGetCodes:app = load_app(get_filepath("test_app_with_only_comments"))assert app is None+ @staticmethod+ def test_get_codes_non_marimo_python_script(static_load) -> None:+ with pytest.raises(MarimoFileError, match="is not a marimo notebook."):+ static_load(+ get_filepath("test_get_codes_non_marimo_python_script")+ )+@staticmethoddef test_get_codes_app_with_no_cells(load_app) -> None:app = load_app(get_filepath("test_app_with_no_cells"))diff --git a/tests/_cli/snapshots/python_script_no_main_to_marimo.txt b/tests/_cli/snapshots/python_script_no_main_to_marimo.txtnew file mode 100644index 0000000000..10873c31b2--- /dev/null+++ b/tests/_cli/snapshots/python_script_no_main_to_marimo.txt@@ -0,0 +1,20 @@+import marimo+++app = marimo.App()+++def _():+ """Simple calculation script."""++ x = 5+ y = 10+ result = x + y+ print(f"Result: {result}")+ return+++if __name__ == "__main__":+ app.run()+diff --git a/tests/_cli/snapshots/python_script_to_marimo.txt b/tests/_cli/snapshots/python_script_to_marimo.txtnew file mode 100644index 0000000000..716c594786--- /dev/null+++ b/tests/_cli/snapshots/python_script_to_marimo.txt@@ -0,0 +1,26 @@+import marimo+++app = marimo.App()+++def _():+ """A simple Python script."""++ import sys++ def main():+ print("Hello, World!")++ def _main_():+ main()+ sys.exit(0)++ _main_()+ return+++if __name__ == "__main__":+ app.run()+diff --git a/tests/_cli/test_cli_convert.py b/tests/_cli/test_cli_convert.pyindex 20282d42d4..7856ed3621 100644--- a/tests/_cli/test_cli_convert.py+++ b/tests/_cli/test_cli_convert.py@@ -167,7 +167,7 @@ print('Hello from Markdown!')text=True,)assert p.returncode != 0- assert "File must be an .ipynb or .md file" in p.stderr+ assert "File must be an .ipynb, .md, or .py file" in p.stderr@staticmethoddef test_convert_remote_ipynb(http_server: MockHTTPServer) -> None:@@ -255,7 +255,7 @@ print('Hello from Remote Markdown!')text=True,)assert p.returncode != 0- assert "File must be an .ipynb or .md file" in p.stderr+ assert "File must be an .ipynb, .md, or .py file" in p.stderr@staticmethoddef test_convert_nonexistent_remote_file(@@ -274,3 +274,82 @@ print('Hello from Remote Markdown!')assert p.returncode != 0# The error message will be from urllib.error.HTTPErrorassert "HTTP Error 404" in p.stderr or "Not Found" in p.stderr++ @staticmethod+ def test_convert_existing_marimo_notebook(tmp_path: Path) -> None:+ """Test that converting an existing marimo notebook prints a message."""+ marimo_path = tmp_path / "existing_marimo.py"+ marimo_content = """import marimo++__generated_with = "0.10.0"+app = marimo.App()+++def __():+ print("Hello from marimo!")+ return+++if __name__ == "__main__":+ app.run()+"""+ marimo_path.write_text(marimo_content)++ p = subprocess.run(+ ["marimo", "convert", str(marimo_path)],+ capture_output=True,+ text=True,+ )+ assert p.returncode == 0+ assert "File is already a valid marimo notebook." in p.stdout++ @staticmethod+ def test_convert_non_marimo_python_script(tmp_path: Path) -> None:+ """Test converting a non-marimo Python script."""+ script_path = tmp_path / "script.py"+ script_content = '''"""A simple Python script."""++import sys++def main():+ print("Hello, World!")++if __name__ == "__main__":+ main()+ sys.exit(0)+'''+ script_path.write_text(script_content)++ p = subprocess.run(+ ["marimo", "convert", str(script_path)],+ capture_output=True,+ text=True,+ )+ assert p.returncode == 0, p.stderr+ output = p.stdout+ output = re.sub(r"__generated_with = .*", "", output)+ snapshot("python_script_to_marimo.txt", output)++ @staticmethod+ def test_convert_python_script_no_main(tmp_path: Path) -> None:+ """Test converting a Python script without main block."""+ script_path = tmp_path / "simple_script.py"+ script_content = '''"""Simple calculation script."""++x = 5+y = 10+result = x + y+print(f"Result: {result}")+'''+ script_path.write_text(script_content)++ p = subprocess.run(+ ["marimo", "convert", str(script_path)],+ capture_output=True,+ text=True,+ )+ assert p.returncode == 0, p.stderr+ output = p.stdout+ output = re.sub(r"__generated_with = .*", "", output)+ snapshot("python_script_no_main_to_marimo.txt", output)diff --git a/tests/_convert/snapshots/minimal_script.py.txt b/tests/_convert/snapshots/minimal_script.py.txtnew file mode 100644index 0000000000..4f37b12132--- /dev/null+++ b/tests/_convert/snapshots/minimal_script.py.txt@@ -0,0 +1,16 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ x = 5+ y = 10+ print(x + y)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/snapshots/pypercent_format.py.txt b/tests/_convert/snapshots/pypercent_format.py.txtnew file mode 100644index 0000000000..8853c44e8e--- /dev/null+++ b/tests/_convert/snapshots/pypercent_format.py.txt@@ -0,0 +1,59 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ """Pypercent format notebook."""++ import numpy as np+ return (np,)++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ This is a markdown cell+ with multiple lines+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ This is a doc string, but also markdown+ """+ )+ return+++def _(np):+ # First code cell+ x = np.array([1, 2, 3])+ print(x)+ return (x,)+++def _(x):+ # Cell with title+ y = x * 2+ print(y)+ return+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/snapshots/pypercent_markdown_only.py.txt b/tests/_convert/snapshots/pypercent_markdown_only.py.txtnew file mode 100644index 0000000000..f7fcaadd82--- /dev/null+++ b/tests/_convert/snapshots/pypercent_markdown_only.py.txt@@ -0,0 +1,42 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ """Documentation in pypercent format."""+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ Introduction+ This is a documentation file.+ """+ )+ return++[email protected](hide_code=True)+def _(mo):+ mo.md(+ r"""+ Usage+ Here's how to use this module.+ """+ )+ return+++def _():+ import marimo as mo+ return (mo,)+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/snapshots/pypercent_with_main.py.txt b/tests/_convert/snapshots/pypercent_with_main.py.txtnew file mode 100644index 0000000000..3cb60e3dff--- /dev/null+++ b/tests/_convert/snapshots/pypercent_with_main.py.txt@@ -0,0 +1,30 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ """Script with main block in pypercent."""+ return+++def _():+ import sys+ return (sys,)+++def _(sys):+ def _main_():+ print("Running as script")+ sys.exit(0)++ _main_()+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/snapshots/simple_script.py.txt b/tests/_convert/snapshots/simple_script.py.txtnew file mode 100644index 0000000000..c829a9d81c--- /dev/null+++ b/tests/_convert/snapshots/simple_script.py.txt@@ -0,0 +1,21 @@+import marimo++__generated_with = "0.0.0"+app = marimo.App()+++def _():+ """A simple script."""++ import math++ def calculate_area(radius):+ return math.pi * radius ** 2++ print(calculate_area(5))+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_convert/test_convert_non_marimo_python_script.py b/tests/_convert/test_convert_non_marimo_python_script.pynew file mode 100644index 0000000000..cae93d3939--- /dev/null+++ b/tests/_convert/test_convert_non_marimo_python_script.py@@ -0,0 +1,103 @@+import pytest++from marimo._convert.converters import MarimoConvert+from marimo._convert.non_marimo_python_script import (+ convert_non_marimo_python_script_to_notebook_ir,+)+from marimo._dependencies.dependencies import DependencyManager+from tests.mocks import snapshotter++HAS_JUPYTEXT = DependencyManager.has("jupytext")++snapshot_test = snapshotter(__file__)+++class TestConvertNonMarimoPython:+ """Test conversion of non-marimo Python files to marimo notebooks."""++ def test_simple_script(self) -> None:+ """Test conversion of a simple script."""+ source = '''"""A simple script."""++import math++def calculate_area(radius):+ return math.pi * radius ** 2++print(calculate_area(5))+'''+ ir = convert_non_marimo_python_script_to_notebook_ir(source)+ converted = MarimoConvert.from_ir(ir).to_py()+ snapshot_test("simple_script.py.txt", converted)++ def test_script_no_header(self) -> None:+ """Test conversion of a minimal script without header."""+ source = """x = 5+y = 10+print(x + y)+"""+ ir = convert_non_marimo_python_script_to_notebook_ir(source)+ converted = MarimoConvert.from_ir(ir).to_py()+ snapshot_test("minimal_script.py.txt", converted)++ @pytest.mark.skipif(not HAS_JUPYTEXT, reason="jupytext not installed")+ def test_pypercent_format(self) -> None:+ """Test conversion of pypercent format file."""+ source = '''"""Pypercent format notebook."""++import numpy as np++# %% [markdown]+# This is a markdown cell+# with multiple lines++# %% [markdown]+"""This is a doc string, but also markdown"""++# %%+# First code cell+x = np.array([1, 2, 3])+print(x)++# %% Data processing+# Cell with title+y = x * 2+print(y)+'''+ ir = convert_non_marimo_python_script_to_notebook_ir(source)+ converted = MarimoConvert.from_ir(ir).to_py()+ snapshot_test("pypercent_format.py.txt", converted)++ @pytest.mark.skipif(not HAS_JUPYTEXT, reason="jupytext not installed")+ def test_pypercent_markdown_only(self) -> None:+ """Test pypercent file with only markdown cells."""+ source = '''"""Documentation in pypercent format."""++# %% [markdown]+# Introduction+This is a documentation file.++# %% [markdown]+# Usage+Here's how to use this module.+'''+ ir = convert_non_marimo_python_script_to_notebook_ir(source)+ converted = MarimoConvert.from_ir(ir).to_py()+ snapshot_test("pypercent_markdown_only.py.txt", converted)++ @pytest.mark.skipif(not HAS_JUPYTEXT, reason="jupytext not installed")+ def test_pypercent_with_main_block(self) -> None:+ """Test pypercent file with main block."""+ source = '''"""Script with main block in pypercent."""++# %%+import sys++# %%+if __name__ == "__main__":+ print("Running as script")+ sys.exit(0)+'''+ ir = convert_non_marimo_python_script_to_notebook_ir(source)+ converted = MarimoConvert.from_ir(ir).to_py()+ snapshot_test("pypercent_with_main.py.txt", converted)