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: detect if in uv project and use 'uv add' (#5044)
Myles Scolnick9bc351cafffc
diff --git a/marimo/_runtime/packages/pypi_package_manager.py b/marimo/_runtime/packages/pypi_package_manager.pyindex 7215dca5c5..c8aeb469db 100644--- a/marimo/_runtime/packages/pypi_package_manager.py+++ b/marimo/_runtime/packages/pypi_package_manager.py@@ -6,8 +6,11 @@ import osimport subprocessimport sysimport tempfile+from functools import cached_property+from pathlib import Pathfrom typing import Optional+from marimo import _loggersfrom marimo._runtime.packages.module_name_to_pypi_name import (module_name_to_pypi_name,)@@ -20,6 +23,8 @@ from marimo._utils.platform import is_pyodidePY_EXE = sys.executable+LOGGER = _loggers.marimo_logger()+class PypiPackageManager(CanonicalizingPackageManager):def _construct_module_name_mapping(self) -> dict[str, str]:@@ -48,11 +53,13 @@ class PipPackageManager(PypiPackageManager):docs_url = "https://pip.pypa.io/"async def _install(self, package: str) -> bool:+ LOGGER.info(f"Installing {package} with pip")return self.run(["pip", "--python", PY_EXE, "install", *split_packages(package)])async def uninstall(self, package: str) -> bool:+ LOGGER.info(f"Uninstalling {package} with pip")return self.run(["pip",@@ -119,17 +126,17 @@ class UvPackageManager(PypiPackageManager):docs_url = "https://docs.astral.sh/uv/"async def _install(self, package: str) -> bool:+ install_cmd: list[str]+ if self.is_in_uv_project:+ LOGGER.info(f"Installing in {package} with 'uv add'")+ install_cmd = ["uv", "add"]+ else:+ LOGGER.info(f"Installing in {package} with 'uv pip install'")+ install_cmd = ["uv", "pip", "install"]+return self.run(- [- "uv",- "pip",- "install",- # trade installation time for faster start time- "--compile",- *split_packages(package),- "-p",- PY_EXE,- ]+ # trade installation time for faster start time+ install_cmd + ["--compile", *split_packages(package), "-p", PY_EXE])def update_notebook_script_metadata(@@ -150,6 +157,7 @@ class UvPackageManager(PypiPackageManager):import_namespaces_to_add: List of import namespaces to addimport_namespaces_to_remove: List of import namespaces to remove"""+ LOGGER.info(f"Updating script metadata for {filepath}")packages_to_add = packages_to_add or []packages_to_remove = packages_to_remove or []import_namespaces_to_add = import_namespaces_to_add or []@@ -193,7 +201,7 @@ class UvPackageManager(PypiPackageManager):return self._process_md_changes(filepath, packages_to_add, packages_to_remove)- return self._process_changes(+ return self._process_changes_for_script_metadata(filepath, packages_to_add, packages_to_remove)@@ -228,7 +236,7 @@ class UvPackageManager(PypiPackageManager):temp_file.write(header)temp_file.flush()# Have UV modify it- self._process_changes(+ self._process_changes_for_script_metadata(temp_file.name,packages_to_add,packages_to_remove,@@ -257,7 +265,7 @@ class UvPackageManager(PypiPackageManager):with open(filepath, "w", encoding="utf-8") as f:f.write("\n".join(document))- def _process_changes(+ def _process_changes_for_script_metadata(self,filepath: str,packages_to_add: list[str],@@ -278,12 +286,54 @@ class UvPackageManager(PypiPackageManager):packages = self.list_packages()return {pkg.name: pkg.version for pkg in packages}+ # Only needs to run once per session+ @cached_property+ def is_in_uv_project(self) -> bool:+ """Determine if we are currently running marimo from a uv project++ A [uv project](https://docs.astral.sh/uv/concepts/projects/layout/) contains a+ pyproject.toml and a uv.lock file.++ We can determine if we are in a uv project AND using this project's virtual environment+ by checking:+ - The "UV" environment variable is set+ - The "VIRTUAL_ENV" environment variable is set+ - The "uv.lock" file exists where the "VIRTUAL_ENV" is+ - The "pyproject.toml" file exists where the "VIRTUAL_ENV" is++ If at least one of these conditions are not met,+ we are in a temporary virtual environment (e.g. `uvx marimo edit` or `uv --with=marimo run marimo edit`)+ or in the currently activated virtual environment (e.g. `uv venv`).+ """+ # Check we have a virtual environment+ venv_path = os.environ.get("VIRTUAL_ENV", None)+ if not venv_path:+ return False+ # Check that the `UV` environment variable is set+ # This tells us that marimo was run by uv+ uv_env_exists = os.environ.get("UV", None)+ if not uv_env_exists:+ return False+ # Check that the uv.lock and pyproject.toml files exist+ uv_lock_path = Path(venv_path).parent / "uv.lock"+ pyproject_path = Path(venv_path).parent / "pyproject.toml"+ return uv_lock_path.exists() and pyproject_path.exists()+async def uninstall(self, package: str) -> bool:+ uninstall_cmd: list[str]+ if self.is_in_uv_project:+ LOGGER.info(f"Uninstalling {package} with 'uv remove'")+ uninstall_cmd = ["uv", "remove"]+ else:+ LOGGER.info(f"Uninstalling {package} with 'uv pip uninstall'")+ uninstall_cmd = ["uv", "pip", "uninstall"]+return self.run(- ["uv", "pip", "uninstall", *split_packages(package), "-p", PY_EXE]+ uninstall_cmd + [*split_packages(package), "-p", PY_EXE])def list_packages(self) -> list[PackageDescription]:+ LOGGER.info("Listing packages with 'uv pip list'")cmd = ["uv", "pip", "list", "--format=json", "-p", PY_EXE]return self._list_packages_from_cmd(cmd)diff --git a/marimo/_smoke_tests/packages/is_in_uv.py b/marimo/_smoke_tests/packages/is_in_uv.pynew file mode 100644index 0000000000..15d28de7f1--- /dev/null+++ b/marimo/_smoke_tests/packages/is_in_uv.py@@ -0,0 +1,32 @@+import marimo++__generated_with = "0.13.11"+app = marimo.App(width="medium")+++def _():+ import os+ from pathlib import Path++ # Check we have a virtual environment+ venv_path = os.environ.get("VIRTUAL_ENV", None)+ # Check that the `UV` environment variable is set+ # This tells us that marimo was run by uv+ uv_env_exists = os.environ.get("UV", None)+ # Check that the uv.lock and pyproject.toml files exist+ uv_lock_path = Path(venv_path).parent / "uv.lock"+ pyproject_path = Path(venv_path).parent / "pyproject.toml"++ # If all these are True or defined, then we are running in a uv project+ {+ "venv_path": venv_path,+ "uv_env_exists": uv_env_exists,+ "uv_lock_path": uv_lock_path.exists(),+ "pyproject_path": pyproject_path.exists(),+ }+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/packages/test_pypi_package_manager.py b/tests/_runtime/packages/test_pypi_package_manager.pyindex 62730bb813..d7cc996b32 100644--- a/tests/_runtime/packages/test_pypi_package_manager.py+++ b/tests/_runtime/packages/test_pypi_package_manager.py@@ -9,6 +9,7 @@ from marimo._ast import compilerfrom marimo._runtime.packages.pypi_package_manager import (PackageDescription,PipPackageManager,+ UvPackageManager,)parse_cell = partial(compiler.compile_cell, cell_id="0")@@ -109,3 +110,176 @@ def test_list_packages_failure(mock_run: MagicMock):packages = manager.list_packages()assert len(packages) == 0+++# UV Package Manager Tests++[email protected]("os.environ", {}, clear=True)+def test_uv_is_in_uv_project_no_venv():+ """Test is_in_uv_project returns False when no VIRTUAL_ENV is set"""+ mgr = UvPackageManager()+ assert mgr.is_in_uv_project is False++[email protected]("os.environ", {"VIRTUAL_ENV": "/path/to/venv"}, clear=True)+def test_uv_is_in_uv_project_no_uv_env():+ """Test is_in_uv_project returns False when UV env var is not set"""+ mgr = UvPackageManager()+ assert mgr.is_in_uv_project is False+++ "os.environ",+ {"VIRTUAL_ENV": "/path/to/venv", "UV": "/other/path"},+ clear=True,+)+def test_uv_is_in_uv_project_uv_env_mismatch():+ """Test is_in_uv_project returns False when UV env var doesn't match VIRTUAL_ENV"""+ mgr = UvPackageManager()+ assert mgr.is_in_uv_project is False+++ "os.environ",+ {"VIRTUAL_ENV": "/path/to/venv", "UV": "/path/to/venv"},+ clear=True,+)+@patch("pathlib.Path.exists")+def test_uv_is_in_uv_project_missing_files(mock_exists: MagicMock):+ """Test is_in_uv_project returns False when uv.lock or pyproject.toml don't exist"""+ mock_exists.return_value = False+ mgr = UvPackageManager()+ assert mgr.is_in_uv_project is False+++ "os.environ",+ {"VIRTUAL_ENV": "/path/to/venv", "UV": "/path/to/venv"},+ clear=True,+)+@patch("pathlib.Path.exists")+def test_uv_is_in_uv_project_true(mock_exists: MagicMock):+ """Test is_in_uv_project returns True when all conditions are met"""+ mock_exists.return_value = True+ mgr = UvPackageManager()+ assert mgr.is_in_uv_project is True+++ "os.environ",+ {"VIRTUAL_ENV": "/path/to/venv", "UV": "/path/to/venv"},+ clear=True,+)+@patch("pathlib.Path.exists")+def test_uv_is_in_uv_project_cached(mock_exists: MagicMock):+ """Test is_in_uv_project is cached and only evaluates once"""+ mock_exists.return_value = True+ mgr = UvPackageManager()++ # Access the property multiple times+ result1 = mgr.is_in_uv_project+ result2 = mgr.is_in_uv_project+ result3 = mgr.is_in_uv_project++ # Should all return the same value+ assert result1 is True+ assert result2 is True+ assert result3 is True++ # Path.exists should only be called twice (once for uv.lock, once for pyproject.toml)+ # since the property is cached after the first access+ assert mock_exists.call_count == 2+++@patch("subprocess.run")[email protected](UvPackageManager, "is_in_uv_project", False)+async def test_uv_install_not_in_project(mock_run: MagicMock):+ """Test UV install uses pip subcommand when not in UV project"""+ mock_run.return_value = MagicMock(returncode=0)+ mgr = UvPackageManager()++ result = await mgr._install("package1 package2")++ mock_run.assert_called_once_with(+ [+ "uv",+ "pip",+ "install",+ "--compile",+ "package1",+ "package2",+ "-p",+ PY_EXE,+ ],+ )+ assert result is True+++@patch("subprocess.run")[email protected](UvPackageManager, "is_in_uv_project", True)+async def test_uv_install_in_project(mock_run: MagicMock):+ """Test UV install uses add subcommand when in UV project"""+ mock_run.return_value = MagicMock(returncode=0)+ mgr = UvPackageManager()++ result = await mgr._install("package1 package2")++ mock_run.assert_called_once_with(+ ["uv", "add", "--compile", "package1", "package2", "-p", PY_EXE],+ )+ assert result is True+++@patch("subprocess.run")[email protected](UvPackageManager, "is_in_uv_project", False)+async def test_uv_uninstall_not_in_project(mock_run: MagicMock):+ """Test UV uninstall uses pip subcommand when not in UV project"""+ mock_run.return_value = MagicMock(returncode=0)+ mgr = UvPackageManager()++ result = await mgr.uninstall("package1 package2")++ mock_run.assert_called_once_with(+ ["uv", "pip", "uninstall", "package1", "package2", "-p", PY_EXE],+ )+ assert result is True+++@patch("subprocess.run")[email protected](UvPackageManager, "is_in_uv_project", True)+async def test_uv_uninstall_in_project(mock_run: MagicMock):+ """Test UV uninstall uses remove subcommand when in UV project"""+ mock_run.return_value = MagicMock(returncode=0)+ mgr = UvPackageManager()++ result = await mgr.uninstall("package1 package2")++ mock_run.assert_called_once_with(+ ["uv", "remove", "package1", "package2", "-p", PY_EXE],+ )+ assert result is True+++@patch("subprocess.run")+def test_uv_list_packages(mock_run: MagicMock):+ """Test UV list packages uses pip list subcommand"""+ mock_output = json.dumps(+ [+ {"name": "package1", "version": "1.0.0"},+ {"name": "package2", "version": "2.1.0"},+ ]+ )+ mock_run.return_value = MagicMock(returncode=0, stdout=mock_output)+ mgr = UvPackageManager()++ packages = mgr.list_packages()++ mock_run.assert_called_once_with(+ ["uv", "pip", "list", "--format=json", "-p", PY_EXE],+ capture_output=True,+ text=True,+ )+ assert len(packages) == 2+ assert packages[0] == PackageDescription(name="package1", version="1.0.0")+ assert packages[1] == PackageDescription(name="package2", version="2.1.0")