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: allow marimo configuration in notebook.py as script metadata (per PEP 723) (#3794)

Myles Scolnick73732d205e2c
diff --git a/docs/guides/configuration/index.md b/docs/guides/configuration/index.md
index cdea8c0aca..567e347926 100644
--- a/docs/guides/configuration/index.md
+++ b/docs/guides/configuration/index.md
@@ -87,6 +87,29 @@ default_width = "full"
You can override any user configuration setting in this way. To find these settings run `marimo config show`.
+!!! note "Overridden settings"
+ Settings overridden in `pyproject.toml` or script metadata cannot be changed through the marimo editor's settings menu. Any changes made to overridden settings in the editor will not take effect.
+
+### Script Metadata Configuration
+
+You can also configure marimo settings directly in your notebook files using script metadata (PEP 723). Add a `script` block at the top of your notebook:
+
+```python
+# /// script
+# [tool.marimo.runtime]
+# auto_instantiate = false
+# on_cell_change = "lazy"
+# [tool.marimo.display]
+# theme = "dark"
+# cell_output = "below"
+# ///
+```
+
+!!! note "Configuration precedence"
+ Script metadata configuration has the highest precedence, followed by `pyproject.toml` configuration, then user configuration:
+
+ **Script config > pyproject.toml config > user config**
+
## Environment Variables
marimo supports the following environment variables for advanced configuration:
diff --git a/docs/guides/configuration/theming.md b/docs/guides/configuration/theming.md
index da2aae8598..297d7c2c3c 100644
--- a/docs/guides/configuration/theming.md
+++ b/docs/guides/configuration/theming.md
@@ -47,6 +47,17 @@ You can further customize your notebook by adding custom HTML in the `<head>` se
See the [Custom HTML Head](html_head.md) guide for more details.
+## Forcing dark mode
+
+In order to force a theme for an application, you can override the marimo configuration specifically for an application using the script metadata. See the [Script Configuration](../configuration/index.md#script-metadata-configuration) for more details.
+
+```python
+# /// script
+# [tool.marimo.display]
+# theme = "dark"
+# ///
+```
+
## Targeting cells
You can target a cell's styles from the `data-cell-name` attribute. You can also target a cell's output with the `data-cell-role="output"` attribute.
diff --git a/examples/misc/custom_configuration.py b/examples/misc/custom_configuration.py
new file mode 100644
index 0000000000..72318f2b18
--- /dev/null
+++ b/examples/misc/custom_configuration.py
@@ -0,0 +1,43 @@
+# /// script
+# requires-python = ">=3.12"
+# dependencies = [
+# "marimo",
+# ]
+# [tool.marimo.runtime]
+# auto_instantiate = false
+# on_cell_change = "lazy"
+# [tool.marimo.display]
+# theme = "dark"
+# cell_output = "below"
+# ///
+import marimo
+
+__generated_with = "0.11.4"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+
+ return (mo,)
+
+
+def _(mo):
+ mo.md(
+ r"""
+ This is not auto-run because it has custom marimo configuration in the file header:
+
+ ```toml
+ [tool.marimo.runtime]
+ auto_instantiate = false
+ on_cell_change = "lazy"
+ ```
+ """
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/marimo/_cli/sandbox.py b/marimo/_cli/sandbox.py
index 8a305edba5..155b399d07 100644
--- a/marimo/_cli/sandbox.py
+++ b/marimo/_cli/sandbox.py
@@ -18,19 +18,16 @@ from marimo._cli.file_path import FileContentReader
from marimo._cli.print import bold, echo, green, muted
from marimo._config.settings import GLOBAL_SETTINGS
from marimo._dependencies.dependencies import DependencyManager
+from marimo._utils.scripts import read_pyproject_from_script
from marimo._utils.versions import is_editable
LOGGER = _loggers.marimo_logger()
-REGEX = (
- r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$"
-)
-
def _get_dependencies(script: str) -> List[str] | None:
"""Get dependencies from string representation of script."""
try:
- pyproject = _read_pyproject(script) or {}
+ pyproject = read_pyproject_from_script(script) or {}
return _pyproject_toml_to_requirements_txt(pyproject)
except Exception as e:
LOGGER.warning(f"Failed to parse dependencies: {e}")
@@ -121,32 +118,6 @@ def get_dependencies_from_filename(name: str) -> List[str]:
return []
-def _read_pyproject(script: str) -> Dict[str, Any] | None:
- """
- Read the pyproject.toml file from the script.
-
- Adapted from https://peps.python.org/pep-0723/#reference-implementation
- """
- name = "script"
- matches = list(
- filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
- )
- if len(matches) > 1:
- raise ValueError(f"Multiple {name} blocks found")
- elif len(matches) == 1:
- content = "".join(
- line[2:] if line.startswith("# ") else line[1:]
- for line in matches[0].group("content").splitlines(keepends=True)
- )
- import tomlkit
-
- pyproject = tomlkit.parse(content)
-
- return pyproject
- else:
- return None
-
-
def _get_python_version_requirement(
pyproject: Dict[str, Any] | None,
) -> str | None:
@@ -287,7 +258,7 @@ def construct_uv_command(args: list[str], name: str | None) -> list[str]:
# Get Python version requirement if available
if name is not None and os.path.exists(name):
contents, _ = FileContentReader().read_file(name)
- pyproject = _read_pyproject(contents)
+ pyproject = read_pyproject_from_script(contents)
python_version = (
_get_python_version_requirement(pyproject)
if pyproject is not None
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index a078663269..9520e9e194 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -12,7 +12,16 @@ if sys.version_info < (3, 11):
else:
from typing import NotRequired
-from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
+from typing import (
+ Any,
+ Dict,
+ List,
+ Literal,
+ Optional,
+ TypedDict,
+ Union,
+ cast,
+)
from marimo._output.rich_help import mddoc
from marimo._utils.deep_merge import deep_merge
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 33c52d9e24..829d1756fb 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import os
from abc import abstractmethod
+from pathlib import Path
from typing import Optional, Union, cast
from marimo import _loggers
@@ -13,8 +14,16 @@ from marimo._config.config import (
merge_config,
merge_default_config,
)
-from marimo._config.reader import read_marimo_config, read_pyproject_config
-from marimo._config.secrets import mask_secrets, remove_secret_placeholders
+from marimo._config.reader import (
+ get_marimo_config_from_pyproject_dict,
+ read_marimo_config,
+ read_pyproject_marimo_config,
+)
+from marimo._config.secrets import (
+ mask_secrets,
+ mask_secrets_partial,
+ remove_secret_placeholders,
+)
from marimo._config.utils import (
get_or_create_user_config_path,
)
@@ -25,12 +34,23 @@ LOGGER = _loggers.marimo_logger()
def get_default_config_manager(
*, current_path: Optional[str]
) -> MarimoConfigManager:
+ """
+ Get the default config manager
+
+ Args:
+ current_path: The current path of the notebook, or a directory.
+ If the current path is a notebook, the config manager will read the
+ project configuration from the notebook following PEP 723.
+ """
# Current path should be the notebook file
# If it's not known, use the current working directory
if current_path is None:
current_path = os.getcwd()
+
return MarimoConfigManager(
- UserConfigManager(), ProjectConfigManager(current_path)
+ UserConfigManager(),
+ ProjectConfigManager(current_path),
+ ScriptConfigManager(current_path),
)
@@ -110,7 +130,7 @@ class ProjectConfigManager(PartialMarimoConfigReader):
def get_config(self, *, hide_secrets: bool = True) -> PartialMarimoConfig:
try:
- project_config = read_pyproject_config(self.start_path)
+ project_config = read_pyproject_marimo_config(self.start_path)
if project_config is None:
return {}
except Exception as e:
@@ -118,10 +138,50 @@ class ProjectConfigManager(PartialMarimoConfigReader):
return {}
if hide_secrets:
- return cast(PartialMarimoConfig, mask_secrets(project_config))
+ return mask_secrets_partial(project_config)
return project_config
+class ScriptConfigManager(PartialMarimoConfigReader):
+ """Read the script configuration following PEP 723
+
+ This looks like a pyproject.toml serialized as a comment in the header
+ of the script.
+ """
+
+ def __init__(self, filename: Optional[str]) -> None:
+ self.filename = filename
+
+ def get_config(self, *, hide_secrets: bool = True) -> PartialMarimoConfig:
+ if self.filename is None:
+ return {}
+ try:
+ filepath = Path(self.filename)
+ if not filepath.is_file():
+ return {}
+
+ from marimo._utils.scripts import read_pyproject_from_script
+
+ script_content = filepath.read_text()
+ script_config = read_pyproject_from_script(script_content)
+ if script_config is None:
+ return {}
+
+ marimo_config = get_marimo_config_from_pyproject_dict(
+ script_config
+ )
+ if marimo_config is None:
+ return {}
+
+ except Exception as e:
+ LOGGER.warning("Failed to read script config: %s", e)
+ return {}
+
+ if hide_secrets:
+ return mask_secrets_partial(marimo_config)
+ return marimo_config
+
+
class UserConfigManager(MarimoConfigReader):
"""Read and write the user configuration"""
@@ -194,7 +254,5 @@ class MarimoConfigReaderWithOverrides(PartialMarimoConfigReader):
def get_config(self, *, hide_secrets: bool = True) -> PartialMarimoConfig:
if hide_secrets:
- return cast(
- PartialMarimoConfig, mask_secrets(self.override_config)
- )
+ return mask_secrets_partial(self.override_config)
return self.override_config
diff --git a/marimo/_config/reader.py b/marimo/_config/reader.py
index 675cd3f412..65135f356e 100644
--- a/marimo/_config/reader.py
+++ b/marimo/_config/reader.py
@@ -1,6 +1,8 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
from pathlib import Path
-from typing import Optional, Union, cast
+from typing import Any, Optional, Union, cast
from marimo import _loggers
from marimo._config.config import PartialMarimoConfig
@@ -14,15 +16,28 @@ def read_marimo_config(path: str) -> PartialMarimoConfig:
return cast(PartialMarimoConfig, read_toml(path))
-def read_pyproject_config(
+def read_pyproject_marimo_config(
start_path: Union[str, Path],
) -> Optional[PartialMarimoConfig]:
- """Read the pyproject.toml configuration."""
+ """Find the nearest pyproject.toml file, then read the marimo tool config."""
path = find_nearest_pyproject_toml(start_path)
if path is None:
return None
pyproject_config = read_toml(path)
- marimo_tool_config = pyproject_config.get("tool", {}).get("marimo", None)
+ marimo_tool_config = get_marimo_config_from_pyproject_dict(
+ pyproject_config
+ )
+ if marimo_tool_config is None:
+ return None
+ LOGGER.debug("Found marimo config in pyproject.toml at %s", path)
+ return marimo_tool_config
+
+
+def get_marimo_config_from_pyproject_dict(
+ pyproject_dict: dict[str, Any],
+) -> Optional[PartialMarimoConfig]:
+ """Get the marimo config from a pyproject.toml dictionary."""
+ marimo_tool_config = pyproject_dict.get("tool", {}).get("marimo", None)
if marimo_tool_config is None:
return None
if not isinstance(marimo_tool_config, dict):
@@ -31,7 +46,6 @@ def read_pyproject_config(
marimo_tool_config,
)
return None
- LOGGER.debug("Found marimo config in pyproject.toml at %s", path)
return cast(PartialMarimoConfig, marimo_tool_config)
diff --git a/marimo/_config/secrets.py b/marimo/_config/secrets.py
index 7508657b4f..2fae03f564 100644
--- a/marimo/_config/secrets.py
+++ b/marimo/_config/secrets.py
@@ -1,15 +1,21 @@
# Copyright 2024 Marimo. All rights reserved.
-from typing import Any, Dict, TypeVar, Union, cast
+from __future__ import annotations
+
+from typing import Any, Dict, TypeVar, cast
from marimo._config.config import MarimoConfig, PartialMarimoConfig
from marimo._config.utils import deep_copy
SECRET_PLACEHOLDER = "********"
+# TODO: mypy doesn't like using @overload here
+
+
+def mask_secrets_partial(config: PartialMarimoConfig) -> PartialMarimoConfig:
+ return cast(PartialMarimoConfig, mask_secrets(cast(MarimoConfig, config)))
+
-def mask_secrets(
- config: Union[MarimoConfig, PartialMarimoConfig],
-) -> MarimoConfig:
+def mask_secrets(config: MarimoConfig) -> MarimoConfig:
def deep_remove_from_path(path: list[str], obj: Dict[str, Any]) -> None:
key = path[0]
if key not in obj:
diff --git a/marimo/_utils/scripts.py b/marimo/_utils/scripts.py
new file mode 100644
index 0000000000..1ab400b0cd
--- /dev/null
+++ b/marimo/_utils/scripts.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+import re
+from typing import Any
+
+REGEX = (
+ r"(?m)^# /// (?P<type>[a-zA-Z0-9-]+)$\s(?P<content>(^#(| .*)$\s)+)^# ///$"
+)
+
+
+def read_pyproject_from_script(script: str) -> dict[str, Any] | None:
+ """
+ Read the pyproject.toml file from the script.
+
+ Adapted from https://peps.python.org/pep-0723/#reference-implementation
+ """
+ name = "script"
+ matches = list(
+ filter(lambda m: m.group("type") == name, re.finditer(REGEX, script))
+ )
+ if len(matches) > 1:
+ raise ValueError(f"Multiple {name} blocks found")
+ elif len(matches) == 1:
+ content = "".join(
+ line[2:] if line.startswith("# ") else line[1:]
+ for line in matches[0].group("content").splitlines(keepends=True)
+ )
+ import tomlkit
+
+ pyproject = tomlkit.parse(content)
+
+ return pyproject
+ else:
+ return None
diff --git a/tests/_cli/test_sandbox.py b/tests/_cli/test_sandbox.py
index f6735f1d98..a882e3c71f 100644
--- a/tests/_cli/test_sandbox.py
+++ b/tests/_cli/test_sandbox.py
@@ -11,10 +11,10 @@ from marimo._cli.sandbox import (
_is_marimo_dependency,
_normalize_sandbox_dependencies,
_pyproject_toml_to_requirements_txt,
- _read_pyproject,
construct_uv_command,
get_dependencies_from_filename,
)
+from marimo._utils.scripts import read_pyproject_from_script
def test_get_dependencies():
@@ -222,7 +222,7 @@ import marimo
"""
assert _get_dependencies(SCRIPT) == ["polars"]
- pyproject = _read_pyproject(SCRIPT)
+ pyproject = read_pyproject_from_script(SCRIPT)
assert pyproject is not None
assert _get_python_version_requirement(pyproject) == ">=3.11"
@@ -233,7 +233,7 @@ import marimo
import marimo
"""
- pyproject_no_python = _read_pyproject(SCRIPT_NO_PYTHON)
+ pyproject_no_python = read_pyproject_from_script(SCRIPT_NO_PYTHON)
assert pyproject_no_python is not None
assert _get_python_version_requirement(pyproject_no_python) is None
assert _get_dependencies(SCRIPT_NO_PYTHON) == ["polars"]
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index f190ed1ab9..f6b04d09a5 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -1,17 +1,22 @@
from __future__ import annotations
+import textwrap
from functools import wraps
-from typing import Any, Callable, TypeVar
+from typing import TYPE_CHECKING, Any, Callable, TypeVar
from unittest.mock import patch
from marimo._config.config import PartialMarimoConfig, merge_default_config
from marimo._config.manager import (
MarimoConfigManager,
MarimoConfigReaderWithOverrides,
+ ScriptConfigManager,
UserConfigManager,
get_default_config_manager,
)
+if TYPE_CHECKING:
+ from pathlib import Path
+
F = TypeVar("F", bound=Callable[..., Any])
@@ -131,3 +136,106 @@ def test_get_config_with_override() -> None:
}
)
assert manager.get_config()["runtime"]["auto_reload"] == "lazy"
+
+
+def test_project_config_manager_with_script_metadata(tmp_path: Path) -> None:
+ # Create a notebook file with script metadata
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # requires-python = ">=3.11"
+ # dependencies = ["polars"]
+ # [tool.marimo]
+ # formatting = {line_length = 79}
+ # [tool.marimo.save]
+ # autosave_delay = 1000
+ # ///
+
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ # Create a pyproject.toml file
+ pyproject_path = tmp_path / "pyproject.toml"
+ pyproject_content = """
+ [tool.marimo]
+ formatting = {line_length = 100}
+ [tool.marimo.save]
+ format_on_save = true
+ autosave = "after_delay"
+ """
+ pyproject_path.write_text(textwrap.dedent(pyproject_content))
+
+ # Initialize ProjectConfigManager with the notebook path
+ manager = get_default_config_manager(current_path=str(notebook_path))
+ config = manager.get_config_overrides(hide_secrets=False)
+
+ # Verify that script metadata takes precedence over pyproject.toml
+ assert config == {
+ "formatting": {"line_length": 79}, # From script metadata
+ "save": {
+ "autosave_delay": 1000, # From script metadata
+ "format_on_save": True, # From pyproject.toml
+ "autosave": "after_delay", # From pyproject.toml
+ },
+ }
+
+
+def test_script_config_manager_empty_file(tmp_path: Path) -> None:
+ notebook_path = tmp_path / "notebook.py"
+ notebook_path.write_text("import marimo as mo")
+
+ manager = ScriptConfigManager(str(notebook_path))
+ assert manager.get_config() == {}
+
+
+def test_script_config_manager_no_file() -> None:
+ manager = ScriptConfigManager(None)
+ assert manager.get_config() == {}
+
+
+def test_script_config_manager_with_metadata(tmp_path: Path) -> None:
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [tool.marimo]
+ # formatting = {line_length = 79}
+ # [tool.marimo.save]
+ # autosave_delay = 1000
+ # ///
+ import marimo as mo
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ manager = ScriptConfigManager(str(notebook_path))
+ assert manager.get_config() == {
+ "formatting": {"line_length": 79},
+ "save": {"autosave_delay": 1000},
+ }
+
+
+def test_script_config_manager_invalid_toml(tmp_path: Path) -> None:
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [invalid toml
+ # ///
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ manager = ScriptConfigManager(str(notebook_path))
+ assert manager.get_config() == {}
+
+
+def test_script_config_manager_no_marimo_section(tmp_path: Path) -> None:
+ notebook_path = tmp_path / "notebook.py"
+ notebook_content = """
+ # /// script
+ # [tool.other]
+ # key = "value"
+ # ///
+ """
+ notebook_path.write_text(textwrap.dedent(notebook_content))
+
+ manager = ScriptConfigManager(str(notebook_path))
+ assert manager.get_config() == {}
diff --git a/tests/_config/test_reader.py b/tests/_config/test_reader.py
index a03276d1a3..8716c7a050 100644
--- a/tests/_config/test_reader.py
+++ b/tests/_config/test_reader.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
import os
import tempfile
from pathlib import Path
@@ -8,7 +10,7 @@ import pytest
from marimo._config.reader import (
find_nearest_pyproject_toml,
read_marimo_config,
- read_pyproject_config,
+ read_pyproject_marimo_config,
read_toml,
)
@@ -67,7 +69,7 @@ def test_read_pyproject_config_with_marimo_section():
"marimo._config.reader.find_nearest_pyproject_toml"
) as mock_find:
mock_find.return_value = Path("/some/path/pyproject.toml")
- result = read_pyproject_config("/some/path")
+ result = read_pyproject_marimo_config("/some/path")
assert result == {
"formatting": {"line_length": 79},
"save": {
@@ -89,7 +91,7 @@ def test_read_pyproject_config_without_marimo_section():
"marimo._config.reader.find_nearest_pyproject_toml"
) as mock_find:
mock_find.return_value = Path("/some/path/pyproject.toml")
- result = read_pyproject_config("/some/path")
+ result = read_pyproject_marimo_config("/some/path")
assert result is None
@@ -103,13 +105,13 @@ def test_read_pyproject_config_invalid_marimo_section():
"marimo._config.reader.find_nearest_pyproject_toml"
) as mock_find:
mock_find.return_value = Path("/some/path/pyproject.toml")
- result = read_pyproject_config("/some/path")
+ result = read_pyproject_marimo_config("/some/path")
assert result is None
def test_read_pyproject_config_no_file():
with tempfile.TemporaryDirectory() as temp_dir:
- result = read_pyproject_config(temp_dir)
+ result = read_pyproject_marimo_config(temp_dir)
assert result is None
diff --git a/tests/_utils/test_scripts.py b/tests/_utils/test_scripts.py
new file mode 100644
index 0000000000..fc222c15c7
--- /dev/null
+++ b/tests/_utils/test_scripts.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import textwrap
+
+import pytest
+
+from marimo._utils.scripts import read_pyproject_from_script
+
+
+def test_read_pyproject_from_script():
+ script = textwrap.dedent(
+ """
+ # /// script
+ # requires-python = ">=3.11"
+ # dependencies = ["polars"]
+ # [tool.marimo]
+ # formatting = {line_length = 79}
+ # ///
+
+ import marimo
+ """
+ )
+
+ pyproject = read_pyproject_from_script(script)
+ assert pyproject is not None
+ assert pyproject["requires-python"] == ">=3.11"
+ assert pyproject["dependencies"] == ["polars"]
+ assert pyproject["tool"]["marimo"]["formatting"]["line_length"] == 79
+
+ # Test no script block
+ script = "import marimo"
+ assert read_pyproject_from_script(script) is None
+
+ # Test multiple script blocks
+ script = textwrap.dedent(
+ """
+ # /// script
+ # requires-python = ">=3.11"
+ # ///
+
+ # /// script
+ # dependencies = ["polars"]
+ # ///
+ """
+ )
+ with pytest.raises(ValueError, match="Multiple script blocks found"):
+ read_pyproject_from_script(script)
+
+ # Test invalid TOML
+ script = textwrap.dedent(
+ """
+ # /// script
+ # invalid toml content
+ # ///
+ """
+ )
+ with pytest.raises(ValueError):
+ read_pyproject_from_script(script)
+
+
+def test_read_marimo_config_from_script():
+ script = textwrap.dedent(
+ """
+ # /// script
+ # [tool.marimo.runtime]
+ # watcher_on_save = "autorun"
+ # auto_instantiate = true
+ # [tool.marimo.display]
+ # cell_output = "above"
+ # ///
+ """
+ )
+ config = read_pyproject_from_script(script)
+ assert config is not None
+ assert config["tool"]["marimo"]["runtime"]["auto_instantiate"] is True
+ assert config["tool"]["marimo"]["runtime"]["watcher_on_save"] == "autorun"
+ assert config["tool"]["marimo"]["display"]["cell_output"] == "above"