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: follow pycache_prefix for __marimo__ location (#8797)

Dylan Madisettif775691f7c58
diff --git a/marimo/_cli/export/thumbnail.py b/marimo/_cli/export/thumbnail.py
index 5759776c89..7693a9a79b 100644
--- a/marimo/_cli/export/thumbnail.py
+++ b/marimo/_cli/export/thumbnail.py
@@ -208,7 +208,7 @@ async def _generate_thumbnails(
sandbox_mode: SandboxMode | None,
) -> None:
from marimo._cli.sandbox import SandboxMode
- from marimo._metadata.opengraph import default_opengraph_image
+ from marimo._metadata.opengraph import default_opengraph_image_abs
failures: list[tuple[MarimoPath, Exception]] = []
@@ -255,12 +255,12 @@ async def _generate_thumbnails(
for index, notebook in enumerate(notebooks):
try:
- notebook_dir = notebook.path.parent
out_path = (
output
if output is not None
- else notebook_dir
- / default_opengraph_image(str(notebook.path))
+ else default_opengraph_image_abs(
+ str(notebook.path)
+ )
)
if out_path.exists() and not overwrite:
echo(
diff --git a/marimo/_metadata/opengraph.py b/marimo/_metadata/opengraph.py
index 66176ec2c4..f6b4d2cfa1 100644
--- a/marimo/_metadata/opengraph.py
+++ b/marimo/_metadata/opengraph.py
@@ -14,7 +14,7 @@ from urllib.parse import urlparse
import msgspec
from marimo import _loggers
-from marimo._utils.paths import normalize_path
+from marimo._utils.paths import MARIMO_DIR_NAME, notebook_output_dir
from marimo._utils.scripts import read_pyproject_from_script
LOGGER = _loggers.marimo_logger()
@@ -160,12 +160,27 @@ def derive_title_from_path(filepath: str) -> str:
def default_opengraph_image(filepath: str) -> str:
"""Return the default relative image path for a given notebook."""
stem = Path(filepath).stem
- return f"__marimo__/assets/{stem}/{DEFAULT_OPENGRAPH_IMAGE_FILENAME}"
+ return str(
+ Path(MARIMO_DIR_NAME)
+ / "assets"
+ / stem
+ / DEFAULT_OPENGRAPH_IMAGE_FILENAME
+ )
+
+
+def default_opengraph_image_abs(filepath: str) -> Path:
+ """Return the absolute image path for a given notebook."""
+ stem = Path(filepath).stem
+ return (
+ notebook_output_dir(filepath)
+ / "assets"
+ / stem
+ / DEFAULT_OPENGRAPH_IMAGE_FILENAME
+ )
def _default_image_exists(filepath: str) -> bool:
- notebook_dir = normalize_path(Path(filepath)).parent
- return (notebook_dir / default_opengraph_image(filepath)).is_file()
+ return default_opengraph_image_abs(filepath).is_file()
def _merge_opengraph_metadata(
diff --git a/marimo/_save/stores/file.py b/marimo/_save/stores/file.py
index cfb2b8bfbb..755989489e 100644
--- a/marimo/_save/stores/file.py
+++ b/marimo/_save/stores/file.py
@@ -6,6 +6,7 @@ from typing import Optional
from marimo._runtime.runtime import notebook_dir
from marimo._save.stores.store import Store
+from marimo._utils.paths import notebook_output_dir
def _valid_path(path: Path) -> bool:
@@ -14,14 +15,22 @@ def _valid_path(path: Path) -> bool:
class FileStore(Store):
def __init__(self, save_path: Optional[str] = None) -> None:
- self.save_path = Path(save_path or self._default_save_path())
- # NB. construction may be called on store import, so do not create
- # directories until needed.
+ # Defer default path resolution until first use so that the runtime
+ # context (and __file__) is available.
+ self._resolved_save_path: Path | None = (
+ Path(save_path) if save_path is not None else None
+ )
self._initialized = False
+ @property
+ def save_path(self) -> Path:
+ if self._resolved_save_path is None:
+ self._resolved_save_path = self._default_save_path()
+ return self._resolved_save_path
+
def _default_save_path(self) -> Path:
if (root := notebook_dir()) is not None:
- return Path(root / "__marimo__" / "cache")
+ return notebook_output_dir(root) / "cache"
# This can happen if the notebook file is unnamed.
return Path("__marimo__", "cache")
diff --git a/marimo/_server/api/endpoints/assets.py b/marimo/_server/api/endpoints/assets.py
index 92a95eb706..7a93888e9e 100644
--- a/marimo/_server/api/endpoints/assets.py
+++ b/marimo/_server/api/endpoints/assets.py
@@ -35,7 +35,12 @@ from marimo._server.templates.templates import (
)
from marimo._session.model import SessionMode
from marimo._utils.async_path import AsyncPath
-from marimo._utils.paths import marimo_package_path, normalize_path
+from marimo._utils.paths import (
+ MARIMO_DIR_NAME,
+ marimo_package_path,
+ normalize_path,
+ notebook_output_dir,
+)
if TYPE_CHECKING:
from starlette.requests import Request
@@ -137,7 +142,7 @@ def og_thumbnail(*, request: Request) -> Response:
)
notebook_dir = normalize_path(Path(notebook_path)).parent
- marimo_dir = notebook_dir / "__marimo__"
+ marimo_dir = notebook_output_dir(notebook_path)
# User-defined OpenGraph generators receive this context (file key, base URL, mode)
# so they can compute metadata dynamically for gallery cards, social previews, and other modes.
@@ -164,7 +169,13 @@ def og_thumbnail(*, request: Request) -> Response:
rel_path = Path(image)
if not rel_path.is_absolute():
- file_path = normalize_path(notebook_dir / rel_path)
+ # Resolve __marimo__/ relative paths against the
+ # (potentially relocated) marimo output directory.
+ parts = rel_path.parts
+ if parts and parts[0] == MARIMO_DIR_NAME:
+ file_path = normalize_path(marimo_dir / Path(*parts[1:]))
+ else:
+ file_path = normalize_path(notebook_dir / rel_path)
# Only allow serving from the notebook's __marimo__ directory.
try:
if file_path.is_file():
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index eb88b7d0e0..8f9e0692af 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -47,7 +47,7 @@ from marimo._utils import async_path
from marimo._utils.code import hash_code
from marimo._utils.data_uri import build_data_url
from marimo._utils.marimo_path import MarimoPath
-from marimo._utils.paths import marimo_package_path
+from marimo._utils.paths import marimo_package_path, notebook_output_dir
from marimo._version import __version__
if TYPE_CHECKING:
@@ -622,8 +622,6 @@ class Exporter:
class AutoExporter:
- EXPORT_DIR = "__marimo__"
-
def __init__(self) -> None:
# Cache directories we've already created to avoid redundant checks
self._created_dirs: set[Path] = set()
@@ -635,11 +633,12 @@ class AutoExporter:
async def _save_file(
self, filename: Optional[str], content: str, extension: str
) -> None:
- directory = Path(get_filename(filename)).parent
- filename = get_download_filename(filename, extension)
+ notebook_path = get_filename(filename)
+ download_name = get_download_filename(filename, extension)
+ export_dir = notebook_output_dir(notebook_path)
- await self._ensure_export_dir_async(directory)
- filepath = directory / self.EXPORT_DIR / filename
+ await self._ensure_export_dir_async(export_dir)
+ filepath = export_dir / download_name
# Run blocking file I/O in thread pool
loop = asyncio.get_event_loop()
@@ -662,17 +661,12 @@ class AutoExporter:
return
filepath.write_text(content, encoding="utf-8")
- async def _ensure_export_dir_async(self, directory: Path) -> None:
+ async def _ensure_export_dir_async(self, export_dir: Path) -> None:
"""Async directory creation with caching to avoid redundant checks"""
- export_dir = directory / self.EXPORT_DIR
-
# Fast path: already created this directory
if export_dir in self._created_dirs:
return
- if not await async_path.exists(directory):
- raise FileNotFoundError(f"Directory {directory} does not exist")
-
await async_path.mkdir(export_dir, parents=True, exist_ok=True)
# Cache that we've created this directory
diff --git a/marimo/_session/state/serialize.py b/marimo/_session/state/serialize.py
index d2c42e35da..13faece967 100644
--- a/marimo/_session/state/serialize.py
+++ b/marimo/_session/state/serialize.py
@@ -360,7 +360,9 @@ def get_session_cache_file(path: Path) -> Path:
For example, if the path is `foo/bar/baz.py`, the cache file is
`foo/bar/__marimo__/session/baz.py.json`.
"""
- return path.parent / "__marimo__" / "session" / f"{path.name}.json"
+ from marimo._utils.paths import notebook_output_dir
+
+ return notebook_output_dir(path) / "session" / f"{path.name}.json"
def _hash_code(code: Optional[str]) -> Optional[str]:
diff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.py
index 136c3f5b20..fd87c1fa49 100644
--- a/marimo/_utils/paths.py
+++ b/marimo/_utils/paths.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import os
+import sys
from pathlib import Path
from typing import TYPE_CHECKING
@@ -51,6 +52,49 @@ def maybe_make_dirs(filepath: Path) -> None:
filepath.parent.mkdir(parents=True, exist_ok=True)
+MARIMO_DIR_NAME = "__marimo__"
+
+
+def notebook_output_dir(notebook_path: Path | str | None) -> Path:
+ """Compute the __marimo__ output directory for a given notebook.
+
+ When ``sys.pycache_prefix`` is set and the notebook path is absolute, the
+ directory tree is mirrored under the prefix (similar to how Python mirrors
+ ``__pycache__`` directories). Otherwise the ``__marimo__`` directory is
+ placed next to the notebook file.
+
+ Resolution order:
+ 1. ``sys.pycache_prefix`` (if set and path is absolute): mirror tree
+ 2. Default: ``<notebook_parent>/__marimo__``
+ 3. Fallback (``None`` path): ``__marimo__`` relative to CWD
+ """
+ if notebook_path is None:
+ return Path(MARIMO_DIR_NAME)
+
+ raw = Path(notebook_path)
+ originally_absolute = raw.is_absolute()
+
+ path = normalize_path(raw)
+ # Determine the notebook's parent directory.
+ if path.is_dir():
+ parent = path
+ elif path.suffix:
+ parent = path.parent
+ else:
+ # Ambiguous (non-existing path without extension): assume directory.
+ # marimo notebooks are expected to have a file extension.
+ parent = path
+
+ prefix = getattr(sys, "pycache_prefix", None)
+ if prefix is not None and originally_absolute:
+ # Strip the filesystem root so we can graft onto the prefix.
+ # On Unix "/" -> parts[1:], on Windows "C:\\" -> parts[1:].
+ relative = Path(*parent.parts[1:]) if len(parent.parts) > 1 else Path()
+ return Path(prefix) / relative / MARIMO_DIR_NAME
+
+ return parent / MARIMO_DIR_NAME
+
+
def normalize_path(path: Path) -> Path:
"""Normalize a path without resolving symlinks.
diff --git a/tests/_metadata/test_opengraph.py b/tests/_metadata/test_opengraph.py
index 1f4e490447..e861617745 100644
--- a/tests/_metadata/test_opengraph.py
+++ b/tests/_metadata/test_opengraph.py
@@ -1,16 +1,21 @@
from __future__ import annotations
import textwrap
+from typing import TYPE_CHECKING
from marimo._metadata.opengraph import (
DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR,
OpenGraphConfig,
default_opengraph_image,
+ default_opengraph_image_abs,
read_opengraph_from_file,
read_opengraph_from_pyproject,
resolve_opengraph_metadata,
)
+if TYPE_CHECKING:
+ import pytest
+
def test_read_opengraph_from_pyproject() -> None:
pyproject = {
@@ -101,13 +106,12 @@ def test_resolve_opengraph_metadata_defaults_image_if_present(
path = tmp_path / "notebook.py"
path.write_text(script, encoding="utf-8")
- default_image = default_opengraph_image(str(path))
- image_path = tmp_path / default_image
- image_path.parent.mkdir(parents=True, exist_ok=True)
- image_path.write_bytes(b"fake-png")
+ image_abs = default_opengraph_image_abs(str(path))
+ image_abs.parent.mkdir(parents=True, exist_ok=True)
+ image_abs.write_bytes(b"fake-png")
resolved = resolve_opengraph_metadata(str(path))
- assert resolved.image == default_image
+ assert resolved.image == default_opengraph_image(str(path))
def test_resolve_opengraph_metadata_supports_https_url_image(tmp_path) -> None:
@@ -128,6 +132,44 @@ def test_resolve_opengraph_metadata_supports_https_url_image(tmp_path) -> None:
assert resolved.image == "https://example.com/opengraph.png"
+def test_default_opengraph_image_abs_follows_pycache_prefix(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ prefix = tmp_path / "prefix"
+ monkeypatch.setattr("sys.pycache_prefix", str(prefix))
+
+ notebook = tmp_path / "project" / "notebook.py"
+ notebook.parent.mkdir(parents=True)
+ notebook.touch()
+
+ abs_path = default_opengraph_image_abs(str(notebook))
+ # Should be under the prefix, not next to the notebook.
+ assert str(abs_path).startswith(str(prefix))
+ assert abs_path.name == "opengraph.png"
+ assert "notebook" in abs_path.parts # stem used as subdirectory
+
+
+def test_default_image_exists_with_pycache_prefix(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """_default_image_exists finds images under the relocated __marimo__ dir."""
+ prefix = tmp_path / "prefix"
+ monkeypatch.setattr("sys.pycache_prefix", str(prefix))
+
+ notebook = tmp_path / "project" / "notebook.py"
+ notebook.parent.mkdir(parents=True)
+ notebook.touch()
+
+ # Image at the relocated path.
+ image = default_opengraph_image_abs(str(notebook))
+ image.parent.mkdir(parents=True)
+ image.write_bytes(b"fake-png")
+
+ from marimo._metadata.opengraph import _default_image_exists
+
+ assert _default_image_exists(str(notebook))
+
+
def test_default_opengraph_placeholder_generator() -> None:
image = DEFAULT_OPENGRAPH_PLACEHOLDER_IMAGE_GENERATOR("Hello World")
assert image.media_type == "image/svg+xml"
diff --git a/tests/_save/stores/test_file.py b/tests/_save/stores/test_file.py
index 4025a0b544..9427b26074 100644
--- a/tests/_save/stores/test_file.py
+++ b/tests/_save/stores/test_file.py
@@ -42,3 +42,12 @@ class TestFileStore:
# Clear non-existent key
result = store.clear("nonexistent")
assert result is False
+
+ def test_default_path_is_lazy(self) -> None:
+ """Default save_path is not resolved at construction time."""
+ store = FileStore()
+ # The backing attribute should be None until first access.
+ assert store._resolved_save_path is None
+ # Accessing the property triggers resolution.
+ _ = store.save_path
+ assert store._resolved_save_path is not None
diff --git a/tests/_session/state/test_serialize_session.py b/tests/_session/state/test_serialize_session.py
index 3d81128625..e367e3cdd9 100644
--- a/tests/_session/state/test_serialize_session.py
+++ b/tests/_session/state/test_serialize_session.py
@@ -582,6 +582,24 @@ def test_get_session_cache_file():
)
+def test_get_session_cache_file_with_pycache_prefix(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ prefix = tmp_path / "prefix"
+ monkeypatch.setattr("sys.pycache_prefix", str(prefix))
+
+ path = tmp_path / "app" / "notebooks" / "notebook.py"
+ cache_file = get_session_cache_file(path)
+ relative_parent = Path(*path.parent.parts[1:]) # strip root
+ assert cache_file == (
+ prefix
+ / relative_parent
+ / "__marimo__"
+ / "session"
+ / "notebook.py.json"
+ )
+
+
def test_hash_code():
"""Test _hash_code function"""
assert _hash_code(None) is None
diff --git a/tests/_utils/test_paths.py b/tests/_utils/test_paths.py
index b49b37b2ca..4eab768693 100644
--- a/tests/_utils/test_paths.py
+++ b/tests/_utils/test_paths.py
@@ -7,7 +7,11 @@ from pathlib import Path
import pytest
-from marimo._utils.paths import normalize_path, pretty_path
+from marimo._utils.paths import (
+ normalize_path,
+ notebook_output_dir,
+ pretty_path,
+)
def test_normalize_path_makes_absolute() -> None:
@@ -114,6 +118,76 @@ def test_normalize_path_does_not_skip_regular_paths() -> None:
assert result.__class__.__module__.startswith("pathlib")
+class TestGetMarimoDir:
+ """Tests for notebook_output_dir function."""
+
+ def test_none_returns_cwd_relative(self) -> None:
+ assert notebook_output_dir(None) == Path("__marimo__")
+
+ def test_file_path_returns_sibling_dir(self, tmp_path: Path) -> None:
+ notebook = tmp_path / "notebook.py"
+ notebook.touch()
+ result = notebook_output_dir(str(notebook))
+ assert result == tmp_path / "__marimo__"
+
+ def test_directory_path(self, tmp_path: Path) -> None:
+ result = notebook_output_dir(tmp_path)
+ assert result == tmp_path / "__marimo__"
+
+ def test_pycache_prefix_mirrors_tree(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ prefix = tmp_path / "prefix"
+ monkeypatch.setattr("sys.pycache_prefix", str(prefix))
+
+ notebook = tmp_path / "app" / "notebooks" / "example" / "foo.py"
+ result = notebook_output_dir(str(notebook))
+ # The notebook's absolute parent tree is mirrored under the prefix.
+ relative_parent = Path(
+ *notebook.parent.parts[1:]
+ ) # strip root (/ or C:\)
+ assert result == prefix / relative_parent / "__marimo__"
+
+ def test_pycache_prefix_not_applied_when_none(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr("sys.pycache_prefix", None)
+ notebook = tmp_path / "app" / "notebooks" / "foo.py"
+ result = notebook_output_dir(str(notebook))
+ assert result == notebook.parent / "__marimo__"
+
+ def test_pycache_prefix_ignored_for_none_path(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr("sys.pycache_prefix", str(tmp_path / "prefix"))
+ assert notebook_output_dir(None) == Path("__marimo__")
+
+ def test_pycache_prefix_ignored_for_relative_path(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Relative paths stay notebook-relative, not relocated under prefix."""
+ monkeypatch.setattr("sys.pycache_prefix", str(tmp_path / "prefix"))
+ result = notebook_output_dir("notebook.py")
+ # Should resolve relative to CWD, not under the prefix.
+ assert (
+ result == normalize_path(Path("notebook.py")).parent / "__marimo__"
+ )
+ assert str(tmp_path / "prefix") not in str(result)
+
+ def test_pycache_prefix_mkdir_creates_full_tree(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Mirrored prefix paths can be created with mkdir(parents=True)."""
+ prefix = tmp_path / "prefix"
+ monkeypatch.setattr("sys.pycache_prefix", str(prefix))
+
+ notebook = tmp_path / "project" / "notebook.py"
+ marimo_dir = notebook_output_dir(str(notebook))
+ # The full tree doesn't exist yet — mkdir should still work.
+ marimo_dir.mkdir(parents=True, exist_ok=True)
+ assert marimo_dir.is_dir()
+
+
class TestPrettyPath:
"""Tests for pretty_path function."""