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: add `mo.notebook_dir()`. avoid relative paths for better reproducibility (#2464)

Myles Scolnickddd11e2203be
diff --git a/docs/api/miscellaneous.md b/docs/api/miscellaneous.md
index 02ea6a1134..7d4eaeafa9 100644
--- a/docs/api/miscellaneous.md
+++ b/docs/api/miscellaneous.md
@@ -11,3 +11,7 @@
```{eval-rst}
.. autofunction:: marimo.refs
```
+
+```{eval-rst}
+.. autofunction:: marimo.notebook_dir
+```
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 0f1f272c5e..09f779527f 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -51,6 +51,7 @@ __all__ = [
"mermaid",
"mpl",
"nav_menu",
+ "notebook_dir",
"output",
"pdf",
"plain_text",
@@ -121,6 +122,7 @@ from marimo._runtime.runtime import (
app_meta,
cli_args,
defs,
+ notebook_dir,
query_params,
refs,
)
diff --git a/marimo/_ast/app.py b/marimo/_ast/app.py
index 88986625b3..6c528fb8b7 100644
--- a/marimo/_ast/app.py
+++ b/marimo/_ast/app.py
@@ -1,6 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import inspect
import random
import string
from dataclasses import asdict, dataclass, field
@@ -178,6 +179,12 @@ class App:
# Set as a private attribute as not to pollute AppConfig or kwargs.
self._anonymous_file = False
+ # Filename is derived from the callsite of the app
+ self._filename: str | None = None
+ try:
+ self._filename = inspect.getfile(inspect.stack()[1].frame)
+ except Exception:
+ ...
self._app_kernel_runner: AppKernelRunner | None = None
def cell(
@@ -295,7 +302,9 @@ class App:
self,
) -> tuple[Sequence[Any], Mapping[str, Any]]:
self._maybe_initialize()
- outputs, glbls = AppScriptRunner(InternalApp(self)).run()
+ outputs, glbls = AppScriptRunner(
+ InternalApp(self), filename=self._filename
+ ).run()
return (self._flatten_outputs(outputs), self._globals_to_defs(glbls))
async def _run_cell_async(
diff --git a/marimo/_runtime/app/script_runner.py b/marimo/_runtime/app/script_runner.py
index b5f37f891e..f2612a585f 100644
--- a/marimo/_runtime/app/script_runner.py
+++ b/marimo/_runtime/app/script_runner.py
@@ -31,8 +31,9 @@ if TYPE_CHECKING:
class AppScriptRunner:
"""Runs an app in a script context."""
- def __init__(self, app: InternalApp) -> None:
+ def __init__(self, app: InternalApp, filename: str | None) -> None:
self.app = app
+ self.filename = filename
def run(self) -> RunOutput:
from marimo._runtime.context.script_context import (
@@ -58,7 +59,9 @@ class AppScriptRunner:
if not runtime_context_installed():
# script context is ephemeral, only installed while the app is
# running
- initialize_script_context(app=app, stream=NoopStream())
+ initialize_script_context(
+ app=app, stream=NoopStream(), filename=self.filename
+ )
installed_script_context = True
# formatters aren't automatically registered when running as a
@@ -128,7 +131,7 @@ class AppScriptRunner:
post_execute_hooks: list[Callable[[], Any]],
) -> RunOutput:
with patch_main_module_context(
- create_main_module(file=None, input_override=None)
+ create_main_module(file=self.filename, input_override=None)
) as module:
glbls = module.__dict__
outputs: dict[CellId_t, Any] = {}
@@ -145,7 +148,7 @@ class AppScriptRunner:
post_execute_hooks: list[Callable[[], Any]],
) -> RunOutput:
with patch_main_module_context(
- create_main_module(file=None, input_override=None)
+ create_main_module(file=self.filename, input_override=None)
) as module:
glbls = module.__dict__
outputs: dict[CellId_t, Any] = {}
diff --git a/marimo/_runtime/context/kernel_context.py b/marimo/_runtime/context/kernel_context.py
index f1d2091e33..9aa7294602 100644
--- a/marimo/_runtime/context/kernel_context.py
+++ b/marimo/_runtime/context/kernel_context.py
@@ -141,6 +141,7 @@ def create_kernel_context(
stderr=stderr,
children=[],
parent=parent,
+ filename=kernel.app_metadata.filename,
)
diff --git a/marimo/_runtime/context/script_context.py b/marimo/_runtime/context/script_context.py
index b1b3aefa48..5dbdcf1668 100644
--- a/marimo/_runtime/context/script_context.py
+++ b/marimo/_runtime/context/script_context.py
@@ -110,7 +110,9 @@ class ScriptRuntimeContext(RuntimeContext):
return self._app
-def initialize_script_context(app: InternalApp, stream: Stream) -> None:
+def initialize_script_context(
+ app: InternalApp, stream: Stream, filename: str | None
+) -> None:
"""Initializes thread-local/session-specific context.
Must be called exactly once for each client thread.
@@ -130,5 +132,6 @@ def initialize_script_context(app: InternalApp, stream: Stream) -> None:
stderr=None,
children=[],
parent=None,
+ filename=filename,
)
initialize_context(runtime_context=runtime_context)
diff --git a/marimo/_runtime/context/types.py b/marimo/_runtime/context/types.py
index d83455db85..4f9949b7f3 100644
--- a/marimo/_runtime/context/types.py
+++ b/marimo/_runtime/context/types.py
@@ -74,6 +74,7 @@ class RuntimeContext(abc.ABC):
stderr: Stderr | None
children: list[RuntimeContext]
parent: RuntimeContext | None
+ filename: str | None
@property
@abc.abstractmethod
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 8ac3299c9a..b51c8b6659 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -277,6 +277,37 @@ def cli_args() -> CLIArgs:
return get_context().cli_args
+@mddoc
+def notebook_dir() -> pathlib.Path | None:
+ """Get the directory of the currently executing notebook.
+
+ **Returns**:
+
+ - A `pathlib.Path` object representing the directory of the current
+ notebook, or `None` if the notebook's directory cannot be determined.
+
+ **Examples**:
+
+ ```python
+ data_file = mo.notebook_dir() / "data" / "example.csv"
+ # Use the directory to read a file
+ if data_file.exists():
+ print(f"Found data file: {data_file}")
+ else:
+ print("No data file found")
+ ```
+ """
+ try:
+ ctx = get_context()
+ except ContextNotInitializedError:
+ return None
+
+ filename = ctx.filename
+ if filename is not None:
+ return pathlib.Path(filename).parent.absolute()
+ return None
+
+
@dataclasses.dataclass
class CellMetadata:
"""CellMetadata
diff --git a/marimo/_smoke_tests/nb_dir.py b/marimo/_smoke_tests/nb_dir.py
new file mode 100644
index 0000000000..db603bbdb6
--- /dev/null
+++ b/marimo/_smoke_tests/nb_dir.py
@@ -0,0 +1,26 @@
+import marimo
+
+__generated_with = "0.8.22"
+app = marimo.App(width="medium")
+
+
+def __():
+ import marimo as mo
+ return (mo,)
+
+
+def __(__file__):
+ print("__file__", __file__)
+ return
+
+
+def __(mo):
+ print("mo.notebook_dir()", mo.notebook_dir())
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index a6b14f34ae..d50ad8af37 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -2,12 +2,13 @@
from __future__ import annotations
+import pathlib
import subprocess
import textwrap
-from typing import TYPE_CHECKING, Any
+from typing import Any
import pytest
-from marimo._ast.app import App, _AppConfig, InternalApp
+from marimo._ast.app import App, _AppConfig
from marimo._ast.errors import (
CycleError,
DeleteNonlocalError,
@@ -15,15 +16,11 @@ from marimo._ast.errors import (
UnparsableError,
)
from marimo._dependencies.dependencies import DependencyManager
-from marimo._output.formatting import as_html
from marimo._plugins.stateless.flex import vstack
from marimo._runtime.requests import SetUIElementValueRequest
from marimo._runtime.runtime import Kernel
from tests.conftest import ExecReqProvider
-if TYPE_CHECKING:
- import pathlib
-
# don't complain for useless expressions (cell outputs)
# ruff: noqa: B018
@@ -378,8 +375,7 @@ class TestApp:
@app.cell
def __() -> tuple[Any]:
- def foo() -> None:
- ...
+ def foo() -> None: ...
return (foo,)
@@ -480,7 +476,9 @@ class TestApp:
assert config.auto_download == []
# Test from_untrusted_dict
- config = _AppConfig.from_untrusted_dict({"auto_download": ["markdown"]})
+ config = _AppConfig.from_untrusted_dict(
+ {"auto_download": ["markdown"]}
+ )
assert config.auto_download == ["markdown"]
# Test asdict
@@ -491,6 +489,23 @@ class TestApp:
config = _AppConfig(auto_download=["invalid"])
assert config.auto_download == ["invalid"]
+ def test_has_file_and_dirname(self) -> None:
+ app = App()
+
+ @app.cell
+ def f():
+ file = __file__
+
+ @app.cell
+ def g():
+ import marimo as mo
+
+ dirpath = mo.notebook_dir()
+
+ _, glbls = app.run()
+ assert glbls["file"] == __file__
+ assert glbls["dirpath"] == pathlib.Path(glbls["file"]).parent
+
def test_app_config() -> None:
config = _AppConfig.from_untrusted_dict({"width": "full"})
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
index 442e2efc39..80f02dac17 100644
--- a/tests/_cli/test_cli_export.py
+++ b/tests/_cli/test_cli_export.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio
import inspect
import subprocess
+import sys
from os import path
from typing import TYPE_CHECKING
@@ -20,6 +21,10 @@ if TYPE_CHECKING:
snapshot = snapshotter(__file__)
+def _is_win32() -> bool:
+ return sys.platform == "win32"
+
+
class TestExportHTML:
@staticmethod
def test_cli_export_html(temp_marimo_file: str) -> None:
@@ -253,8 +258,8 @@ class TestExportScript:
)
@pytest.mark.skipif(
- condition=DependencyManager.watchdog.has(),
- reason="hangs when watchdog is installed",
+ condition=DependencyManager.watchdog.has() or _is_win32(),
+ reason="hangs when watchdog is installed, flaky on Windows",
)
async def test_export_watch_script(self, temp_marimo_file: str) -> None:
temp_out_file = temp_marimo_file.replace(".py", ".script.py")
@@ -362,8 +367,8 @@ class TestExportMarkdown:
snapshot("broken.txt", output)
@pytest.mark.skipif(
- condition=DependencyManager.watchdog.has(),
- reason="hangs when watchdog is installed",
+ condition=DependencyManager.watchdog.has() or _is_win32(),
+ reason="hangs when watchdog is installed, flaky on Windows",
)
async def test_export_watch_markdown(self, temp_marimo_file: str) -> None:
temp_out_file = temp_marimo_file.replace(".py", ".md")
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 75f3365c01..fd4821011c 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -21,6 +21,10 @@ from marimo._messaging.ops import CellOp
from marimo._messaging.types import NoopStream
from marimo._plugins.ui._core.ids import IDProvider
from marimo._plugins.ui._core.ui_element import UIElement
+from marimo._runtime.context.kernel_context import (
+ initialize_kernel_context,
+)
+from marimo._runtime.context.types import teardown_context
from marimo._runtime.dataflow import EdgeWithVar
from marimo._runtime.patches import create_main_module
from marimo._runtime.requests import (
@@ -880,6 +884,56 @@ class TestExecution:
assert "pytest" in k.globals["x"]
+ async def test_notebook_dir(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("x = mo.notebook_dir()"),
+ ]
+ )
+ assert "x" in k.globals
+ assert k.globals["x"] is None
+
+ async def test_notebook_dir_for_unnamed_notebook(
+ self, tmp_path: pathlib.Path, exec_req: ExecReqProvider
+ ) -> None:
+ try:
+ filename = str(tmp_path / "notebook.py")
+ k = Kernel(
+ stream=NoopStream(),
+ stdout=None,
+ stderr=None,
+ stdin=None,
+ cell_configs={},
+ user_config=DEFAULT_CONFIG,
+ app_metadata=AppMetadata(
+ query_params={}, filename=filename, cli_args={}
+ ),
+ enqueue_control_request=lambda _: None,
+ module=create_main_module(None, None),
+ )
+ initialize_kernel_context(
+ kernel=k,
+ stream=k.stream,
+ stdout=k.stdout,
+ stderr=k.stderr,
+ )
+
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("x = mo.notebook_dir() / 'foo.csv'"),
+ ]
+ )
+ assert str(k.globals["x"]).endswith("foo.csv")
+ finally:
+ teardown_context()
+ if str(tmp_path) in sys.path:
+ sys.path.remove(str(tmp_path))
+
async def test_pickle(
self, any_kernel: Kernel, exec_req: ExecReqProvider
) -> None: