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
user config: use TOML instead of Python (#86)
Akshay Agrawal29a67976942e
diff --git a/marimo/__init__.py b/marimo/__init__.pyindex db0f2b0938..120f860fae 100644--- a/marimo/__init__.py+++ b/marimo/__init__.py@@ -20,7 +20,6 @@ __all__ = ["audio","callout","center",- "config","defs","doc","download",@@ -41,7 +40,6 @@ __all__ = []__version__ = "0.1.5"-from marimo import configfrom marimo._ast.app import Appfrom marimo._output.doc import docfrom marimo._output.formatting import as_htmldiff --git a/marimo/_config/__init__.py b/marimo/_config/__init__.pynew file mode 100644index 0000000000..618f22fc54--- /dev/null+++ b/marimo/_config/__init__.py@@ -0,0 +1 @@+# Copyright 2023 Marimo. All rights reserved.diff --git a/marimo/config/_config.py b/marimo/_config/config.pysimilarity index 64%rename from marimo/config/_config.pyrename to marimo/_config/config.pyindex eb52c8f18e..e58112dea4 100644--- a/marimo/config/_config.py+++ b/marimo/_config/config.py@@ -87,7 +87,7 @@ class MarimoConfig(TypedDict, total=False):keymap: KeymapConfig-_DEFAULT_CONFIG: MarimoConfig = {+DEFAULT_CONFIG: MarimoConfig = {"completion": {"activate_on_typing": True},"save": {"autosave": "after_delay", "autosave_delay": 1000},"keymap": {"preset": "default"},@@ -100,68 +100,47 @@ ConfigType = TypeVar(# TODO(akshayka): Type-safety, can't index into TypedDict with nonliteral-def _merge_key(defaults: Any, override: Any, key: str, path: list[str]) -> Any:+def _merge_key(defaults: Any, override: Any, key: str) -> Any:if key not in defaults:- pathstr = " (" + ".".join(path + [key]) + ")" if path else ""- raise TypeError("Invalid setting in MarimoConfig: " + key + pathstr)+ # forward compatibility: old versions of marimo won't be aware of new+ # settings. Config might also have misspelled keys, but shouldn't fail+ # if that happens.+ return override[key]elif key not in override:return defaults[key]elif not isinstance(defaults[key], dict):return override[key]else:- return _merge_configs(defaults[key], override[key], path=path + [key])+ return _merge_configs(defaults[key], override[key])-def _merge_configs(- defaults: ConfigType, override: ConfigType, path: list[str]-) -> ConfigType:+def _merge_configs(defaults: ConfigType, override: ConfigType) -> ConfigType:return cast(ConfigType,{- key: _merge_key(defaults, override, key, path)+ key: _merge_key(defaults, override, key)for key in set(defaults.keys()).union(set(override.keys()))},)@mddoc-def configure(config: MarimoConfig) -> None:- """Configure the marimo editor.-- Place a call to this function in a file named `marimo.config.py`, and- marimo will use `config` to configure the editor.-- marimo searches for a config file from the directory in which it was- started back to the home directory, using the first file it finds.-- **Example.**-- To have autosave enabled and code completion activate automatically as you- type, create a file named `marimo.config.py` in your home directory and- paste the following code into it.-- ```python3- import marimo as mo--- mo.config.configure(- config={- # Automatically activate completions- "completion": {"activate_on_typing": True},- # Autosave after a delay of 1000ms- "save": {"autosave": "after_delay", "autosave_delay": 1000},- }- )- ```+def configure(config: MarimoConfig) -> MarimoConfig:+ """Configure the marimo editor with a user config.**Args.**- `config`: A configuration object."""global _USER_CONFIG- _USER_CONFIG = _merge_configs(_DEFAULT_CONFIG, config, [])+ # Robust merging of configs (want to merge on leaves, not just keys)+ _USER_CONFIG = cast(MarimoConfig, _merge_configs(DEFAULT_CONFIG, config))+ return _USER_CONFIGdef get_configuration() -> MarimoConfig:"""Return the current configuration."""- return _USER_CONFIG if _USER_CONFIG is not None else _DEFAULT_CONFIG+ return cast(+ MarimoConfig,+ _USER_CONFIG if _USER_CONFIG is not None else DEFAULT_CONFIG,+ )diff --git a/marimo/config/_utils.py b/marimo/_config/utils.pysimilarity index 80%rename from marimo/config/_utils.pyrename to marimo/_config/utils.pyindex 7d718d15c1..53c5c37612 100644--- a/marimo/config/_utils.py+++ b/marimo/_config/utils.py@@ -1,10 +1,11 @@# Copyright 2023 Marimo. All rights reserved.-import importlib.utilimport os-from typing import Optional+from typing import Optional, cast++import tomlkitfrom marimo import _loggers-from marimo.config._config import MarimoConfig, get_configuration+from marimo._config.config import MarimoConfig, configure, get_configurationLOGGER = _loggers.marimo_logger()@@ -28,7 +29,7 @@ def _check_directory_for_file(directory: str, filename: str) -> Optional[str]:def get_config_path() -> Optional[str]:- """Find path of config file (marimo.config.py).+ """Find path of config file (.marimo.toml).Searches from current directory to home, return the first config filefound, if Any.@@ -38,7 +39,7 @@ def get_config_path() -> Optional[str]:May raise an OSError."""- filename = "marimo.config.py"+ filename = ".marimo.toml"# we use os.path.realpath to canonicalize paths, just in case# some these functions don't eliminate symlinks on some platforms@@ -88,15 +89,14 @@ def load_config() -> Optional[MarimoConfig]:if path is not None:LOGGER.debug("Using config at %s", path)- spec = importlib.util.spec_from_file_location("marimo_config", path)- if spec is None:- raise RuntimeError("Failed to load module spec")- marimo_config = importlib.util.module_from_spec(spec)- if spec.loader is None:- raise RuntimeError("Failed to load module spec's loader")- # loaded module should modify global in `config` module by running- # `config.configure()`- spec.loader.exec_module(marimo_config)+ try:+ with open(path, "rb") as f:+ user_config = tomlkit.parse(f.read())+ except Exception as e:+ LOGGER.error("Failed to read user config at %s", path)+ LOGGER.error(str(e))+ return get_configuration()+ configure(cast(MarimoConfig, user_config))else:LOGGER.debug("No config found; loading default settings.")return get_configuration()diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.pyindex b483f11cfa..89a2016acc 100644--- a/marimo/_runtime/runtime.py+++ b/marimo/_runtime/runtime.py@@ -19,6 +19,7 @@ from typing import Any, Iterator, Optionalfrom marimo import _loggersfrom marimo._ast.cell import CellId_t, parse_cell+from marimo._config.config import configurefrom marimo._messaging.errors import (Error,MarimoAncestorStoppedError,@@ -61,7 +62,6 @@ from marimo._runtime.requests import ()from marimo._runtime.state import Statefrom marimo._runtime.validate_graph import check_for_errors-from marimo.config._config import configureLOGGER = _loggers.marimo_logger()diff --git a/marimo/_server/api/save_user_config.py b/marimo/_server/api/save_user_config.pyindex f11429a869..9b763caa43 100644--- a/marimo/_server/api/save_user_config.py+++ b/marimo/_server/api/save_user_config.py@@ -5,15 +5,16 @@ import osfrom dataclasses import dataclassfrom typing import Any+import tomlkitimport tornado.webfrom marimo import _loggers+from marimo._config.config import MarimoConfig, configure+from marimo._config.utils import get_config_pathfrom marimo._runtime import requestsfrom marimo._server import sessionsfrom marimo._server.api.model import parse_rawfrom marimo._server.api.status import HTTPStatus-from marimo.config._config import MarimoConfig, configure-from marimo.config._utils import get_config_pathLOGGER = _loggers.marimo_logger()@@ -57,21 +58,10 @@ class SaveUserConfigurationHandler(tornado.web.RequestHandler):else os.path.expanduser("~"))LOGGER.debug("Saving user configuration to %s", config_dir)- config_path = os.path.join(config_dir, "marimo.config.py")- file_contents = "\n".join(- [- "import marimo as mo",- "",- "mo.config.configure(",- f"{_INDENT}config="- + _format_configuration(args.config, depth=2),- ")",- ]- )-+ config_path = os.path.join(config_dir, ".marimo.toml")try:with open(config_path, "w", encoding="utf-8") as f:- f.write(file_contents)+ tomlkit.dump(args.config, f)except Exception as e:raise tornado.web.HTTPError(HTTPStatus.SERVER_ERROR,diff --git a/marimo/_server/server.py b/marimo/_server/server.pyindex 750a07ca77..b2650479bc 100644--- a/marimo/_server/server.py+++ b/marimo/_server/server.py@@ -30,10 +30,10 @@ import tornado.webimport tornado.websocketfrom marimo import _loggers+from marimo._config.config import get_configuration+from marimo._config.utils import load_configfrom marimo._server import api, sessionsfrom marimo._server.utils import TAB, print_tabbed-from marimo.config._config import get_configuration-from marimo.config._utils import load_configDEFAULT_PORT = 2718UTF8_SUPPORTED = Falsediff --git a/marimo/_tutorials/intro.py b/marimo/_tutorials/intro.pyindex 7489dad21a..d7519d5a9b 100644--- a/marimo/_tutorials/intro.py+++ b/marimo/_tutorials/intro.py@@ -1,7 +1,7 @@# Copyright 2023 Marimo. All rights reserved.import marimo-__generated_with = "0.0.6"+__generated_with = "0.1.5"app = marimo.App()@@ -359,8 +359,8 @@ def __():command line, e.g., `marimo edit app_name.py`.- _Save_ by clicking the save icon on the bottom left, or by- inputting `Ctrl/Cmd+s`. You can also configure marimo to- autosave.+ inputting `Ctrl/Cmd+s`. By default marimo is configured+ to autosave."""),"Running": (@@ -425,25 +425,9 @@ def __():"""),"Configuration": (- """- Configure the editor by creating a file called- `marimo.config.py` that includes a call to- `marimo.config.configure()`.-- _Example._-- ```python3- import marimo as mo-- mo.config.configure(- config={{- # Autocomplete- "completion": {{"activate_on_typing": True}},- # Enable autosave- "save": {{"autosave": "after_delay", "autosave_delay": 1000}},- }}- )- ```+ """+ Configure the editor by clicking the gears icon near the top-right+ of the screen."""),}diff --git a/marimo/config/__init__.py b/marimo/config/__init__.pydeleted file mode 100644index 97aa6205f3..0000000000--- a/marimo/config/__init__.py+++ /dev/null@@ -1,19 +0,0 @@-# Copyright 2023 Marimo. All rights reserved.-"""Configure the Marimo editor.--This module contains tools used to configure the editor.-"""--__all__ = [- "CompletionConfig",- "MarimoConfig",- "SaveConfig",- "configure",-]--from marimo.config._config import (- CompletionConfig,- MarimoConfig,- SaveConfig,- configure,-)diff --git a/pyproject.toml b/pyproject.tomlindex 14e82e7640..6d7d8e70b6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -19,6 +19,8 @@ dependencies = ["pymdown-extensions>=9.0,<11",# syntax highlighting of code in markdown"pygments>=2.3,<3",+ # for reading, writing configs+ "tomlkit>= 0.12.0",# web server"tornado>=6.1,<7",# python 3.8 compatibility