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: allow editable installs when devloping locally with sandbox (#3568)
Myles Scolnick7170bc165db1
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex d40bf354bb..8a305edba5 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -8,6 +8,7 @@ import signalimport subprocessimport sysimport tempfile+from pathlib import Pathfrom typing import Any, Dict, List, Optional, castimport click@@ -17,6 +18,7 @@ from marimo._cli.file_path import FileContentReaderfrom marimo._cli.print import bold, echo, green, mutedfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._dependencies.dependencies import DependencyManager+from marimo._utils.versions import is_editableLOGGER = _loggers.marimo_logger()@@ -227,10 +229,9 @@ def _normalize_sandbox_dependencies(# Find all marimo dependenciesmarimo_deps = [d for d in dependencies if _is_marimo_dependency(d)]if not marimo_deps:- # During development, you can comment this out to install an- # editable version of marimo assuming you are in the marimo directory- # DO NOT COMMIT THIS WHEN SUBMITTING PRs- # return dependencies + [f"marimo -e ."]+ if is_editable("marimo"):+ LOGGER.info("Using editable of marimo for sandbox")+ return dependencies + [f"-e {get_marimo_dir()}"]return dependencies + [f"marimo=={marimo_version}"]@@ -241,6 +242,10 @@ def _normalize_sandbox_dependencies(# Remove all marimo depsfiltered = [d for d in dependencies if not _is_marimo_dependency(d)]+ if is_editable("marimo"):+ LOGGER.info("Using editable of marimo for sandbox")+ return filtered + [f"-e {get_marimo_dir()}"]+# Add version if not already versionedif not _is_versioned(chosen):chosen = f"{chosen}=={marimo_version}"@@ -248,6 +253,10 @@ def _normalize_sandbox_dependencies(return filtered + [chosen]+def get_marimo_dir() -> Path:+ return Path(__file__).parent.parent.parent++def construct_uv_command(args: list[str], name: str | None) -> list[str]:cmd = ["marimo"] + argsif "--sandbox" in cmd:diff --git a/marimo/_server/templates/templates.py b/marimo/_server/templates/templates.pyindex 4e2c72d255..466e9797ea 100644--- a/marimo/_server/templates/templates.py+++ b/marimo/_server/templates/templates.py@@ -17,6 +17,7 @@ from marimo._server.api.utils import parse_titlefrom marimo._server.file_manager import read_css_file, read_html_head_filefrom marimo._server.model import SessionModefrom marimo._server.tokens import SkewProtectionToken+from marimo._utils.versions import is_editabledef home_page_template(@@ -30,7 +31,7 @@ def home_page_template(html = html.replace("{{ user_config }}", json.dumps(user_config))html = html.replace("{{ config_overrides }}", json.dumps(config_overrides))html = html.replace("{{ server_token }}", str(server_token))- html = html.replace("{{ version }}", __version__)+ html = html.replace("{{ version }}", get_version())html = html.replace("{{ title }}", "marimo")html = html.replace("{{ app_config }}", json.dumps({}))@@ -54,7 +55,7 @@ def notebook_page_template(html = html.replace("{{ user_config }}", json.dumps(user_config))html = html.replace("{{ config_overrides }}", json.dumps(config_overrides))html = html.replace("{{ server_token }}", str(server_token))- html = html.replace("{{ version }}", __version__)+ html = html.replace("{{ version }}", get_version())html = html.replace("{{ title }}",@@ -123,7 +124,7 @@ def static_notebook_template()html = html.replace("{{ config_overrides }}", json.dumps(config_overrides))html = html.replace("{{ server_token }}", str(server_token))- html = html.replace("{{ version }}", __version__)+ html = html.replace("{{ version }}", get_version())html = html.replace("{{ title }}",@@ -345,3 +346,9 @@ def _del_none_or_empty(d: Any) -> Any:for key, value in d.items()if value is not None and value != []}+++def get_version() -> str:+ return (+ f"{__version__} (editable)" if is_editable("marimo") else __version__+ )diff --git a/marimo/_utils/versions.py b/marimo/_utils/versions.pynew file mode 100644index 0000000000..f1cfb11015--- /dev/null+++ b/marimo/_utils/versions.py@@ -0,0 +1,23 @@+from __future__ import annotations++import json+from importlib.metadata import Distribution+++def is_editable(pkg_name: str) -> bool:+ """Check if a package is an editable install"""++ try:+ direct_url = Distribution.from_name(pkg_name).read_text(+ "direct_url.json"+ )+ except Exception:+ return False++ if direct_url is None:+ return False++ pkg_is_editable = (+ json.loads(direct_url).get("dir_info", {}).get("editable", False)+ )+ return bool(pkg_is_editable)diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.pyindex 51f31cea19..78e4d238d3 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -13,7 +13,6 @@ from typing import TYPE_CHECKINGimport pytest-from marimo import __version__from marimo._dependencies.dependencies import DependencyManagerfrom tests._server.templates.utils import normalize_index_htmlfrom tests.mocks import snapshotter@@ -422,7 +421,6 @@ class TestExportScript:)assert p.returncode == 0, p.stderr.decode()output = p.stdout.decode()- output = output.replace(__version__, "0.0.0")snapshot("script.txt", output)@staticmethod@@ -469,7 +467,6 @@ class TestExportScript:)assert p.returncode == 0, p.stderr.decode()output = p.stdout.decode()- output = output.replace(__version__, "0.0.0")snapshot("script_with_errors.txt", output)@pytest.mark.skipif(@@ -556,7 +553,6 @@ class TestExportMarkdown:)assert p.returncode == 0, p.stderr.decode()output = p.stdout.decode()- output = output.replace(__version__, "0.0.0")snapshot("markdown.txt", output)@staticmethod@@ -567,7 +563,6 @@ class TestExportMarkdown:)assert p.returncode == 0, p.stderr.decode()output = p.stdout.decode()- output = output.replace(__version__, "0.0.0")snapshot("async.txt", output)@staticmethod@@ -578,7 +573,6 @@ class TestExportMarkdown:)assert p.returncode == 0, p.stderr.decode()output = p.stdout.decode()- output = output.replace(__version__, "0.0.0")snapshot("broken.txt", output)@staticmethod@@ -591,7 +585,6 @@ class TestExportMarkdown:)assert p.returncode == 0, p.stderr.decode()output = p.stdout.decode()- output = output.replace(__version__, "0.0.0")snapshot("export_markdown_with_errors.txt", output)@pytest.mark.skipif(@@ -792,7 +785,7 @@ class TestExportIpynb:assert p.returncode != 0, p.stderr.decode()assert "ZeroDivisionError" in p.stderr.decode()output = p.stdout.decode()- output = _delete_lines_with_files(output.replace(__version__, "0.0.0"))+ output = _delete_lines_with_files(output)snapshot("ipynb_with_errors.txt", output)@staticmethoddiff --git a/tests/_cli/test_markdown_conversion.py b/tests/_cli/test_markdown_conversion.pyindex 15b50607b1..c119229573 100644--- a/tests/_cli/test_markdown_conversion.py+++ b/tests/_cli/test_markdown_conversion.py@@ -63,9 +63,7 @@ def convert_from_py(py: str) -> str:)def test_markdown_snapshots() -> None:for name, mod in modules.items():- output = sanitized_version(- export_as_md(MarimoPath(mod.__file__)).contents- )+ output = export_as_md(MarimoPath(mod.__file__)).contentssnapshot(f"{name}.md.txt", output)@@ -100,7 +98,7 @@ def test_markdown_frontmatter() -> None:```"""[1:])- output = sanitized_version(convert_from_md(script))+ output = convert_from_md(script)assert 'app_title="My Title"' in outputsnapshot("frontmatter-test.py.txt", output)@@ -210,9 +208,7 @@ def test_python_to_md_code_injection() -> None:"""[1:])maybe_unsafe_md = convert_from_py(unsafe_app).strip()- maybe_unsafe_py = sanitized_version(- convert_from_md(maybe_unsafe_md).strip()- )+ maybe_unsafe_py = convert_from_md(maybe_unsafe_md).strip()snapshot("unsafe-app.py.txt", maybe_unsafe_py)snapshot("unsafe-app.md.txt", maybe_unsafe_md)diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex c9acdc2272..f6735f1d98 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -1,5 +1,8 @@from __future__ import annotations+from typing import Any+from unittest.mock import patch+import pytestfrom marimo._cli.sandbox import (@@ -244,12 +247,14 @@ def test_get_dependencies_with_nonexistent_file():assert get_dependencies_from_filename(None) == [] # type: ignore-def test_normalize_marimo_dependencies():+@patch("marimo._cli.sandbox.is_editable", return_value=False)+def test_normalize_marimo_dependencies(mock_is_editable: Any):# Test adding marimo when not presentassert _normalize_sandbox_dependencies(["numpy"], "1.0.0") == ["numpy","marimo==1.0.0",]+ assert mock_is_editable.call_count == 1# Test preferring bracketed versionassert _normalize_sandbox_dependencies(@@ -289,6 +294,18 @@ def test_normalize_marimo_dependencies():) == ["numpy", f"marimo{spec}"]+def test_normalize_marimo_dependencies_editable():+ deps = _normalize_sandbox_dependencies(["numpy"], "1.0.0")+ assert deps[0] == "numpy"+ assert deps[1].startswith("-e")+ assert "marimo" in deps[1]++ deps = _normalize_sandbox_dependencies(["numpy", "marimo"], "1.0.0")+ assert deps[0] == "numpy"+ assert deps[1].startswith("-e")+ assert "marimo" in deps[1]++def test_is_marimo_dependency():assert _is_marimo_dependency("marimo")assert _is_marimo_dependency("marimo[extras]")diff --git a/tests/_server/templates/utils.py b/tests/_server/templates/utils.pyindex a8187d4ac2..4592d78774 100644--- a/tests/_server/templates/utils.py+++ b/tests/_server/templates/utils.py@@ -3,8 +3,6 @@ from __future__ import annotationsimport osimport re-from marimo import __version__-def remove_hash_from_href(url: str) -> str:base, ext = os.path.splitext(url)@@ -39,5 +37,4 @@ def normalize_index_html(index_html: str) -> str:lambda x: remove_hash_from_href(x.group(0)),index_html,)- index_html = index_html.replace(__version__, "0.0.0")return index_htmldiff --git a/tests/mocks.py b/tests/mocks.pyindex e616bee220..4971a31470 100644--- a/tests/mocks.py+++ b/tests/mocks.py@@ -4,6 +4,7 @@ import difflibimport osfrom typing import Callable+from marimo import __version__from marimo._utils.paths import maybe_make_dirs@@ -18,11 +19,16 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:but the snapshot will be updated with the new result."""- def snapshot(filename: str, result: str) -> None:+ def snapshot(+ filename: str, result: str, keep_version: bool = False+ ) -> None:filepath = os.path.join(os.path.dirname(current_file), "snapshots", filename)+ if not keep_version:+ result = _sanitize_version(result)+# If snapshot directory doesn't exist, create itmaybe_make_dirs(filepath)@@ -78,3 +84,9 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:assert result == expected, f"Snapshot differs:\n{text_diff}"return snapshot+++def _sanitize_version(output: str) -> str:+ return output.replace(f"{__version__} (editable)", "0.0.0").replace(+ f"{__version__}", "0.0.0"+ )