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: --sandbox flag should add script metadata when none exists (#7954)

Akshay Agrawala8c7120c8481
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 3acbcfcf29..af3b8a54e9 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -24,6 +24,7 @@ from marimo._utils.inline_script_metadata import (
has_marimo_in_script_metadata,
is_marimo_dependency,
)
+from marimo._utils.scripts import with_python_version_requirement
from marimo._utils.uv import find_uv_bin
from marimo._utils.versions import is_editable
from marimo._version import __version__
@@ -320,25 +321,68 @@ 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.
+def _ensure_python_version_in_script_metadata(name: str) -> None:
+ """Add requires-python to script metadata if not present.
- If the file has PEP 723 script metadata but marimo is not listed
- as a dependency, add it using uv.
+ Reads the file, parses the PEP 723 metadata, adds requires-python
+ if missing, and writes the updated metadata back.
"""
+ from marimo._utils.scripts import (
+ REGEX,
+ read_pyproject_from_script,
+ write_pyproject_to_script,
+ )
+
+ with open(name, encoding="utf-8") as f:
+ content = f.read()
+
+ project = read_pyproject_from_script(content)
+ if project is None:
+ # No script metadata exists
+ return
+
+ if "requires-python" in project:
+ # Already has Python version
+ return
+
+ # Generate new script metadata block
+ project = with_python_version_requirement(project)
+ new_block = write_pyproject_to_script(project)
+
+ # Replace the old block with the new one
+ import re
+ new_content = re.sub(REGEX, new_block, content, count=1)
+
+ if new_content != content:
+ with open(name, "w", encoding="utf-8") as f:
+ f.write(new_content)
+
+
+def _ensure_marimo_in_script_metadata(name: str | None) -> None:
+ """Ensure marimo is in the script metadata.
+
+ If the file has no PEP 723 script metadata or marimo is not listed
+ as a dependency, add marimo using uv.
+ """
# Only applicable to `.py` files.
if name is None or not name.endswith(".py"):
return
+ # If the file doesn't exist or is empty, don't create it here - let marimo
+ # create the notebook normally with proper structure
+ if not os.path.exists(name) or os.path.getsize(name) == 0:
+ 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)
+ if has_marimo is True:
+ # marimo is already present
return
# Add marimo to script metadata using uv
+ # This will create the script metadata block if it doesn't exist
try:
result = subprocess.run(
[find_uv_bin(), "add", "--script", name, "marimo"],
@@ -373,8 +417,10 @@ 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 and python version are in the script metadata before running
_ensure_marimo_in_script_metadata(name)
+ if name is not None and name.endswith(".py"):
+ _ensure_python_version_in_script_metadata(name)
uv_cmd = construct_uv_command(
args, name, additional_features or [], additional_deps or []
diff --git a/marimo/_session/notebook/file_manager.py b/marimo/_session/notebook/file_manager.py
index a2118eeabd..4c561cb4b6 100644
--- a/marimo/_session/notebook/file_manager.py
+++ b/marimo/_session/notebook/file_manager.py
@@ -25,6 +25,7 @@ from marimo._session.notebook.storage import (
from marimo._types.ids import CellId_t
from marimo._utils.http import HTTPException, HTTPStatus
from marimo._utils.marimo_path import MarimoPath
+from marimo._utils.scripts import with_python_version_requirement
LOGGER = _loggers.marimo_logger()
@@ -194,7 +195,11 @@ class AppFileManager:
from marimo._utils.scripts import write_pyproject_to_script
header = write_pyproject_to_script(
- {"dependencies": ["marimo"]}
+ with_python_version_requirement(
+ {
+ "dependencies": ["marimo"],
+ }
+ )
)
# Rewrap with header if relevant and set filename.
diff --git a/marimo/_utils/scripts.py b/marimo/_utils/scripts.py
index 79ad6fe8e7..53549305f3 100644
--- a/marimo/_utils/scripts.py
+++ b/marimo/_utils/scripts.py
@@ -1,6 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
+import platform
import re
from typing import Any
@@ -11,6 +12,15 @@ REGEX = (
)
+def with_python_version_requirement(project: dict[str, Any]) -> dict[str, Any]:
+ # TODO(akshayka): consider locking the Python version for greater
+ # reproducibility, instead of returning a lowerbound
+ project = project.copy()
+ version_tuple = platform.python_version_tuple()
+ project["requires-python"] = f">={version_tuple[0]}.{version_tuple[1]}"
+ return project
+
+
def read_pyproject_from_script(script: str) -> dict[str, Any] | None:
"""
Read the pyproject.toml file from the script.
diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.py
index 86872f58bb..6515cbbebf 100644
--- a/tests/_cli/test_sandbox.py
+++ b/tests/_cli/test_sandbox.py
@@ -12,6 +12,7 @@ import pytest
from marimo._cli.sandbox import (
SandboxMode,
_ensure_marimo_in_script_metadata,
+ _ensure_python_version_in_script_metadata,
_normalize_sandbox_dependencies,
build_sandbox_venv,
cleanup_sandbox_dir,
@@ -532,6 +533,7 @@ import marimo
assert uv_cmd[python_idx + 1] == platform.python_version()
[email protected](not HAS_UV, reason="uv required")
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"
@@ -553,8 +555,9 @@ import marimo
def test_ensure_marimo_in_script_metadata_noop_when_present(
tmp_path: Path,
) -> None:
- """Test that file is unchanged when marimo already present."""
+ """Test that file is unchanged when marimo and requires-python already present."""
original = """# /// script
+# requires-python = ">=3.10"
# dependencies = ["marimo", "numpy"]
# ///
import marimo
@@ -563,14 +566,16 @@ import marimo
script_path.write_text(original)
_ensure_marimo_in_script_metadata(str(script_path))
+ _ensure_python_version_in_script_metadata(str(script_path))
assert script_path.read_text() == original
-def test_ensure_marimo_in_script_metadata_noop_no_metadata(
[email protected](not HAS_UV, reason="uv required")
+def test_ensure_marimo_in_script_metadata_adds_when_no_metadata(
tmp_path: Path,
) -> None:
- """Test that file is unchanged when no script metadata exists."""
+ """Test that script metadata is added when it doesn't exist."""
original = """import marimo
app = marimo.App()
"""
@@ -578,10 +583,86 @@ app = marimo.App()
script_path.write_text(original)
_ensure_marimo_in_script_metadata(str(script_path))
+ _ensure_python_version_in_script_metadata(str(script_path))
+
+ content = script_path.read_text()
+ assert "# /// script" in content
+ assert "marimo" in content
+ assert "requires-python" in content
+
+
[email protected](not HAS_UV, reason="uv required")
+def test_ensure_marimo_in_script_metadata_adds_python_version(
+ tmp_path: Path,
+) -> None:
+ """Test that requires-python is added to script metadata."""
+ import platform
+
+ script_path = tmp_path / "test.py"
+ script_path.write_text("""# /// script
+# dependencies = ["numpy"]
+# ///
+import marimo
+""")
+
+ _ensure_marimo_in_script_metadata(str(script_path))
+ _ensure_python_version_in_script_metadata(str(script_path))
+
+ content = script_path.read_text()
+ assert "requires-python" in content
+ major, minor = platform.python_version_tuple()[:2]
+ assert f">={major}.{minor}" in content
+
+
+def test_ensure_python_version_in_script_metadata(tmp_path: Path) -> None:
+ """Test that requires-python is added when missing."""
+ import platform
+
+ script_path = tmp_path / "test.py"
+ script_path.write_text("""# /// script
+# dependencies = ["marimo", "numpy"]
+# ///
+import marimo
+""")
+
+ _ensure_python_version_in_script_metadata(str(script_path))
+
+ content = script_path.read_text()
+ assert "requires-python" in content
+ major, minor = platform.python_version_tuple()[:2]
+ assert f">={major}.{minor}" in content
+
+
+def test_ensure_python_version_in_script_metadata_noop_when_present(
+ tmp_path: Path,
+) -> None:
+ """Test that file is unchanged when requires-python already present."""
+ original = """# /// script
+# requires-python = ">=3.10"
+# dependencies = ["marimo", "numpy"]
+# ///
+import marimo
+"""
+ script_path = tmp_path / "test.py"
+ script_path.write_text(original)
+
+ _ensure_python_version_in_script_metadata(str(script_path))
assert script_path.read_text() == original
+def test_ensure_marimo_in_script_metadata_noop_when_file_missing(
+ tmp_path: Path,
+) -> None:
+ """Test that file is not created when it doesn't exist."""
+ script_path = tmp_path / "nonexistent.py"
+
+ _ensure_marimo_in_script_metadata(str(script_path))
+
+ # File should still not exist
+ assert not script_path.exists()
+
+
def test_get_sandbox_requirements_adds_additional_deps(tmp_path: Path) -> None:
"""Test that additional deps are added when not present."""
from marimo._cli.sandbox import get_sandbox_requirements
diff --git a/tests/_utils/test_scripts.py b/tests/_utils/test_scripts.py
index 5a7fa03060..480ca20610 100644
--- a/tests/_utils/test_scripts.py
+++ b/tests/_utils/test_scripts.py
@@ -4,7 +4,10 @@ import textwrap
import pytest
-from marimo._utils.scripts import read_pyproject_from_script
+from marimo._utils.scripts import (
+ read_pyproject_from_script,
+ with_python_version_requirement,
+)
def test_read_pyproject_from_script():
@@ -79,3 +82,29 @@ def test_read_marimo_config_from_script():
assert config["tool"]["marimo"]["runtime"]["output_max_bytes"] == 20
assert config["tool"]["marimo"]["runtime"]["std_stream_max_bytes"] == 10
assert config["tool"]["marimo"]["display"]["cell_output"] == "above"
+
+
+def test_with_python_version_requirement():
+ import platform
+
+ project = {"dependencies": ["numpy"]}
+ result = with_python_version_requirement(project)
+
+ # Original should not be mutated
+ assert project == {"dependencies": ["numpy"]}
+
+ # Check the result
+ major, minor = platform.python_version_tuple()[:2]
+ assert result == {
+ "dependencies": ["numpy"],
+ "requires-python": f">={major}.{minor}",
+ }
+
+
+def test_with_python_version_requirement_empty_project():
+ import platform
+
+ result = with_python_version_requirement({})
+
+ major, minor = platform.python_version_tuple()[:2]
+ assert result == {"requires-python": f">={major}.{minor}"}