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 `__file__` in embedded notebooks (#5854)

Trevor Manz8c6a88694851
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index ca9bf094be..780327dab5 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -282,6 +282,7 @@ class App:
A new `app` object with the same code.
"""
app = App()
+ app._filename = self._filename
app._cell_manager = CellManager(prefix=str(uuid4()))
for cell_id, code, name, config in zip(
self._cell_manager.cell_ids(),
@@ -762,6 +763,10 @@ class InternalApp:
def cell_manager(self) -> CellManager:
return self._app._cell_manager
+ @property
+ def filename(self) -> str | None:
+ return self._app._filename
+
@property
def graph(self) -> dataflow.DirectedGraph:
self._app._maybe_initialize()
diff --git a/marimo/_runtime/app/kernel_runner.py b/marimo/_runtime/app/kernel_runner.py
index 35889ea5e6..b95d92dce4 100644
--- a/marimo/_runtime/app/kernel_runner.py
+++ b/marimo/_runtime/app/kernel_runner.py
@@ -64,7 +64,7 @@ class AppKernelRunner:
else:
self.outputs[cell.cell_id] = run_result.output
- filename = "<unknown>"
+ filename = app.filename if app.filename is not None else "<unknown>"
self._kernel = Kernel(
cell_configs={},
app_metadata=AppMetadata(
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index b089ae7e7c..8c3eb0b60f 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -378,7 +378,8 @@ def notebook_dir() -> pathlib.Path | None:
# return the current working directory
return pathlib.Path().absolute()
- filename = ctx.filename
+ # NB: __file__ is patched by runner, so always bound to be correct.
+ filename = ctx.globals.get("__file__", None) or ctx.filename
if filename is not None:
return pathlib.Path(filename).parent.absolute()
diff --git a/tests/_ast/app_data/notebook_filename.py b/tests/_ast/app_data/notebook_filename.py
new file mode 100644
index 0000000000..3c7ece91d4
--- /dev/null
+++ b/tests/_ast/app_data/notebook_filename.py
@@ -0,0 +1,26 @@
+import marimo
+
+__generated_with = "0.14.15"
+app = marimo.App(width="medium")
+
+
+with app.setup:
+ import marimo as mo
+
+
+def _():
+ this_is_foo_path = mo.notebook_dir()
+ this_is_foo_path
+ return
+
+
+def _():
+ this_is_foo_file = __file__
+ this_is_foo_file
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index 40e1f31864..d34bcef028 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -3,17 +3,19 @@
from __future__ import annotations
import pathlib
import subprocess
+import sys
import textwrap
-from typing import Any, TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
import pytest
-from marimo._ast.app_config import _AppConfig
from marimo._ast.app import (
App,
+ AppEmbedResult,
AppKernelRunnerRegistry,
InternalApp,
)
+from marimo._ast.app_config import _AppConfig
from marimo._ast.errors import (
CycleError,
DeleteNonlocalError,
@@ -21,10 +23,18 @@ from marimo._ast.errors import (
SetupRootError,
UnparsableError,
)
+from marimo._ast.load import load_app
+from marimo._convert.converters import MarimoConvert
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins.stateless.flex import vstack
from marimo._runtime.context.types import get_context
from marimo._runtime.requests import SetUIElementValueRequest
+from marimo._schemas.serialization import (
+ AppInstantiation,
+ CellDef,
+ NotebookSerializationV1,
+)
+from marimo._types.ids import CellId_t
from tests.conftest import ExecReqProvider
if TYPE_CHECKING:
@@ -850,7 +860,7 @@ def test_cli_args(tmp_path: pathlib.Path) -> None:
"""
py_file.write_text(textwrap.dedent(content))
p = subprocess.run(
- ["python", str(py_file), "--foo", "value1", "--bar", "value2"],
+ [sys.executable, str(py_file), "--foo", "value1", "--bar", "value2"],
stdout=subprocess.PIPE,
)
assert p.returncode == 0
@@ -1044,12 +1054,14 @@ class TestAppComposition:
@staticmethod
def test_setup_hide_code() -> None:
+ setup_cell_id = CellId_t("setup")
+
# Test property access (default behavior, hide_code=False)
app1 = App()
with app1.setup:
x = 1
- setup_cell = app1._cell_manager._cell_data.get("setup")
+ setup_cell = app1._cell_manager._cell_data.get(setup_cell_id)
assert setup_cell is not None
assert setup_cell.config.hide_code is False
@@ -1058,7 +1070,7 @@ class TestAppComposition:
with app2.setup():
x2 = 1
- setup_cell = app2._cell_manager._cell_data.get("setup")
+ setup_cell = app2._cell_manager._cell_data.get(setup_cell_id)
assert setup_cell is not None
assert setup_cell.config.hide_code is False
@@ -1067,7 +1079,7 @@ class TestAppComposition:
with app3.setup(hide_code=True):
y = 2
- setup_cell = app3._cell_manager._cell_data.get("setup")
+ setup_cell = app3._cell_manager._cell_data.get(setup_cell_id)
assert setup_cell is not None
assert setup_cell.config.hide_code is True
@@ -1075,12 +1087,66 @@ class TestAppComposition:
app4 = App()
with app4.setup(hide_code=False):
z = 3
-
- setup_cell = app4._cell_manager._cell_data.get("setup")
+
+ setup_cell = app4._cell_manager._cell_data.get(setup_cell_id)
assert setup_cell is not None
assert setup_cell.config.hide_code is False
+ @staticmethod
+ async def test_app_embed_preserves_file_path(
+ app: App
+ ) -> None:
+ with app.setup:
+ from tests._ast.app_data import notebook_filename
+
+ @app.cell
+ async def _():
+ app = await notebook_filename.app.embed()
+ cloned = await notebook_filename.app.clone().embed()
+ filename = "notebook_filename.py"
+ directory = "app_data"
+ return (app, cloned, filename, directory)
+
+ @app.cell
+ def _(app: AppEmbedResult, filename: str, directory: str) -> None:
+ assert app.defs.get("this_is_foo_file").endswith(filename)
+ assert app.defs.get("this_is_foo_path").stem == directory
+
+ @app.cell
+ def _(cloned: AppEmbedResult, filename: str, directory: str) -> None:
+ assert cloned.defs.get("this_is_foo_file").endswith(filename)
+ assert cloned.defs.get("this_is_foo_path").stem == directory
+
+
+ @staticmethod
+ async def test_app_embed_in_kernel(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ from tests._ast.app_data import notebook_filename
+ """
+ ),
+ exec_req.get(
+ """
+ app = await notebook_filename.app.embed()
+ cloned = await notebook_filename.app.clone().embed()
+ """
+ ),
+ ]
+ )
+ assert not k.errors
+ filename = "notebook_filename.py"
+ directory = "app_data"
+ assert k.globals["app"].defs.get("this_is_foo_file").endswith(filename)
+ assert k.globals["cloned"].defs.get("this_is_foo_file").endswith(filename)
+ assert k.globals["app"].defs.get("this_is_foo_path").stem == directory
+ assert k.globals["cloned"].defs.get("this_is_foo_path").stem == directory
+
+
class TestAppKernelRunnerRegistry:
def test_get_runner(self, k: Kernel) -> None:
# `k` fixture installs a context, needed for AppKernelRunner
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index d18a7d7250..b979a55488 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1137,7 +1137,7 @@ class TestExecution:
]
)
assert "x" in k.globals
- assert k.globals["x"] is None
+ assert k.globals["x"] is not None
async def test_notebook_location(
self, any_kernel: Kernel, exec_req: ExecReqProvider
@@ -1151,9 +1151,9 @@ class TestExecution:
]
)
assert "loc" in k.globals
- assert k.globals["loc"] is None
+ assert k.globals["loc"] is not None
assert "dir" in k.globals
- assert k.globals["dir"] is k.globals["loc"]
+ assert k.globals["dir"] is not None
@pytest.mark.skipif(
sys.platform == "win32", reason="Windows paths behave differently"
diff --git a/tests/conftest.py b/tests/conftest.py
index a8256c1f99..9efb8e9644 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import dataclasses
import inspect
import os
+import pathlib
import re
import sys
import textwrap
@@ -150,8 +151,18 @@ class MockedKernel:
self.stderr = MockStderr(self.stream)
self.stdin = MockStdin(self.stream)
self._main = sys.modules["__main__"]
+ # On Windows, sys.modules["__main__"].__file__ might be something like
+ # "pytest.exe\__main__.py" which causes issues. Use a dummy file instead.
+ test_file = None
+ if (
+ sys.platform == "win32"
+ and hasattr(sys.modules["__main__"], "__file__")
+ and "pytest.exe" in str(sys.modules["__main__"].__file__)
+ ):
+ test_file = str(pathlib.Path.cwd() / "__test__.py")
+
module = patches.patch_main_module(
- file=None,
+ file=test_file,
input_override=input_override,
print_override=print_override,
)