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
improvement: support uv index-url and extra-index-url (#3827)
Myles Scolnicka63d22862b94
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex 155b399d07..4f892171c8 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -9,7 +9,7 @@ import subprocessimport sysimport tempfilefrom pathlib import Path-from typing import Any, Dict, List, Optional, cast+from typing import Any, Optional, castimport click@@ -24,19 +24,68 @@ from marimo._utils.versions import is_editableLOGGER = _loggers.marimo_logger()-def _get_dependencies(script: str) -> List[str] | None:- """Get dependencies from string representation of script."""- try:- pyproject = read_pyproject_from_script(script) or {}- return _pyproject_toml_to_requirements_txt(pyproject)- except Exception as e:- LOGGER.warning(f"Failed to parse dependencies: {e}")- return None+class PyProjectReader:+ def __init__(self, project: dict[str, Any]):+ self.project = project++ @staticmethod+ def from_filename(name: str) -> "PyProjectReader":+ return PyProjectReader(_get_pyproject_from_filename(name) or {})++ @staticmethod+ def from_script(script: str) -> "PyProjectReader":+ return PyProjectReader(read_pyproject_from_script(script) or {})++ @property+ def extra_index_urls(self) -> list[str]:+ # See https://docs.astral.sh/uv/reference/settings/#pip_extra-index-url+ return ( # type: ignore[no-any-return]+ self.project.get("tool", {})+ .get("uv", {})+ .get("extra-index-url", [])+ )++ @property+ def index_configs(self) -> list[dict[str, str]]:+ # See https://docs.astral.sh/uv/reference/settings/#index+ return self.project.get("tool", {}).get("uv", {}).get("index", []) # type: ignore[no-any-return]++ @property+ def index_url(self) -> str | None:+ # See https://docs.astral.sh/uv/reference/settings/#pip_index-url+ return ( # type: ignore[no-any-return]+ self.project.get("tool", {}).get("uv", {}).get("index-url", None)+ )++ @property+ def python_version(self) -> str | None:+ try:+ version = self.project.get("requires-python")+ # Only return string version requirements+ if not isinstance(version, str):+ return None+ return version+ except Exception as e:+ LOGGER.warning(f"Failed to parse Python version requirement: {e}")+ return None++ @property+ def dependencies(self) -> list[str]:+ return self.project.get("dependencies", []) # type: ignore[no-any-return]++ @property+ def requirements_txt_lines(self) -> list[str]:+ """Get dependencies from string representation of script."""+ try:+ return _pyproject_toml_to_requirements_txt(self.project)+ except Exception as e:+ LOGGER.warning(f"Failed to parse dependencies: {e}")+ return []def _pyproject_toml_to_requirements_txt(- pyproject: Dict[str, Any],-) -> List[str]:+ pyproject: dict[str, Any],+) -> list[str]:"""Convert a pyproject.toml file to a requirements.txt file.@@ -50,7 +99,7 @@ def _pyproject_toml_to_requirements_txt(# [tool.uv.sources]# python-gcode = { git = "https://github.com/fetlab/python_gcode", rev = "new" }""" # noqa: E501- dependencies = cast(List[str], pyproject.get("dependencies", []))+ dependencies = cast(list[str], pyproject.get("dependencies", []))if not dependencies:return []@@ -104,35 +153,14 @@ def _pyproject_toml_to_requirements_txt(return dependencies-def get_dependencies_from_filename(name: str) -> List[str]:- if not name:- return []-+def _get_pyproject_from_filename(name: str) -> dict[str, Any] | None:try:contents, _ = FileContentReader().read_file(name)- return _get_dependencies(contents) or []+ return read_pyproject_from_script(contents)except FileNotFoundError:- return []- except Exception:- LOGGER.warning(f"Failed to read dependencies from {name}")- return []---def _get_python_version_requirement(- pyproject: Dict[str, Any] | None,-) -> str | None:- """Extract Python version requirement from pyproject metadata."""- if pyproject is None:return None-- try:- version = pyproject.get("requires-python")- # Only return string version requirements- if not isinstance(version, str):- return None- return version- except Exception as e:- LOGGER.warning(f"Failed to parse Python version requirement: {e}")+ except Exception:+ LOGGER.warning(f"Failed to read pyproject.toml from {name}")return None@@ -143,8 +171,8 @@ def prompt_run_in_sandbox(name: str | None) -> bool:if name is None:return False- dependencies = get_dependencies_from_filename(name)- if not dependencies:+ pyproject = PyProjectReader.from_filename(name)+ if not pyproject.dependencies:return False# Notebook has inlined dependencies.@@ -190,8 +218,8 @@ def _is_versioned(dependency: str) -> bool:def _normalize_sandbox_dependencies(- dependencies: List[str], marimo_version: str-) -> List[str]:+ dependencies: list[str], marimo_version: str+) -> list[str]:"""Normalize marimo dependencies to have only one version.If multiple marimo dependencies exist, prefer the one with brackets.@@ -233,11 +261,15 @@ def construct_uv_command(args: list[str], name: str | None) -> list[str]:if "--sandbox" in cmd:cmd.remove("--sandbox")- # If name if a filepath, parse the dependencies from the file- dependencies = (- get_dependencies_from_filename(name) if name is not None else []+ pyproject = (+ PyProjectReader.from_filename(name)+ if name is not None+ else PyProjectReader({}))+ # If name if a filepath, parse the dependencies from the file+ dependencies = pyproject.requirements_txt_lines+# If there are no dependencies, which can happen for marimo new or# on marimo edit a_new_file.py, uv may use a cached venv, even though# we are passing --isolated; `--refresh` ensures that the venv is@@ -255,18 +287,6 @@ def construct_uv_command(args: list[str], name: str | None) -> list[str]:# Clean up the temporary file after the subprocess has runatexit.register(lambda: os.unlink(temp_file_path))- # Get Python version requirement if available- if name is not None and os.path.exists(name):- contents, _ = FileContentReader().read_file(name)- pyproject = read_pyproject_from_script(contents)- python_version = (- _get_python_version_requirement(pyproject)- if pyproject is not None- else None- )- else:- python_version = None-# Construct base UV commanduv_cmd = ["uv",@@ -277,12 +297,36 @@ def construct_uv_command(args: list[str], name: str | None) -> list[str]:"--no-project","--with-requirements",temp_file_path,- ] + (["--refresh"] if uv_needs_refresh else [])+ ]++ # Add refresh+ if uv_needs_refresh:+ uv_cmd.append("--refresh")# Add Python version if specified+ python_version = pyproject.python_versionif python_version:uv_cmd.extend(["--python", python_version])+ # Add index URL if specified+ index_url = pyproject.index_url+ if index_url:+ uv_cmd.extend(["--index-url", index_url])++ # Add extra-index-urls if specified+ extra_index_urls = pyproject.extra_index_urls+ if extra_index_urls:+ for url in extra_index_urls:+ uv_cmd.extend(["--extra-index-url", url])++ # Add index configs if specified+ index_configs = pyproject.index_configs+ if index_configs:+ for config in index_configs:+ if "url" in config:+ # Looks like: https://docs.astral.sh/uv/guides/scripts/#using-alternative-package-indexes+ uv_cmd.extend(["--index", config["url"]])+# Final command assembly: combine the uv prefix with the original marimo# command.return uv_cmd + cmddiff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex a882e3c71f..fedc6b4204 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -1,21 +1,22 @@from __future__ import annotations-from typing import Any+from typing import TYPE_CHECKING, Anyfrom unittest.mock import patchimport pytestfrom marimo._cli.sandbox import (- _get_dependencies,- _get_python_version_requirement,+ PyProjectReader,_is_marimo_dependency,_normalize_sandbox_dependencies,_pyproject_toml_to_requirements_txt,construct_uv_command,- get_dependencies_from_filename,)from marimo._utils.scripts import read_pyproject_from_script+if TYPE_CHECKING:+ from pathlib import Path+def test_get_dependencies():SCRIPT = """@@ -35,7 +36,7 @@ import marimo__generated_with = "0.8.2"app = marimo.App(width="medium")"""- assert _get_dependencies(SCRIPT) == [+ assert PyProjectReader.from_script(SCRIPT).dependencies == ["polars","marimo>=0.8.0","quak",@@ -45,7 +46,7 @@ app = marimo.App(width="medium")def test_get_dependencies_github():url = "https://github.com/marimo-team/marimo/blob/a1e1be3190023a86650904249f911b2e6ffb8fac/examples/third_party/leafmap/leafmap_example.py"- assert get_dependencies_from_filename(url) == [+ assert PyProjectReader.from_filename(url).dependencies == ["leafmap==0.41.0","marimo",]@@ -58,7 +59,7 @@ import marimo__generated_with = "0.8.2"app = marimo.App(width="medium")"""- assert _get_dependencies(SCRIPT) == []+ assert PyProjectReader.from_script(SCRIPT).dependencies == []def test_pyproject_toml_to_requirements_txt_git_sources():@@ -200,15 +201,15 @@ def test_pyproject_toml_to_requirements_txt_with_versioned_dependencies(def test_get_python_version_requirement():pyproject = {"requires-python": ">=3.11"}- assert _get_python_version_requirement(pyproject) == ">=3.11"+ assert PyProjectReader(pyproject).python_version == ">=3.11"pyproject = {"dependencies": ["polars"]}- assert _get_python_version_requirement(pyproject) is None+ assert PyProjectReader(pyproject).python_version is None- assert _get_python_version_requirement(None) is None+ assert PyProjectReader({}).python_version is Nonepyproject = {"requires-python": {"invalid": "type"}}- assert _get_python_version_requirement(pyproject) is None+ assert PyProjectReader(pyproject).python_version is Nonedef test_get_dependencies_with_python_version():@@ -220,11 +221,11 @@ def test_get_dependencies_with_python_version():import marimo"""- assert _get_dependencies(SCRIPT) == ["polars"]+ assert PyProjectReader.from_script(SCRIPT).dependencies == ["polars"]pyproject = read_pyproject_from_script(SCRIPT)assert pyproject is not None- assert _get_python_version_requirement(pyproject) == ">=3.11"+ assert PyProjectReader(pyproject).python_version == ">=3.11"SCRIPT_NO_PYTHON = """# /// script@@ -235,16 +236,20 @@ import marimo"""pyproject_no_python = read_pyproject_from_script(SCRIPT_NO_PYTHON)assert pyproject_no_python is not None- assert _get_python_version_requirement(pyproject_no_python) is None- assert _get_dependencies(SCRIPT_NO_PYTHON) == ["polars"]+ assert PyProjectReader(pyproject_no_python).python_version is None+ assert PyProjectReader.from_script(SCRIPT_NO_PYTHON).dependencies == [+ "polars"+ ]def test_get_dependencies_with_nonexistent_file():# Test with a non-existent file- assert get_dependencies_from_filename("nonexistent_file.py") == []+ assert (+ PyProjectReader.from_filename("nonexistent_file.py").dependencies == []+ )- # Test with None- assert get_dependencies_from_filename(None) == [] # type: ignore+ # Test with empty+ assert PyProjectReader.from_filename("").dependencies == []@patch("marimo._cli.sandbox.is_editable", return_value=False)@@ -362,3 +367,108 @@ def test_construct_uv_cmd_marimo_edit_sandboxed_file(assert "--refresh" not in uv_cmdassert uv_cmd[0] == "uv"assert uv_cmd[1] == "run"+++def test_construct_uv_cmd_with_python_version(tmp_path: Path) -> None:+ # Test Python version requirement is passed through+ script_path = tmp_path / "test.py"+ script_path.write_text(+ """+# /// script+# requires-python = ">=3.11"+# dependencies = ["numpy"]+# ///+import marimo+ """+ )+ uv_cmd = construct_uv_command(+ ["edit", str(script_path), "--sandbox"], str(script_path)+ )+ assert "--python" in uv_cmd+ assert ">=3.11" in uv_cmd+ assert "--isolated" in uv_cmd+ assert "--no-project" in uv_cmd+ assert "--sandbox" not in uv_cmd+++def test_construct_uv_cmd_with_index_urls() -> None:+ pyproject = {+ "tool": {+ "uv": {+ "index-url": "https://custom.pypi.org/simple",+ "extra-index-url": [+ "https://extra1.pypi.org/simple",+ "https://extra2.pypi.org/simple",+ ],+ }+ }+ }+ with patch("marimo._cli.sandbox.PyProjectReader.from_filename") as mock:+ mock.return_value = PyProjectReader(pyproject)+ uv_cmd = construct_uv_command(+ ["edit", "test.py", "--sandbox"], "test.py"+ )+ assert "--index-url" in uv_cmd+ assert "https://custom.pypi.org/simple" in uv_cmd+ assert "--extra-index-url" in uv_cmd+ assert "https://extra1.pypi.org/simple" in uv_cmd+ assert "https://extra2.pypi.org/simple" in uv_cmd+++def test_construct_uv_cmd_with_index_configs() -> None:+ pyproject = {+ "tool": {+ "uv": {+ "index": [+ {+ "name": "torch-gpu",+ "url": "https://download.pytorch.org/whl/cu124",+ }+ ]+ }+ }+ }+ with patch("marimo._cli.sandbox.PyProjectReader.from_filename") as mock:+ mock.return_value = PyProjectReader(pyproject)+ uv_cmd = construct_uv_command(+ ["edit", "test.py", "--sandbox"], "test.py"+ )+ assert "--index" in uv_cmd+ assert "https://download.pytorch.org/whl/cu124" in uv_cmd+++def test_construct_uv_cmd_with_sandbox_flag() -> None:+ # Test --sandbox flag is removed+ uv_cmd = construct_uv_command(["edit", "test.py", "--sandbox"], "test.py")+ assert "--sandbox" not in uv_cmd+++def test_construct_uv_cmd_empty_dependencies() -> None:+ # Test empty dependencies triggers refresh+ with patch("marimo._cli.sandbox.PyProjectReader.from_filename") as mock:+ mock.return_value = PyProjectReader({})+ uv_cmd = construct_uv_command(["edit", "test.py"], "test.py")+ assert "--refresh" in uv_cmd+ assert "--isolated" in uv_cmd+ assert "--no-project" in uv_cmd+++def test_construct_uv_cmd_with_complex_args() -> None:+ # Test complex command arguments are preserved+ args = [+ "edit",+ "test.py",+ "--theme",+ "dark",+ "--port",+ "8000",+ "--sandbox",+ ]+ uv_cmd = construct_uv_command(args, "test.py")+ assert "edit" in uv_cmd+ assert "test.py" in uv_cmd+ assert "--theme" in uv_cmd+ assert "dark" in uv_cmd+ assert "--port" in uv_cmd+ assert "8000" in uv_cmd+ assert "--sandbox" not in uv_cmd