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: better fallback for notebook_dir (#3767)

Myles Scolnick196343e9866b
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 6b1668e9d0..993a8cedbf 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -324,11 +324,14 @@ def notebook_dir() -> pathlib.Path | None:
try:
ctx = get_context()
except ContextNotInitializedError:
- return None
+ # If we are not running in a notebook (e.g. exported to Jupyter),
+ # return the current working directory
+ return pathlib.Path().absolute()
filename = ctx.filename
if filename is not None:
return pathlib.Path(filename).parent.absolute()
+
return None
@@ -380,10 +383,7 @@ def notebook_location() -> pathlib.PurePath | None:
return URLPath(str(path_location))
else:
- nb_dir = notebook_dir()
- if nb_dir is not None:
- return nb_dir
- return None
+ return notebook_dir()
@dataclasses.dataclass
diff --git a/tests/_runtime/test_runtime.py b/tests/_runtime/test_runtime.py
index b87daebbe9..8d67f79969 100644
--- a/tests/_runtime/test_runtime.py
+++ b/tests/_runtime/test_runtime.py
@@ -1,10 +1,11 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+import pathlib
import sys
import textwrap
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Sequence
+from typing import Sequence
import pytest
@@ -37,15 +38,12 @@ from marimo._runtime.requests import (
SetCellConfigRequest,
SetUIElementValueRequest,
)
-from marimo._runtime.runtime import Kernel
+from marimo._runtime.runtime import Kernel, notebook_dir, notebook_location
from marimo._runtime.scratch import SCRATCH_CELL_ID
from marimo._server.model import SessionMode
from marimo._utils.parse_dataclass import parse_raw
from tests.conftest import ExecReqProvider, MockedKernel
-if TYPE_CHECKING:
- import pathlib
-
def _check_edges(error: Error, expected_edges: Sequence[EdgeWithVar]) -> None:
assert isinstance(error, CycleError)
@@ -2804,6 +2802,11 @@ class TestErrorHandling:
assert errors[0].msg.startswith("An internal error occurred: ")
+def test_notebook_dir_in_non_notebook_mode() -> None:
+ assert notebook_dir() == pathlib.Path().absolute()
+ assert notebook_location() == pathlib.Path().absolute()
+
+
def _parse_error_output(cell_op: CellOp) -> list[Error]:
error_output = cell_op.output
assert error_output is not None