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
feat: add [tool.marimo.venv].path to specify a specific venv (#7821)
Dylan Madisetti338080376ae3
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.pyindex fda2b21011..3acbcfcf29 100644--- a/marimo/_cli/sandbox.py+++ b/marimo/_cli/sandbox.py@@ -42,6 +42,7 @@ class SandboxMode(Enum):LOGGER = _loggers.marimo_logger()+DepFeatures = Literal["lsp", "recommended"]@@ -403,10 +404,6 @@ def run_in_sandbox(return process.wait()-# Dependencies required for IPC kernel communication (ZeroMQ-based)-IPC_KERNEL_DEPS: list[str] = ["pyzmq"]--def get_sandbox_requirements(filename: str | None,additional_deps: list[str] | None = None,@@ -415,7 +412,7 @@ def get_sandbox_requirements(Reads dependencies from the notebook's PEP 723 script metadata,normalizes marimo dependency, and adds any additional deps- (e.g., IPC_KERNEL_DEPS for kernel communication).+ (e.g., get_ipc_kernel_deps() for kernel communication).Args:filename: Path to notebook file, or None for empty deps.@@ -460,7 +457,7 @@ def build_sandbox_venv(Args:filename: Path to notebook file for reading dependencies.- additional_deps: Extra dependencies to add (e.g., IPC_KERNEL_DEPS).+ additional_deps: Extra dependencies to add (e.g., get_ipc_kernel_deps()).Returns:Tuple of (sandbox_dir, venv_python_path).diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex 7d5692dd3c..b85804a804 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -97,6 +97,26 @@ OnCellChangeType = Literal["lazy", "autorun"]ExecutionType = Literal["relaxed", "strict"]+@mddoc+@dataclass+class VenvConfig(TypedDict, total=False):+ """Configuration for external Python environment in home sandbox mode.++ Allows specifying an existing virtualenv to use instead of creating+ ephemeral sandboxes per notebook. Only applies in home sandbox mode.++ **Keys.**++ - `path`: path to a virtualenv directory (absolute or relative to+ pyproject.toml)+ - `writable`: if true, marimo will manage script metadata (inline+ dependencies). Defaults to false.+ """++ path: str+ writable: bool++# TODO(akshayka): remove normal, migrate to compact# normal == compactWidthType = Literal["normal", "compact", "medium", "full", "columns"]@@ -555,6 +575,7 @@ class MarimoConfig(TypedDict):datasources: NotRequired[DatasourcesConfig]sharing: NotRequired[SharingConfig]mcp: NotRequired[MCPConfig]+ venv: NotRequired[VenvConfig]@mddoc@@ -622,6 +643,7 @@ class PartialMarimoConfig(TypedDict, total=False):snippets: SnippetsConfigdatasources: NotRequired[DatasourcesConfig]sharing: NotRequired[SharingConfig]+ venv: NotRequired[VenvConfig]DEFAULT_CONFIG: MarimoConfig = {diff --git a/marimo/_session/_venv.py b/marimo/_session/_venv.pynew file mode 100644index 0000000000..6a00b8641c--- /dev/null+++ b/marimo/_session/_venv.py@@ -0,0 +1,224 @@+# Copyright 2026 Marimo. All rights reserved.+"""Virtual environment configuration utilities.++This module provides utilities for working with configured virtual environments+in marimo's sandbox mode. It handles:+- Finding Python interpreters in virtual environments+- Checking marimo installation status in venvs+- PYTHONPATH injection for kernel subprocesses+- Installing marimo into configured venvs+"""++from __future__ import annotations++import os+import subprocess+import sys+from importlib.metadata import version+from pathlib import Path+from typing import TYPE_CHECKING++from marimo import _loggers+from marimo._cli.print import echo+from marimo._utils.uv import find_uv_bin+from marimo._version import __version__++if TYPE_CHECKING:+ from marimo._config.config import VenvConfig++LOGGER = _loggers.marimo_logger()+++def get_ipc_kernel_deps() -> list[str]:+ """Get dependencies required for IPC kernel communication.++ Returns pyzmq pinned to the currently installed version to ensure+ compatibility between host and sandbox environments.+ """+ try:+ pyzmq_version = version("pyzmq")+ return [f"pyzmq=={pyzmq_version}"]+ except Exception:+ # Fallback if pyzmq not installed+ return ["pyzmq>=27.1.0"]+++def _find_python_in_venv(venv_path: str) -> str | None:+ """Find Python interpreter in a venv directory.++ Args:+ venv_path: Path to the virtualenv directory.++ Returns:+ Path to Python binary, or None if not found.+ """+ venv = Path(venv_path)+ if not venv.exists() or not venv.is_dir():+ return None++ if sys.platform == "win32":+ python_path = venv / "Scripts" / "python.exe"+ else:+ python_path = venv / "bin" / "python"++ if not python_path.exists():+ return None++ return str(python_path.absolute())+++def get_configured_venv_python(+ venv_config: VenvConfig,+ base_path: str | None = None,+) -> str | None:+ """Get Python path from venv config.++ Args:+ venv_config: The venv config dict (from config.get("venv")).+ base_path: Base path for resolving relative venv paths (e.g., script path).++ Returns:+ Path to Python interpreter in configured venv, or None if not configured.++ Raises:+ ValueError: If venv is configured but invalid.+ """+ venv_path = venv_config.get("path")++ if not venv_path:+ return None++ if base_path and not os.path.isabs(venv_path):+ base_dir = os.path.dirname(os.path.abspath(base_path))+ venv_path = os.path.join(base_dir, venv_path)++ if not os.path.isdir(venv_path):+ raise ValueError(f"Configured venv does not exist: {venv_path}")++ python_path = _find_python_in_venv(venv_path)+ if not python_path:+ raise ValueError(+ f"No Python interpreter found in configured venv: {venv_path}"+ )++ return python_path+++def get_kernel_pythonpath() -> str:+ """Get PYTHONPATH for kernel subprocess.++ Returns paths needed to import marimo and its dependencies (pyzmq, msgspec)+ from the parent process's environment. Used when launching a kernel+ in a configured venv that has marimo available via path injection.++ Returns:+ Colon-separated (or semicolon on Windows) path string for PYTHONPATH.+ """+ paths: list[str] = []++ # Find actual paths where dependencies are installed by checking their __file__+ # This is more reliable than site.getsitepackages() which may return+ # ephemeral paths e.g. when running via `uv run --with=pyzmq`.+ # We also include msgspec as a reliable dependency that _should_ be in the+ # desired user system path.+ # Also add marimo's parent directory.+ # NB. If running in edit mode this may be local directory.+ for module_name in ["marimo", "zmq", "msgspec"]:+ try:+ module = __import__(module_name)+ if hasattr(module, "__file__") and module.__file__:+ # Get the site-packages directory containing this module+ module_path = Path(module.__file__).parent.parent+ module_path_str = str(module_path)+ if module_path_str not in paths:+ paths.append(module_path_str)+ except ImportError:+ pass++ return os.pathsep.join(paths)+++def has_marimo_installed(venv_python: str) -> bool:+ """Check if marimo and its IPC deps are installed in the venv.++ Args:+ venv_python: Path to the venv's Python interpreter.++ Returns:+ True if marimo, msgspec, and zmq can all be imported.+ """+ result = subprocess.run(+ [+ venv_python,+ "-c",+ "import marimo, msgspec, zmq; print(marimo.__version__)",+ ],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ return False++ venv_version = result.stdout.strip()+ if venv_version != __version__:+ LOGGER.warning(+ f"marimo version mismatch: venv has {venv_version}, "+ f"current is {__version__}. "+ f"This may cause unexpected behavior. "+ f"Consider upgrading both environments to the same version: "+ f"uv pip install --upgrade marimo"+ )++ return True+++def check_python_version_compatibility(venv_python: str) -> bool:+ """Check if venv Python version matches current Python.++ Binary dependencies (pyzmq, msgspec) aren't cross-version compatible,+ so the venv must use the same Python major.minor version.++ Args:+ venv_python: Path to the venv's Python interpreter.++ Returns:+ True if versions match, False otherwise.+ """+ result = subprocess.run(+ [+ venv_python,+ "-c",+ "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')",+ ],+ capture_output=True,+ text=True,+ )+ venv_version = result.stdout.strip()+ current_version = f"{sys.version_info.major}.{sys.version_info.minor}"++ return venv_version == current_version+++def install_marimo_into_venv(venv_python: str) -> None:+ """Install marimo and IPC dependencies into a venv.++ Installs marimo and IPC dependencies (pyzmq) into the specified venv.++ Args:+ venv_python: Path to the venv's Python interpreter.+ """+ uv_bin = find_uv_bin()++ packages = [f"marimo=={__version__}"] + get_ipc_kernel_deps()++ echo("Installing marimo into configured venv...", err=True)++ result = subprocess.run(+ [uv_bin, "pip", "install", "--python", venv_python] + packages,+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ LOGGER.warning(+ f"Failed to install marimo into configured venv: {result.stderr}"+ )diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.pyindex f4df727800..8c61cd8e88 100644--- a/marimo/_session/managers/ipc.py+++ b/marimo/_session/managers/ipc.py@@ -15,13 +15,22 @@ from typing import TYPE_CHECKING, Optional, Union, castfrom marimo import _loggersfrom marimo._cli.sandbox import (- IPC_KERNEL_DEPS,build_sandbox_venv,cleanup_sandbox_dir,)+from marimo._config.config import VenvConfig+from marimo._config.manager import MarimoConfigReaderfrom marimo._config.settings import GLOBAL_SETTINGSfrom marimo._messaging.types import KernelMessagefrom marimo._runtime import commands+from marimo._session._venv import (+ check_python_version_compatibility,+ get_configured_venv_python,+ get_ipc_kernel_deps,+ get_kernel_pythonpath,+ has_marimo_installed,+ install_marimo_into_venv,+)from marimo._session.model import SessionModefrom marimo._session.queue import ProcessLike, QueueTypefrom marimo._session.types import KernelManager, QueueManager@@ -29,7 +38,6 @@ from marimo._utils.typed_connection import TypedConnectionif TYPE_CHECKING:from marimo._ast.cell import CellConfig- from marimo._config.manager import MarimoConfigReaderfrom marimo._ipc.queue_manager import QueueManager as IPCQueueManagerTypefrom marimo._ipc.types import ConnectionInfofrom marimo._runtime.commands import AppMetadata@@ -38,6 +46,12 @@ if TYPE_CHECKING:LOGGER = _loggers.marimo_logger()+def _get_venv_config(config_manager: MarimoConfigReader) -> VenvConfig:+ """Get the [tool.marimo.venv] config from a config manager."""+ config = config_manager.get_config(hide_secrets=False)+ return cast(VenvConfig, config.get("venv", {}))++class KernelStartupError(Exception):"""Raised when kernel subprocess fails to start."""@@ -150,7 +164,6 @@ class IPCKernelManagerImpl(KernelManager):from marimo._cli.print import echo, mutedfrom marimo._ipc.types import KernelArgs- # Build kernel argskernel_args = KernelArgs(configs=self.configs,app_metadata=self.app_metadata,@@ -162,28 +175,96 @@ class IPCKernelManagerImpl(KernelManager):redirect_console_to_browser=self.redirect_console_to_browser,)- # Build environmentenv = os.environ.copy()- # Build sandbox venv with IPC dependencies+ venv_config = _get_venv_config(self.config_manager)try:- self._sandbox_dir, venv_python = build_sandbox_venv(- self.app_metadata.filename,- additional_deps=IPC_KERNEL_DEPS,+ configured_python = get_configured_venv_python(+ venv_config, base_path=self.app_metadata.filename)- cmd = [venv_python, "-m", "marimo._ipc.launch_kernel"]- except Exception as e:- cleanup_sandbox_dir(self._sandbox_dir)- raise KernelStartupError(- f"Failed to build sandbox environment.\n\n{e}"- ) from e+ except ValueError as e:+ raise KernelStartupError(str(e)) from e++ # Ephemeral sandboxes are always writable; configured venvs respect the+ # flag.+ writable = True++ # An explicitly configured venv takes precedence over an ephemeral+ # sandbox.+ if configured_python:+ echo(+ f"Using configured venv: {muted(configured_python)}",+ err=True,+ )+ venv_python = configured_python- echo(- f"Running kernel in sandbox: {muted(' '.join(cmd))}",- err=True,- )- # Set MARIMO_MANAGE_SCRIPT_METADATA for sandbox- env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"+ writable = venv_config.get("writable", False)++ # Configured environments are assumed to be read-only.+ # If not, then install marimo by default to ensure that the+ # environment can spawn a marimo kernel.+ if writable:+ try:+ install_marimo_into_venv(venv_python)+ except Exception as e:+ raise KernelStartupError(+ f"Failed to install marimo into configured venv.\n\n{e}"+ ) from e+ elif not has_marimo_installed(venv_python):+ # Check Python version compatibility for binary deps+ if not check_python_version_compatibility(venv_python):+ # If we have gotten to this point+ # - We have a prescribed venv+ # - The venv is not writable+ # - The venv does not contain marimo nor zmq+ # As such there is nothing we can do, as we can't get marimo+ # into the runtime without installing it somewhere else.+ raise KernelStartupError(+ f"Configured venv uses a different Python version than marimo.\n"+ f"Binary dependencies (pyzmq, msgspec) aren't cross-version compatible.\n\n"+ f"Options:\n"+ f" 1. Set writable=true in [tool.marimo.venv] to allow marimo to install deps\n"+ f" 2. Install marimo in your venv: uv pip install marimo --python {venv_python}\n"+ f" 3. Remove [tool.marimo.venv].path to use an ephemeral sandbox instead"+ )++ # Inject PYTHONPATH for marimo and dependencies from the+ # current runtime as a last chance effort to expose marimo+ # to the kernel.+ kernel_path = get_kernel_pythonpath()+ existing = env.get("PYTHONPATH", "")+ if existing:+ env["PYTHONPATH"] = f"{kernel_path}{os.pathsep}{existing}"+ else:+ env["PYTHONPATH"] = kernel_path+ else:+ # Fall back to building ephemeral sandbox venv+ # with IPC dependencies.+ # NB. "Ephemeral" sandboxes (or rather tmp sandboxes built by uv)+ # are always writable, and as such install marimo as a default,+ # making them much easier than a configured venv we cannot manage.+ try:+ self._sandbox_dir, venv_python = build_sandbox_venv(+ self.app_metadata.filename,+ additional_deps=get_ipc_kernel_deps(),+ )+ except Exception as e:+ cleanup_sandbox_dir(self._sandbox_dir)+ raise KernelStartupError(+ f"Failed to build sandbox environment.\n\n{e}"+ ) from e++ echo(+ f"Running kernel in sandbox: {muted(venv_python)}",+ err=True,+ )++ cmd = [venv_python, "-m", "marimo._ipc.launch_kernel"]+ if writable:+ # Setting this attempts to make auto-installations work even if+ # other normally detected criteria are not true.+ # IPC by itself does not seem to trigger them.+ env["MARIMO_MANAGE_SCRIPT_METADATA"] = "true"LOGGER.debug(f"Launching kernel: {' '.join(cmd)}")diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yamlindex 267e6468fd..2781a9f4d2 100644--- a/packages/openapi/api.yaml+++ b/packages/openapi/api.yaml@@ -2678,6 +2678,8 @@ components:$ref: '#/components/schemas/SharingConfig'snippets:$ref: '#/components/schemas/SnippetsConfig'+ venv:+ $ref: '#/components/schemas/VenvConfig'required:- completion- display@@ -4364,6 +4366,21 @@ components:- variablestitle: VariablesNotificationtype: object+ VenvConfig:+ description: "Configuration for external Python environment in home sandbox\+ \ mode.\n\n Allows specifying an existing virtualenv to use instead of\+ \ creating\n ephemeral sandboxes per notebook. Only applies in home sandbox\+ \ mode.\n\n **Keys.**\n\n - `path`: path to a virtualenv directory (absolute\+ \ or relative to\n pyproject.toml)\n - `writable`: if true, marimo\+ \ will manage script metadata (inline\n dependencies). Defaults to false."+ properties:+ path:+ type: string+ writable:+ type: boolean+ required: []+ title: VenvConfig+ type: objectWorkspaceFilesRequest:properties:includeMarkdown:diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.tsindex 82c7c58987..f3261a0b21 100644--- a/packages/openapi/src/api.ts+++ b/packages/openapi/src/api.ts@@ -4468,6 +4468,7 @@ export interface components {server: components["schemas"]["ServerConfig"];sharing?: components["schemas"]["SharingConfig"];snippets?: components["schemas"]["SnippetsConfig"];+ venv?: components["schemas"]["VenvConfig"];};/** MarimoExceptionRaisedError */MarimoExceptionRaisedError: {@@ -5429,6 +5430,24 @@ export interface components {op: "variables";variables: components["schemas"]["VariableDeclarationNotification"][];};+ /**+ * VenvConfig+ * @description Configuration for external Python environment in home sandbox mode.+ *+ * Allows specifying an existing virtualenv to use instead of creating+ * ephemeral sandboxes per notebook. Only applies in home sandbox mode.+ *+ * **Keys.**+ *+ * - `path`: path to a virtualenv directory (absolute or relative to+ * pyproject.toml)+ * - `writable`: if true, marimo will manage script metadata (inline+ * dependencies). Defaults to false.+ */+ VenvConfig: {+ path?: string;+ writable?: boolean;+ };/** WorkspaceFilesRequest */WorkspaceFilesRequest: {/** @default false */diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.pyindex b4571cc6e0..86872f58bb 100644--- a/tests/_cli/test_sandbox.py+++ b/tests/_cli/test_sandbox.py@@ -1,19 +1,27 @@from __future__ import annotations+import osfrom typing import TYPE_CHECKING, Anyfrom unittest.mock import patch+if TYPE_CHECKING:+ from pathlib import Path++import pytest+from marimo._cli.sandbox import (SandboxMode,_ensure_marimo_in_script_metadata,_normalize_sandbox_dependencies,+ build_sandbox_venv,+ cleanup_sandbox_dir,construct_uv_command,resolve_sandbox_mode,)+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._utils.inline_script_metadata import PyProjectReader-if TYPE_CHECKING:- from pathlib import Path+HAS_UV = DependencyManager.which("uv")@patch("marimo._cli.sandbox.is_editable", return_value=False)@@ -574,16 +582,6 @@ app = marimo.App()assert script_path.read_text() == original-# Tests for IPC sandbox functions---def test_ipc_kernel_deps_constant() -> None:- """Test IPC_KERNEL_DEPS constant contains expected deps."""- from marimo._cli.sandbox import IPC_KERNEL_DEPS-- assert "pyzmq" in IPC_KERNEL_DEPS--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@@ -671,3 +669,36 @@ def test_cleanup_sandbox_dir_handles_nonexistent(tmp_path: Path) -> None:nonexistent = str(tmp_path / "does_not_exist")cleanup_sandbox_dir(nonexistent) # Should not raise++[email protected](not HAS_UV, reason="uv required")+def test_build_sandbox_venv_creates_venv(tmp_path: Path) -> None:+ """Test venv is created and returns paths."""+ script = tmp_path / "test.py"+ script.write_text("# /// script\n# dependencies = []\n# ///\n")++ sandbox_dir, venv_python = build_sandbox_venv(str(script))+ try:+ assert os.path.isdir(sandbox_dir)+ assert os.path.exists(venv_python)+ assert "python" in venv_python+ finally:+ cleanup_sandbox_dir(sandbox_dir)++[email protected](not HAS_UV, reason="uv required")+def test_build_sandbox_venv_with_additional_deps(tmp_path: Path) -> None:+ """Test additional deps are passed through."""+ from marimo._session._venv import get_ipc_kernel_deps++ script = tmp_path / "test.py"+ script.write_text("# /// script\n# dependencies = []\n# ///\n")++ sandbox_dir, venv_python = build_sandbox_venv(+ str(script), additional_deps=get_ipc_kernel_deps()+ )+ try:+ assert os.path.isdir(sandbox_dir)+ assert os.path.exists(venv_python)+ finally:+ cleanup_sandbox_dir(sandbox_dir)diff --git a/tests/_session/test_venv.py b/tests/_session/test_venv.pynew file mode 100644index 0000000000..f8adf717f6--- /dev/null+++ b/tests/_session/test_venv.py@@ -0,0 +1,292 @@+from __future__ import annotations++import os+import sys+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from pathlib import Path++import pytest++from marimo._session._venv import (+ check_python_version_compatibility,+ get_configured_venv_python,+ get_kernel_pythonpath,+ has_marimo_installed,+)+++def test_get_configured_venv_python_returns_none_when_not_configured() -> None:+ """Test returns None when venv not in config."""+ config: dict[str, Any] = {} # No venv configured+ result = get_configured_venv_python(config)+ assert result is None+++def test_get_configured_venv_python_returns_none_when_venv_empty() -> None:+ """Test returns None when venv is empty string."""+ config: dict[str, Any] = {"path": ""}+ result = get_configured_venv_python(config)+ assert result is None+++def test_get_configured_venv_python_returns_path_when_valid(+ tmp_path: Path,+) -> None:+ """Test returns Python path when venv is valid."""+ # Create a mock venv with Python+ venv_dir = tmp_path / "venv"+ venv_dir.mkdir()+ if sys.platform == "win32":+ bin_dir = venv_dir / "Scripts"+ python_name = "python.exe"+ else:+ bin_dir = venv_dir / "bin"+ python_name = "python"+ bin_dir.mkdir()+ python_path = bin_dir / python_name+ python_path.touch()++ config: dict[str, Any] = {"path": str(venv_dir)}+ result = get_configured_venv_python(config)+ assert result is not None+ assert result.endswith(python_name)+++def test_get_configured_venv_python_raises_on_missing_venv() -> None:+ """Test raises ValueError when configured venv doesn't exist."""+ config: dict[str, Any] = {"path": "/nonexistent/venv/path"}+ with pytest.raises(ValueError, match="does not exist"):+ get_configured_venv_python(config)+++def test_get_configured_venv_python_raises_on_no_python(+ tmp_path: Path,+) -> None:+ """Test raises ValueError when venv has no Python interpreter."""+ venv_dir = tmp_path / "venv"+ venv_dir.mkdir() # Empty venv, no bin/python++ config: dict[str, Any] = {"path": str(venv_dir)}+ with pytest.raises(ValueError, match="No Python interpreter"):+ get_configured_venv_python(config)+++def test_get_configured_venv_python_resolves_relative_path(+ tmp_path: Path,+) -> None:+ """Test that relative venv paths are resolved from base_path."""+ # Create a mock venv with Python+ venv_dir = tmp_path / "venvs" / "myenv"+ venv_dir.mkdir(parents=True)+ if sys.platform == "win32":+ bin_dir = venv_dir / "Scripts"+ python_name = "python.exe"+ else:+ bin_dir = venv_dir / "bin"+ python_name = "python"+ bin_dir.mkdir()+ python_path = bin_dir / python_name+ python_path.touch()++ # Create a script file in tmp_path+ script_path = tmp_path / "notebook.py"+ script_path.touch()++ # Relative path from script location+ config: dict[str, Any] = {"path": "venvs/myenv"}+ result = get_configured_venv_python(config, base_path=str(script_path))+ assert result is not None+ assert result.endswith(python_name)+++def test_get_kernel_pythonpath_includes_marimo_dir() -> None:+ """Test that kernel PYTHONPATH includes marimo's parent directory."""+ import marimo++ pythonpath = get_kernel_pythonpath()+ paths = pythonpath.split(os.pathsep)++ marimo_dir = os.path.dirname(os.path.dirname(marimo.__file__))+ assert marimo_dir in paths, f"marimo dir {marimo_dir} not in {paths}"+++def test_get_kernel_pythonpath_detects_module_via_import(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test that module detection works by importing and checking __file__."""+ from types import ModuleType++ fake_zmq = ModuleType("zmq")+ fake_zmq.__file__ = "/fake/site-packages/zmq/__init__.py"+ monkeypatch.setitem(sys.modules, "zmq", fake_zmq)++ pythonpath = get_kernel_pythonpath()+ paths = pythonpath.split(os.pathsep)++ assert os.path.normpath("/fake/site-packages") in paths+++def test_get_kernel_pythonpath_skips_module_without_file(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test that modules without __file__ are skipped gracefully."""+ from types import ModuleType++ fake_zmq = ModuleType("zmq")+ # Don't set __file__ - simulates built-in or namespace package+ monkeypatch.setitem(sys.modules, "zmq", fake_zmq)++ pythonpath = get_kernel_pythonpath()+ assert pythonpath # Should still have marimo dir at minimum+++def test_get_kernel_pythonpath_handles_import_error(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test that ImportError is handled gracefully."""+ import marimo++ monkeypatch.delitem(sys.modules, "zmq", raising=False)+ monkeypatch.delitem(sys.modules, "msgspec", raising=False)++ original_import = __builtins__["__import__"] # type: ignore[index]++ def fake_import(name: str, *args: Any, **kwargs: Any) -> Any:+ if name in ("zmq", "msgspec"):+ raise ImportError(f"No module named '{name}'")+ return original_import(name, *args, **kwargs)++ monkeypatch.setattr("builtins.__import__", fake_import)++ pythonpath = get_kernel_pythonpath()+ paths = pythonpath.split(os.pathsep)++ marimo_dir = os.path.dirname(os.path.dirname(marimo.__file__))+ assert marimo_dir in paths+++def test_get_kernel_pythonpath_deduplicates(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test that duplicate paths are deduplicated."""+ from types import ModuleType++ fake_zmq = ModuleType("zmq")+ fake_zmq.__file__ = "/shared/site-packages/zmq/__init__.py"+ fake_msgspec = ModuleType("msgspec")+ fake_msgspec.__file__ = "/shared/site-packages/msgspec/__init__.py"++ monkeypatch.setitem(sys.modules, "zmq", fake_zmq)+ monkeypatch.setitem(sys.modules, "msgspec", fake_msgspec)++ pythonpath = get_kernel_pythonpath()+ paths = pythonpath.split(os.pathsep)++ assert paths.count(os.path.normpath("/shared/site-packages")) == 1+++def test_has_marimo_installed_returns_true_when_imports_succeed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test returns True when marimo and deps can be imported."""+ import subprocess++ from marimo._version import __version__++ def mock_run(+ *args: Any, **_kwargs: Any+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(+ args=args[0],+ returncode=0,+ stdout=f"{__version__}\n",+ stderr="",+ )++ monkeypatch.setattr(subprocess, "run", mock_run)+ assert has_marimo_installed("/fake/python") is True+++def test_has_marimo_installed_returns_false_when_import_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test returns False when imports fail."""+ import subprocess++ def mock_run(+ *args: Any, **_kwargs: Any+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(+ args=args[0],+ returncode=1,+ stdout="",+ stderr="ModuleNotFoundError: No module named 'marimo'",+ )++ monkeypatch.setattr(subprocess, "run", mock_run)+ assert has_marimo_installed("/fake/python") is False+++def test_has_marimo_installed_returns_true_on_version_mismatch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test returns True even when venv has different marimo version."""+ import subprocess++ def mock_run(+ *args: Any, **_kwargs: Any+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(+ args=args[0],+ returncode=0,+ stdout="0.0.1\n", # Different version+ stderr="",+ )++ monkeypatch.setattr(subprocess, "run", mock_run)+ # Should return True even with version mismatch (warning is logged)+ assert has_marimo_installed("/fake/python") is True+++def test_check_python_version_compatibility_returns_true_when_match(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test returns True when Python versions match."""+ import subprocess++ current_version = f"{sys.version_info.major}.{sys.version_info.minor}"++ def mock_run(+ *args: Any, **_kwargs: Any+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(+ args=args[0],+ returncode=0,+ stdout=f"{current_version}\n",+ stderr="",+ )++ monkeypatch.setattr(subprocess, "run", mock_run)+ assert check_python_version_compatibility("/fake/python") is True+++def test_check_python_version_compatibility_returns_false_when_mismatch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Test returns False when Python versions differ."""+ import subprocess++ def mock_run(+ *args: Any, **_kwargs: Any+ ) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(+ args=args[0],+ returncode=0,+ stdout="2.7\n", # Different version+ stderr="",+ )++ monkeypatch.setattr(subprocess, "run", mock_run)+ assert check_python_version_compatibility("/fake/python") is False