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
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.mdindex 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__.pyindex 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.pyindex 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 inspectimport randomimport stringfrom 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 = Nonedef 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.pyindex 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 = filenamedef 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.pyindex 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.pyindex 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.pyindex 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 | Nonechildren: list[RuntimeContext]parent: RuntimeContext | None+ filename: str | None@property@abc.abstractmethoddiff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex 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.dataclassclass CellMetadata:"""CellMetadatadiff --git a/marimo/_smoke_tests/nb_dir.py b/marimo/_smoke_tests/nb_dir.pynew file mode 100644index 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.pyindex a6b14f34ae..d50ad8af37 100644--- a/tests/_ast/test_app.py+++ b/tests/_ast/test_app.py@@ -2,12 +2,13 @@from __future__ import annotations+import pathlibimport subprocessimport textwrap-from typing import TYPE_CHECKING, Any+from typing import Anyimport pytest-from marimo._ast.app import App, _AppConfig, InternalApp+from marimo._ast.app import App, _AppConfigfrom 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_htmlfrom marimo._plugins.stateless.flex import vstackfrom marimo._runtime.requests import SetUIElementValueRequestfrom marimo._runtime.runtime import Kernelfrom 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.celldef __() -> 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.pyindex 442e2efc39..80f02dac17 100644--- a/tests/_cli/test_cli_export.py+++ b/tests/_cli/test_cli_export.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport asyncioimport inspectimport subprocess+import sysfrom os import pathfrom typing import TYPE_CHECKING@@ -20,6 +21,10 @@ if TYPE_CHECKING:snapshot = snapshotter(__file__)+def _is_win32() -> bool:+ return sys.platform == "win32"++class TestExportHTML:@staticmethoddef 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.pyindex 75f3365c01..fd4821011c 100644--- a/tests/_runtime/test_runtime.py+++ b/tests/_runtime/test_runtime.py@@ -21,6 +21,10 @@ from marimo._messaging.ops import CellOpfrom marimo._messaging.types import NoopStreamfrom marimo._plugins.ui._core.ids import IDProviderfrom 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_contextfrom marimo._runtime.dataflow import EdgeWithVarfrom marimo._runtime.patches import create_main_modulefrom 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: