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: mock micropip when not running under pyodide (#907)
Akshay Agrawal5de3462b5dd8
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.pyindex 2bf07a3614..cd6f12fc3c 100644--- a/marimo/_runtime/patches.py+++ b/marimo/_runtime/patches.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport contextlibimport functoolsimport sys+import textwrapimport typesfrom typing import Any, Callable, Iterator@@ -22,10 +23,92 @@ def patch_sys_module(module: types.ModuleType) -> None:sys.modules[module.__name__] = module+def patch_micropip(glbls: dict[Any, Any]) -> None:+ """Mock micropip with no-ops"""++ definitions = textwrap.dedent(+ """\+from importlib.abc import Loader, MetaPathFinder++class _MicropipFinder(MetaPathFinder):+++ def find_spec(self, fullname, path, target=None):+ from importlib.util import spec_from_loader++ if fullname == 'micropip':+ return spec_from_loader(fullname, _MicropipLoader())+ return None+++class _MicropipLoader(Loader):+ def create_module(self, spec):+ del spec+ # use default spec creation+ return None++ def exec_module(self, module):+ import textwrap++ code = textwrap.dedent(+'''\+def _warn_uninstalled(prefix=""):+ import sys+ sys.stderr.write(prefix + 'micropip is only available in WASM notebooks.')++async def install(+ requirements, keep_going=False, deps=True,+ credentials=None, pre=False, index_urls=None, *,+ verbose=False+):+ _warn_uninstalled(prefix=f'{requirements} was not installed: ')++def list():+ _warn_uninstalled()++def freeze():+ _warn_uninstalled()++def add_mock_package(name, version, *, modules=None, persistent=False):+ _warn_uninstalled()++def list_mock_packages():+ _warn_uninstalled()++def remove_mock_package(name):+ _warn_uninstalled()++def uninstall(packages, *, verbose=False):+ _warn_uninstalled()++def set_index_urls(urls):+ _warn_uninstalled()+'''+ )+ exec(code, vars(module))++del Loader; del MetaPathFinder+"""+ )++ exec(definitions, glbls)++ # append the finder to the end of meta_path, in case the user+ # already has a package called micropip+ exec(+ "import sys; sys.meta_path.append(_MicropipFinder()); del sys",+ glbls,+ )++def patch_main_module(file: str | None, input_override: Callable[[Any], str] | None) -> types.ModuleType:- """Patches __main__ so that functions are pickleable."""+ """Patches __main__ module++ - Makes functions pickleable+ - Loads some overrides and mocks into globals+ """# Every kernel gets its own main module, whose __dict__ attribute# serves as the global namespacediff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex caf30f946f..e352f4b2f7 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -87,6 +87,7 @@ from marimo._runtime.requests import (from marimo._runtime.state import Statefrom marimo._runtime.validate_graph import check_for_errorsfrom marimo._server.types import QueueType+from marimo._utils.platform import is_pyodidefrom marimo._utils.signals import restore_signalsfrom marimo._utils.typed_connection import TypedConnection@@ -222,8 +223,10 @@ class Kernel:# was invoked. New state updates evict older ones.self.state_updates: dict[State[Any], CellId_t] = {}+ if not is_pyodide():+ patches.patch_micropip(self.globals)# an empty string represents the current directory- exec("import sys; sys.path.append('')", self.globals)+ exec("import sys; sys.path.append(''); del sys", self.globals)exec("import marimo as __marimo__", self.globals)@propertydiff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.pyindex 8f4169d548..6eb245fbc6 100644--- a/marimo/_runtime/virtual_file.py+++ b/marimo/_runtime/virtual_file.py@@ -15,13 +15,14 @@ from marimo import _loggersfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.utils import build_data_urlfrom marimo._runtime.cell_lifecycle_item import CellLifecycleItem+from marimo._utils.platform import is_pyodideif TYPE_CHECKING:from marimo._runtime.context import RuntimeContextLOGGER = _loggers.marimo_logger()-if "pyodide" not in sys.modules:+if not is_pyodide():# the shared_memory module is not supported in the Pyodide distributionfrom multiprocessing import shared_memorydiff --git a/marimo/_smoke_tests/bugs/852.py b/marimo/_smoke_tests/bugs/852.pyindex cc9b86df39..87c70ba141 100644--- a/marimo/_smoke_tests/bugs/852.py+++ b/marimo/_smoke_tests/bugs/852.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.2.9"diff --git a/marimo/_smoke_tests/bugs/877.py b/marimo/_smoke_tests/bugs/877.pyindex d91c79c44e..188c182504 100644--- a/marimo/_smoke_tests/bugs/877.py+++ b/marimo/_smoke_tests/bugs/877.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.2.12"diff --git a/marimo/_smoke_tests/bugs/881.py b/marimo/_smoke_tests/bugs/881.pyindex a51823cfdd..99fa708eb4 100644--- a/marimo/_smoke_tests/bugs/881.py+++ b/marimo/_smoke_tests/bugs/881.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import marimo__generated_with = "0.2.12"diff --git a/marimo/_utils/debounce.py b/marimo/_utils/debounce.pyindex d90aadb7c1..9168a13681 100644--- a/marimo/_utils/debounce.py+++ b/marimo/_utils/debounce.py@@ -1,3 +1,4 @@+# Copyright 2024 Marimo. All rights reserved.import timefrom functools import wrapsfrom typing import Any, Callable, TypeVar, castdiff --git a/marimo/_utils/platform.py b/marimo/_utils/platform.pynew file mode 100644index 0000000000..0353eeebe8--- /dev/null+++ b/marimo/_utils/platform.py@@ -0,0 +1,10 @@+# Copyright 2024 Marimo. All rights reserved.+import sys+++def is_windows() -> bool:+ return sys.platform == "win32" or sys.platform == "cygwin"+++def is_pyodide() -> bool:+ return "pyodide" in sys.modulesdiff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.pyindex 272039dde4..a16551df61 100644--- a/tests/_messaging/test_streams.py+++ b/tests/_messaging/test_streams.py@@ -22,14 +22,18 @@ class TestStdin:async def test_readline_installed(k: Kernel, exec_req: ExecReqProvider) -> None:- await k.run([exec_req.get("output = sys.stdin.readline()")])+ await k.run(+ [exec_req.get("import sys; output = sys.stdin.readline()")]+ )assert k.globals["output"] == ""@staticmethodasync def test_readlines_installed(k: Kernel, exec_req: ExecReqProvider) -> None:- await k.run([exec_req.get("output = sys.stdin.readlines()")])+ await k.run(+ [exec_req.get("import sys; output = sys.stdin.readlines()")]+ )assert k.globals["output"] == [""]@@ -40,7 +44,7 @@ class TestStdout:@staticmethodasync def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:- await k.run([exec_req.get("fileno = sys.stdout.fileno()")])+ await k.run([exec_req.get("import sys; fileno = sys.stdout.fileno()")])assert k.globals["fileno"] is not None@staticmethod@@ -82,7 +86,7 @@ class TestStderr:@staticmethodasync def test_fileno(k: Kernel, exec_req: ExecReqProvider) -> None:- await k.run([exec_req.get("fileno = sys.stderr.fileno()")])+ await k.run([exec_req.get("import sys; fileno = sys.stderr.fileno()")])assert k.globals["fileno"] is not None@staticmethoddiff --git a/tests/_runtime/test_patches.py b/tests/_runtime/test_patches.pynew file mode 100644index 0000000000..c2ac7f5384--- /dev/null+++ b/tests/_runtime/test_patches.py@@ -0,0 +1,120 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._runtime.capture import capture_stderr+from marimo._runtime.runtime import Kernel+from marimo._utils.platform import is_pyodide+from tests.conftest import ExecReqProvider+++class TestMicropip:+ @staticmethod+ def _assert_micropip_warning_printed(message: str) -> None:+ assert "micropip is only available in WASM notebooks" in message++ @staticmethod+ async def test_micropip_available(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ await executing_kernel.run([exec_req.get("import micropip")])+ assert "micropip" in executing_kernel.globals++ @staticmethod+ async def test_micropip_install(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get("await micropip.install('foo')"),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())++ @staticmethod+ async def test_micropip_list(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get("micropip.list()"),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())++ @staticmethod+ async def test_micropip_freeze(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get("micropip.freeze()"),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())++ @staticmethod+ async def test_micropip_add_mock_package(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get(+ "micropip.add_mock_package('foo', '0.1')"+ ),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())++ @staticmethod+ async def test_micropip_list_mock_packages(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get("micropip.list_mock_packages()"),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())++ @staticmethod+ async def test_micropip_uninstall(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get("micropip.uninstall('foo')"),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())++ @staticmethod+ async def test_micropip_set_index_urls(+ executing_kernel: Kernel, exec_req: ExecReqProvider+ ) -> None:+ if not is_pyodide():+ with capture_stderr() as buf:+ await executing_kernel.run(+ [+ exec_req.get("import micropip"),+ exec_req.get("micropip.set_index_urls('foo')"),+ ]+ )+ TestMicropip._assert_micropip_warning_printed(buf.getvalue())