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.

feat/fix: reactive filename/ fallback for __file__ (#1991)

Dylan Madisetti0d89232e175b
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index b8f906c508..68fc94a729 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -155,6 +155,7 @@ def _generate_schema() -> dict[str, Any]:
requests.FunctionCallRequest,
requests.InstallMissingPackagesRequest,
requests.PreviewDatasetColumnRequest,
+ requests.RenameRequest,
requests.SetCellConfigRequest,
requests.SetUserConfigRequest,
requests.StopRequest,
diff --git a/marimo/_runtime/patches.py b/marimo/_runtime/patches.py
index 7454ade8ca..64bc08a561 100644
--- a/marimo/_runtime/patches.py
+++ b/marimo/_runtime/patches.py
@@ -136,6 +136,10 @@ def create_main_module(
_module.__dict__.setdefault(
"__file__", sys.modules["__main__"].__file__
)
+ else:
+ # Windows seems to have this edgecase where __file__ is not set
+ # so default to None, per the intended behavior in #668.
+ _module.__dict__.setdefault("__file__", None)
return _module
diff --git a/marimo/_runtime/requests.py b/marimo/_runtime/requests.py
index 80585dbe8a..8b49154bd9 100644
--- a/marimo/_runtime/requests.py
+++ b/marimo/_runtime/requests.py
@@ -61,6 +61,11 @@ class ExecuteScratchpadRequest:
code: str
+@dataclass
+class RenameRequest:
+ filename: str
+
+
@dataclass
class SetUIElementValueRequest:
object_ids: List[UIElementId]
@@ -168,6 +173,7 @@ ControlRequest = Union[
CreationRequest,
DeleteCellRequest,
FunctionCallRequest,
+ RenameRequest,
SetCellConfigRequest,
SetUserConfigRequest,
SetUIElementValueRequest,
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 49ade2b46f..5c99bdfe2b 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -104,6 +104,7 @@ from marimo._runtime.requests import (
FunctionCallRequest,
InstallMissingPackagesRequest,
PreviewDatasetColumnRequest,
+ RenameRequest,
SetCellConfigRequest,
SetUIElementValueRequest,
SetUserConfigRequest,
@@ -1116,6 +1117,14 @@ class Kernel:
self.mutate_graph(filtered_requests, deletion_requests=[])
)
+ async def rename_file(self, filename: str) -> None:
+ self.globals["__file__"] = filename
+ roots = set()
+ for cell in self.graph.cells.values():
+ if "__file__" in cell.refs:
+ roots.add(cell.cell_id)
+ await self._run_cells(roots)
+
async def run_scratchpad(self, code: str) -> None:
roots = {SCRATCH_CELL_ID}
@@ -1619,6 +1628,8 @@ class Kernel:
await self.run_scratchpad(request.code)
elif isinstance(request, ExecuteStaleRequest):
await self.run_stale_cells()
+ elif isinstance(request, RenameRequest):
+ await self.rename_file(request.filename)
elif isinstance(request, SetCellConfigRequest):
await self.set_cell_config(request)
elif isinstance(request, SetUserConfigRequest):
diff --git a/marimo/_server/api/endpoints/files.py b/marimo/_server/api/endpoints/files.py
index bc7a3a9c82..fc14e52660 100644
--- a/marimo/_server/api/endpoints/files.py
+++ b/marimo/_server/api/endpoints/files.py
@@ -97,6 +97,10 @@ async def rename_file(
elif new_path:
app_state.session_manager.recents.touch(new_path)
+ app_state.require_current_session().put_control_request(
+ body.as_execution_request()
+ )
+
return SuccessResponse()
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index 5509a36eff..1ff4af4786 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import os
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
@@ -9,6 +10,7 @@ from marimo._config.config import MarimoConfig
from marimo._runtime.requests import (
ExecuteMultipleRequest,
ExecuteScratchpadRequest,
+ RenameRequest,
)
UIElementId = str
@@ -66,6 +68,9 @@ class ReadCodeResponse:
class RenameFileRequest:
filename: str
+ def as_execution_request(self) -> RenameRequest:
+ return RenameRequest(filename=os.path.abspath(self.filename))
+
@dataclass
class OpenFileRequest:
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index 30de8990d5..00cfaef027 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -6,10 +6,14 @@ import random
from typing import TYPE_CHECKING
from tests._server.conftest import get_session_manager
-from tests._server.mocks import token_header, with_session
+from tests._server.mocks import (
+ token_header,
+ with_session,
+ with_websocket_session,
+)
if TYPE_CHECKING:
- from fastapi.testclient import TestClient
+ from fastapi.testclient import TestClient, WebSocketTestSession
SESSION_ID = "session-123"
HEADERS = {
@@ -226,3 +230,62 @@ def test_save_app_config(client: TestClient) -> None:
assert "import marimo" in response.text
file_contents = open(filename).read()
assert 'marimo.App(width="medium"' in file_contents
+
+
+@with_websocket_session(SESSION_ID)
+def test_rename_propagates(
+ client: TestClient, websocket: WebSocketTestSession
+) -> None:
+ current_filename = get_session_manager(
+ client
+ ).file_router.get_unique_file_key()
+
+ assert current_filename
+ assert os.path.exists(current_filename)
+
+ initial_response = client.post(
+ "/api/kernel/run",
+ headers=HEADERS,
+ json={
+ "cell_ids": ["cell-1", "cell-2"],
+ "codes": ["b = __file__", "a = 'x' + __file__"],
+ },
+ )
+ assert initial_response.json() == {"success": True}
+ assert initial_response.status_code == 200, initial_response.text
+
+ variables = {}
+ while len(variables) < 2:
+ data = websocket.receive_json()
+ if data["op"] == "variable-values":
+ for var in data["data"]["variables"]:
+ variables[var["name"]] = var["value"]
+
+ # Variable outputs are truncated to 50 characters
+ # current_filename can exceed this count on windows and OSX.
+ assert ("x" + current_filename).startswith(variables["a"])
+ assert current_filename.startswith(variables["b"])
+
+ directory = os.path.dirname(current_filename)
+ random_name = random.randint(0, 100000)
+ new_filename = os.path.join(directory, f"test_{random_name}.py")
+
+ response = client.post(
+ "/api/kernel/rename",
+ headers=HEADERS,
+ json={
+ "filename": new_filename,
+ },
+ )
+ assert response.json() == {"success": True}
+ assert response.status_code == 200, response.text
+
+ variables = {}
+ while len(variables) < 2:
+ data = websocket.receive_json()
+ if data["op"] == "variable-values":
+ for var in data["data"]["variables"]:
+ variables[var["name"]] = var["value"]
+
+ assert ("x" + new_filename).startswith(variables["a"])
+ assert new_filename.startswith(variables["b"])
diff --git a/tests/_server/mocks.py b/tests/_server/mocks.py
index 7d8e46b999..616b62d4d2 100644
--- a/tests/_server/mocks.py
+++ b/tests/_server/mocks.py
@@ -113,6 +113,37 @@ def with_session(
return decorator
+def with_websocket_session(
+ session_id: str,
+ auto_shutdown: bool = True,
+) -> Callable[[Callable[..., None]], Callable[..., None]]:
+ """Decorator to create a session and close it after the test"""
+
+ def decorator(func: Callable[..., None]) -> Callable[..., None]:
+ def wrapper(client: TestClient) -> None:
+ auth_token = get_session_manager(client).auth_token
+ headers = token_header(auth_token)
+
+ with client.websocket_connect(
+ f"/ws?session_id={session_id}", headers=headers
+ ) as websocket:
+ data = websocket.receive_text()
+ assert data
+
+ func(client, websocket)
+ # shutdown after websocket exits, otherwise
+ # test fails on Windows (loop closed twice)
+ if auto_shutdown:
+ client.post(
+ "/api/kernel/shutdown",
+ headers=headers,
+ )
+
+ return wrapper
+
+ return decorator
+
+
def with_read_session(
session_id: str,
) -> Callable[[Callable[..., None]], Callable[..., None]]: