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: mo.notebook_location() (#3353)

Myles Scolnick99612893b090
diff --git a/docs/api/miscellaneous.md b/docs/api/miscellaneous.md
index 6b7a56613a..862733f112 100644
--- a/docs/api/miscellaneous.md
+++ b/docs/api/miscellaneous.md
@@ -5,6 +5,9 @@
::: marimo.defs
::: marimo.refs
+
::: marimo.notebook_dir
+::: marimo.notebook_location
+
::: marimo.Thread
diff --git a/marimo/__init__.py b/marimo/__init__.py
index ded4cb59fd..3b098487ab 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -56,6 +56,7 @@ __all__ = [
"mpl",
"nav_menu",
"notebook_dir",
+ "notebook_location",
"output",
"pdf",
"persistent_cache",
@@ -130,6 +131,7 @@ from marimo._runtime.runtime import (
cli_args,
defs,
notebook_dir,
+ notebook_location,
query_params,
refs,
)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index d418d2e575..f9a0cc7ffa 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -317,6 +317,48 @@ def notebook_dir() -> pathlib.Path | None:
return None
+@mddoc
+def notebook_location() -> pathlib.Path | None:
+ """Get the location of the currently executing notebook.
+
+ In WASM, this is the URL of webpage, for example, `https://my-site.com`.
+ For nested paths, this is the URL including the origin and pathname.
+ `https://<my-org>.github.io/<my-repo>/folder`.
+
+ In non-WASM, this is the directory of the notebook, which is the same as
+ `mo.notebook_dir()`.
+
+ Examples:
+ In order to access data both locally and when a notebook runs via
+ WebAssembly (e.g. hosted on GitHub Pages), you can use this
+ approach to fetch data from the notebook's location.
+
+ ```python
+ import polars as pl
+
+ data_path = mo.notebook_location() / "public" / "data.csv"
+ df = pl.read_csv(data_path)
+ df.head()
+ ```
+
+ Returns:
+ pathlib.Path | None: A pathlib.Path object representing the URL or directory of the current
+ notebook, or None if the notebook's directory cannot be determined.
+ """
+ if is_pyodide():
+ from js import location # type: ignore
+
+ path_location = pathlib.Path(str(location))
+ # The location looks like https://marimo-team.github.io/marimo-gh-pages-template/notebooks/assets/worker-BxJ8HeOy.js
+ # We want to crawl out of the assets/ folder
+ if "assets" in path_location.parts:
+ return path_location.parent.parent
+ return path_location
+
+ else:
+ return notebook_dir()
+
+
@dataclasses.dataclass
class CellMetadata:
"""CellMetadata class for storing cell metadata.
diff --git a/tests/_ast/test_app.py b/tests/_ast/test_app.py
index f52502cc22..6ec2123d5a 100644
--- a/tests/_ast/test_app.py
+++ b/tests/_ast/test_app.py
@@ -508,6 +508,23 @@ class TestApp:
assert glbls["file"] == __file__
assert glbls["dirpath"] == pathlib.Path(glbls["file"]).parent
+ def test_notebook_location(self) -> None:
+ app = App()
+
+ @app.cell
+ def __():
+ import marimo as mo
+
+ dirpath = mo.notebook_dir()
+ location = mo.notebook_location()
+
+ _, glbls = app.run()
+ dirpath = glbls["dirpath"]
+ location = glbls["location"]
+ assert dirpath is not None
+ assert location is not None
+ assert dirpath == location
+
def test_app_config() -> None:
config = _AppConfig.from_untrusted_dict({"width": "full"})
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index 2139f7fbdb..df2b3eb5ab 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import sys
import textwrap
from dataclasses import dataclass
+from pathlib import Path
from typing import TYPE_CHECKING, Sequence
import pytest
@@ -1022,6 +1023,50 @@ class TestExecution:
assert "x" in k.globals
assert k.globals["x"] is None
+ async def test_notebook_location(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ await k.run(
+ [
+ exec_req.get("import marimo as mo"),
+ exec_req.get("loc = mo.notebook_location()"),
+ exec_req.get("dir = mo.notebook_dir()"),
+ ]
+ )
+ assert "loc" in k.globals
+ assert k.globals["loc"] is None
+ assert "dir" in k.globals
+ assert k.globals["dir"] is k.globals["loc"]
+
+ async def test_notebook_location_for_pyodide(
+ self, any_kernel: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ k = any_kernel
+ import sys
+ from types import ModuleType
+
+ # Mock pyodide and js modules
+ sys.modules["pyodide"] = ModuleType("pyodide")
+ js = ModuleType("js")
+ js.location = "https://marimo-team.github.io/marimo-gh-pages-template/notebooks/assets/worker-BxJ8HeOy.js"
+ sys.modules["js"] = js
+
+ try:
+ await k.run(
+ [
+ exec_req.get(
+ "import marimo as mo; loc = mo.notebook_location()"
+ )
+ ]
+ )
+ assert k.globals["loc"] == Path(
+ "https://marimo-team.github.io/marimo-gh-pages-template/notebooks"
+ )
+ finally:
+ del sys.modules["pyodide"]
+ del sys.modules["js"]
+
async def test_notebook_dir_for_unnamed_notebook(
self, tmp_path: pathlib.Path, exec_req: ExecReqProvider
) -> None: