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: add marimo as a dependency if it isn't already (#7656)
Dylan Madisetti4f0ebf26da56
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 6aac35d479..17c62fd306 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -19,6 +19,7 @@ from marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._utils.inline_script_metadata import (PyProjectReader,+ has_marimo_in_script_metadata,is_marimo_dependency,)from marimo._utils.uv import find_uv_bin@@ -325,6 +326,39 @@ def construct_uv_command(return uv_cmd + cmd+def _ensure_marimo_in_script_metadata(name: str | None) -> None:+ """Ensure marimo is in the script metadata if metadata exists.++ If the file has PEP 723 script metadata but marimo is not listed+ as a dependency, add it using uv.+ """++ # Only applicable to `.py` files.+ if name is None or not name.endswith(".py"):+ return++ # Check if script metadata exists and whether marimo is present+ # Returns: True (has marimo), False (no marimo), None (no metadata)+ has_marimo = has_marimo_in_script_metadata(name)+ if has_marimo is not False:+ # Either marimo is present (True) or no metadata exists (None)+ return++ # Add marimo to script metadata using uv+ try:+ result = subprocess.run(+ [find_uv_bin(), "add", "--script", name, "marimo"],+ check=True,+ capture_output=True,+ text=True,+ )+ LOGGER.info(f"Added marimo to script metadata: {result.stdout}")+ except subprocess.CalledProcessError as e:+ LOGGER.warning(f"Failed to add marimo to script metadata: {e.stderr}")+ except Exception as e:+ LOGGER.warning(f"Failed to add marimo to script metadata: {e}")++def run_in_sandbox(args: list[str],*,@@ -336,6 +370,9 @@ def run_in_sandbox(if find_uv_bin() == "uv" and not DependencyManager.which("uv"):raise click.UsageError("uv must be installed to use --sandbox")+ # Ensure marimo is in the script metadata before running+ _ensure_marimo_in_script_metadata(name)+uv_cmd = construct_uv_command(args, name, additional_features or [], additional_deps or [])diff --git a/marimo/_utils/inline_script_metadata.py b/marimo/_utils/inline_script_metadata.pyindex ee642b5e3f..aa8ecf5074 100644--- a/marimo/_utils/inline_script_metadata.py+++ b/marimo/_utils/inline_script_metadata.py@@ -229,3 +229,20 @@ def get_headers_from_frontmatter(headers["pyproject"] = pyprojectheaders["header"] = frontmatter.get("header", "")return headers+++def has_marimo_in_script_metadata(filepath: str) -> bool | None:+ """Check if marimo is in the file's PEP 723 script metadata dependencies.++ Returns:+ True if marimo is in dependencies+ False if script metadata exists but marimo is not in dependencies+ None if file has no script metadata+ """++ project = _get_pyproject_from_filename(filepath)+ if project is None:+ return None++ dependencies = project.get("dependencies", [])+ return any(is_marimo_dependency(dep) for dep in dependencies)diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex 24da569ea2..79e6d2d98c 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -7,6 +7,7 @@ import clickimport pytestfrom marimo._cli.sandbox import (+ _ensure_marimo_in_script_metadata,_normalize_sandbox_dependencies,construct_uv_command,should_run_in_sandbox,@@ -508,3 +509,53 @@ import marimoassert "--python" in uv_cmdpython_idx = uv_cmd.index("--python")assert uv_cmd[python_idx + 1] == platform.python_version()+++def test_ensure_marimo_in_script_metadata_adds_marimo(tmp_path: Path) -> None:+ """Test that marimo is added to script metadata when missing."""+ script_path = tmp_path / "test.py"+ script_path.write_text(+ """# /// script+# dependencies = ["numpy"]+# ///+import marimo+"""+ )++ _ensure_marimo_in_script_metadata(str(script_path))++ content = script_path.read_text()+ assert "marimo" in content+ assert "numpy" in content+++def test_ensure_marimo_in_script_metadata_noop_when_present(+ tmp_path: Path,+) -> None:+ """Test that file is unchanged when marimo already present."""+ original = """# /// script+# dependencies = ["marimo", "numpy"]+# ///+import marimo+"""+ script_path = tmp_path / "test.py"+ script_path.write_text(original)++ _ensure_marimo_in_script_metadata(str(script_path))++ assert script_path.read_text() == original+++def test_ensure_marimo_in_script_metadata_noop_no_metadata(+ tmp_path: Path,+) -> None:+ """Test that file is unchanged when no script metadata exists."""+ original = """import marimo+app = marimo.App()+"""+ script_path = tmp_path / "test.py"+ script_path.write_text(original)++ _ensure_marimo_in_script_metadata(str(script_path))++ assert script_path.read_text() == originaldiff --git a/tests/_utils/test_inline_script_metadata.py b/tests/_utils/test_inline_script_metadata.pyindex e93dfd4f4d..e6191dd563 100644--- a/tests/_utils/test_inline_script_metadata.py+++ b/tests/_utils/test_inline_script_metadata.py@@ -5,6 +5,7 @@ import pytestfrom marimo._utils.inline_script_metadata import (PyProjectReader,_pyproject_toml_to_requirements_txt,+ has_marimo_in_script_metadata,is_marimo_dependency,)from marimo._utils.platform import is_windows@@ -335,3 +336,28 @@ def test_is_marimo_dependency():assert not is_marimo_dependency("pandas")assert not is_marimo_dependency("marimo-ai")assert not is_marimo_dependency("marimo-ai==0.1.0")+++def test_has_marimo_in_script_metadata(tmp_path):+ """Test has_marimo_in_script_metadata returns correct values."""+ # True: marimo present+ with_marimo = tmp_path / "with_marimo.py"+ with_marimo.write_text(+ "# /// script\n# dependencies = ['marimo']\n# ///\n"+ )+ assert has_marimo_in_script_metadata(str(with_marimo)) is True++ # False: metadata exists but no marimo+ without_marimo = tmp_path / "without_marimo.py"+ without_marimo.write_text(+ "# /// script\n# dependencies = ['numpy']\n# ///\n"+ )+ assert has_marimo_in_script_metadata(str(without_marimo)) is False++ # None: no metadata+ no_metadata = tmp_path / "no_metadata.py"+ no_metadata.write_text("import marimo\n")+ assert has_marimo_in_script_metadata(str(no_metadata)) is None++ # None: non-.py file+ assert has_marimo_in_script_metadata(str(tmp_path / "test.md")) is None