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: typings of marimo config, fix typedict to openapi cases (#2519)

Myles Scolnick53a50c102519
diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx
index 434848cdfe..c64d237944 100644
--- a/frontend/src/components/editor/cell/code/cell-editor.tsx
+++ b/frontend/src/components/editor/cell/code/cell-editor.tsx
@@ -194,7 +194,7 @@ const CellEditorInternal = ({
completionConfig: userConfig.completion,
keymapConfig: userConfig.keymap,
theme,
- hotkeys: new OverridingHotkeyProvider(userConfig.keymap.overrides),
+ hotkeys: new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),
});
extensions.push(
@@ -268,7 +268,7 @@ const CellEditorInternal = ({
reconfigureLanguageEffect(
editorViewRef.current,
userConfig.completion,
- new OverridingHotkeyProvider(userConfig.keymap.overrides),
+ new OverridingHotkeyProvider(userConfig.keymap.overrides ?? {}),
),
],
});
diff --git a/frontend/src/core/config/config.ts b/frontend/src/core/config/config.ts
index 00cbccd6f4..50e058e946 100644
--- a/frontend/src/core/config/config.ts
+++ b/frontend/src/core/config/config.ts
@@ -19,7 +19,7 @@ export const autoInstantiateAtom = atom((get) => {
});
export const hotkeyOverridesAtom = atom((get) => {
- return get(userConfigAtom).keymap.overrides;
+ return get(userConfigAtom).keymap.overrides ?? {};
});
export const hotkeysAtom = atom((get) => {
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index 4c569d3680..20e9ba4bf9 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -33,6 +33,7 @@ function setFeatureFlag(
value: boolean,
) {
const userConfig = getUserConfig();
+ userConfig.experimental = userConfig.experimental ?? {};
userConfig.experimental[feature] = value;
saveUserConfig({ config: userConfig });
}
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 78c7a5eb87..2d441a57ab 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import sys
from dataclasses import dataclass
+from typing import TypeVar
if sys.version_info < (3, 11):
from typing_extensions import NotRequired
@@ -54,7 +55,7 @@ class SaveConfig(TypedDict):
@mddoc
@dataclass
-class KeymapConfig(TypedDict, total=False):
+class KeymapConfig(TypedDict):
"""Configuration for keymaps.
**Keys.**
@@ -64,7 +65,7 @@ class KeymapConfig(TypedDict, total=False):
"""
preset: Literal["default", "vim"]
- overrides: Dict[str, str]
+ overrides: NotRequired[Dict[str, str]]
OnCellChangeType = Literal["lazy", "autorun"]
@@ -166,7 +167,7 @@ class PackageManagementConfig(TypedDict):
@dataclass
-class AiConfig(TypedDict):
+class AiConfig(TypedDict, total=False):
"""Configuration options for AI.
**Keys.**
@@ -182,7 +183,7 @@ class AiConfig(TypedDict):
@dataclass
-class OpenAiConfig(TypedDict):
+class OpenAiConfig(TypedDict, total=False):
"""Configuration options for OpenAI or OpenAI-compatible services.
**Keys.**
@@ -199,7 +200,7 @@ class OpenAiConfig(TypedDict):
@dataclass
-class AnthropicConfig(TypedDict):
+class AnthropicConfig(TypedDict, total=False):
"""Configuration options for Anthropic.
**Keys.**
@@ -211,7 +212,7 @@ class AnthropicConfig(TypedDict):
@dataclass
-class GoogleAiConfig(TypedDict):
+class GoogleAiConfig(TypedDict, total=False):
"""Configuration options for Google AI.
**Keys.**
@@ -239,6 +240,23 @@ class MarimoConfig(TypedDict):
experimental: NotRequired[Dict[str, Any]]
+@mddoc
+@dataclass
+class PartialMarimoConfig(TypedDict, total=False):
+ """Partial configuration for the marimo editor"""
+
+ completion: CompletionConfig
+ display: DisplayConfig
+ formatting: FormattingConfig
+ keymap: KeymapConfig
+ runtime: RuntimeConfig
+ save: SaveConfig
+ server: ServerConfig
+ package_management: PackageManagementConfig
+ ai: NotRequired[AiConfig]
+ experimental: NotRequired[Dict[str, Any]]
+
+
DEFAULT_CONFIG: MarimoConfig = {
"completion": {"activate_on_typing": True, "copilot": False},
"display": {
@@ -268,13 +286,15 @@ DEFAULT_CONFIG: MarimoConfig = {
}
-def merge_default_config(config: MarimoConfig) -> MarimoConfig:
+def merge_default_config(
+ config: PartialMarimoConfig | MarimoConfig,
+) -> MarimoConfig:
"""Merge a user configuration with the default configuration."""
return merge_config(DEFAULT_CONFIG, config)
def merge_config(
- config: MarimoConfig, new_config: MarimoConfig
+ config: MarimoConfig, new_config: PartialMarimoConfig | MarimoConfig
) -> MarimoConfig:
"""Merge a user configuration with a new configuration."""
# Remove the keymap overrides from the incoming config,
@@ -319,7 +339,7 @@ def _deep_copy(obj: Any) -> Any:
SECRET_PLACEHOLDER = "********"
-def mask_secrets(config: MarimoConfig) -> MarimoConfig:
+def mask_secrets(config: MarimoConfig | PartialMarimoConfig) -> MarimoConfig:
def deep_remove_from_path(path: list[str], obj: Dict[str, Any]) -> None:
key = path[0]
if key not in obj:
@@ -343,7 +363,10 @@ def mask_secrets(config: MarimoConfig) -> MarimoConfig:
return new_config # type: ignore
-def remove_secret_placeholders(config: MarimoConfig) -> MarimoConfig:
+T = TypeVar("T")
+
+
+def remove_secret_placeholders(config: T) -> T:
def deep_remove(obj: Any) -> Any:
if isinstance(obj, dict):
# Filter all keys with value SECRET_PLACEHOLDER
diff --git a/marimo/_config/manager.py b/marimo/_config/manager.py
index 0827b69fb3..1b31140d34 100644
--- a/marimo/_config/manager.py
+++ b/marimo/_config/manager.py
@@ -6,6 +6,7 @@ from typing import Optional
from marimo import _loggers
from marimo._config.config import (
MarimoConfig,
+ PartialMarimoConfig,
mask_secrets,
merge_config,
merge_default_config,
@@ -24,7 +25,9 @@ class UserConfigManager:
self._config_path = config_path
self.config = load_config()
- def save_config(self, config: MarimoConfig) -> MarimoConfig:
+ def save_config(
+ self, config: MarimoConfig | PartialMarimoConfig
+ ) -> MarimoConfig:
import tomlkit
config_path = self.get_config_path()
diff --git a/marimo/_config/utils.py b/marimo/_config/utils.py
index 0c250a3622..4393930ca5 100644
--- a/marimo/_config/utils.py
+++ b/marimo/_config/utils.py
@@ -8,6 +8,7 @@ from marimo import _loggers
from marimo._config.config import (
DEFAULT_CONFIG,
MarimoConfig,
+ PartialMarimoConfig,
merge_default_config,
)
@@ -139,7 +140,7 @@ def load_config() -> MarimoConfig:
LOGGER.error("Failed to read user config at %s", path)
LOGGER.error(str(e))
return DEFAULT_CONFIG
- return merge_default_config(cast(MarimoConfig, user_config))
+ return merge_default_config(cast(PartialMarimoConfig, user_config))
else:
LOGGER.debug("No config found; loading default settings.")
return DEFAULT_CONFIG
diff --git a/marimo/_utils/dataclass_to_openapi.py b/marimo/_utils/dataclass_to_openapi.py
index 15105bba26..41aabe6283 100644
--- a/marimo/_utils/dataclass_to_openapi.py
+++ b/marimo/_utils/dataclass_to_openapi.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import dataclasses
import datetime
+import sys
from collections.abc import Mapping, Sequence
from decimal import Decimal
from enum import Enum
@@ -22,7 +23,11 @@ from typing import (
)
from marimo._server.models.base import to_camel_case
-from marimo._utils.typing import NotRequired
+
+if sys.version_info < (3, 11):
+ from typing_extensions import NotRequired
+else:
+ from typing import NotRequired
class PythonTypeToOpenAPI:
@@ -134,6 +139,40 @@ class PythonTypeToOpenAPI:
self.convert(arg, processed_classes) for arg in args
],
}
+ elif is_typeddict_subclass(py_type):
+ if py_type in processed_classes:
+ ref = processed_classes[py_type]
+ return {"$ref": f"#/components/schemas/{ref}"}
+
+ properties: dict[str, Any] = {}
+ required: list[str] = []
+ annotations = py_type.__annotations__
+ for key, value in get_type_hints(py_type).items():
+ properties[to_camel_case(key) if self.camel_case else key] = (
+ self.convert(value, processed_classes)
+ )
+ annotation = annotations[key]
+ if "NotRequired[" not in str(annotation):
+ required.append(
+ to_camel_case(key) if self.camel_case else key
+ )
+
+ # Optional keys come from TypedDict(total=False)
+ optional_keys = py_type.__optional_keys__
+ # Remove any keys that are optional
+ required = [key for key in required if key not in optional_keys]
+
+ schema: Dict[str, Any] = {
+ "type": "object",
+ "properties": properties,
+ }
+ if required:
+ schema["required"] = required
+
+ schema_name = self.name_overrides.get(py_type, py_type.__name__)
+ processed_classes[py_type] = schema_name
+
+ return schema
elif dataclasses.is_dataclass(py_type):
return self.convert_dataclass(py_type, processed_classes)
elif py_type is Any:
@@ -257,4 +296,16 @@ def _is_optional(field: dataclasses.Field[Any]) -> bool:
"""
Check if a field is Optional
"""
- return get_origin(field) is Union and type(None) in get_args(field)
+ return (get_origin(field) is Union and type(None) in get_args(field)) or (
+ get_origin(field) is NotRequired
+ )
+
+
+def is_typeddict_subclass(cls: Any) -> bool:
+ return (
+ isinstance(cls, type)
+ and issubclass(cls, dict)
+ and hasattr(cls, "__annotations__")
+ and hasattr(cls, "__total__")
+ and isinstance(cls.__total__, bool) # ignore
+ )
diff --git a/openapi/api.yaml b/openapi/api.yaml
index 05e7b0e7b4..e6b052c32f 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -1034,15 +1034,11 @@ components:
properties:
api_key:
type: string
- required:
- - api_key
type: object
google:
properties:
api_key:
type: string
- required:
- - api_key
type: object
open_ai:
properties:
@@ -1052,15 +1048,7 @@ components:
type: string
model:
type: string
- required:
- - api_key
- - model
- - base_url
type: object
- required:
- - open_ai
- - anthropic
- - google
type: object
completion:
properties:
@@ -1137,7 +1125,6 @@ components:
type: string
required:
- preset
- - overrides
type: object
package_management:
properties:
@@ -1211,8 +1198,6 @@ components:
- save
- server
- package_management
- - ai
- - experimental
type: object
MarimoExceptionRaisedError:
properties:
@@ -1919,7 +1904,7 @@ components:
type: object
info:
title: marimo API
- version: 0.8.22
+ version: 0.9.1
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 0cb9c0108c..f64657d67c 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -2385,17 +2385,17 @@ export interface components {
type: "ancestor-stopped";
};
MarimoConfig: {
- ai: {
- anthropic: {
- api_key: string;
+ ai?: {
+ anthropic?: {
+ api_key?: string;
};
- google: {
- api_key: string;
+ google?: {
+ api_key?: string;
};
- open_ai: {
- api_key: string;
- base_url: string;
- model: string;
+ open_ai?: {
+ api_key?: string;
+ base_url?: string;
+ model?: string;
};
};
completion: {
@@ -2414,14 +2414,14 @@ export interface components {
/** @enum {string} */
theme: "light" | "dark" | "system";
};
- experimental: {
+ experimental?: {
[key: string]: unknown;
};
formatting: {
line_length: number;
};
keymap: {
- overrides: {
+ overrides?: {
[key: string]: string;
};
/** @enum {string} */
diff --git a/tests/_config/test_config.py b/tests/_config/test_config.py
index dcbbac29d5..4d421b7485 100644
--- a/tests/_config/test_config.py
+++ b/tests/_config/test_config.py
@@ -11,6 +11,7 @@ from unittest import mock
from marimo._config.config import (
DEFAULT_CONFIG,
MarimoConfig,
+ PartialMarimoConfig,
mask_secrets,
merge_config,
merge_default_config,
@@ -19,18 +20,20 @@ from marimo._config.config import (
from marimo._config.utils import get_config_path, get_or_create_config_path
-def assert_config(override: MarimoConfig) -> None:
+def assert_config(override: MarimoConfig | PartialMarimoConfig) -> None:
user_config = merge_default_config(override)
assert user_config == {**DEFAULT_CONFIG, **override}
def test_configure_partial_keymap() -> None:
- assert_config(MarimoConfig(keymap={"preset": "vim", "overrides": {}}))
+ assert_config(
+ PartialMarimoConfig(keymap={"preset": "vim", "overrides": {}})
+ )
def test_configure_full() -> None:
assert_config(
- MarimoConfig(
+ PartialMarimoConfig(
completion={"activate_on_typing": False, "copilot": False},
save={
"autosave": "after_delay",
@@ -51,7 +54,7 @@ def test_configure_unknown() -> None:
def test_merge_config() -> None:
prev_config = merge_default_config(
- MarimoConfig(
+ PartialMarimoConfig(
ai={
"open_ai": {
"api_key": "super_secret",
@@ -67,13 +70,13 @@ def test_merge_config() -> None:
new_config = merge_config(
prev_config,
- MarimoConfig(
+ PartialMarimoConfig(
ai={
"open_ai": {
"model": "davinci",
},
"google": {
- "model": "gemini-1.5-pro",
+ "api_key": "google_secret",
},
},
),
@@ -82,12 +85,11 @@ def test_merge_config() -> None:
assert new_config["ai"]["open_ai"]["api_key"] == "super_secret"
assert new_config["ai"]["open_ai"]["model"] == "davinci"
assert new_config["ai"]["google"]["api_key"] == "google_secret"
- assert new_config["ai"]["google"]["model"] == "gemini-1.5-pro"
def test_merge_config_with_keymap_overrides() -> None:
prev_config = merge_default_config(
- MarimoConfig(
+ PartialMarimoConfig(
keymap={
"preset": "default",
"overrides": {
@@ -96,12 +98,14 @@ def test_merge_config_with_keymap_overrides() -> None:
},
)
)
+ assert "preset" in prev_config["keymap"]
+ assert "overrides" in prev_config["keymap"]
assert prev_config["keymap"]["preset"] == "default"
assert prev_config["keymap"]["overrides"]["run-all"] == "ctrl-enter"
new_config = merge_config(
prev_config,
- MarimoConfig(
+ PartialMarimoConfig(
keymap={
"preset": "vim",
"overrides": {
@@ -117,7 +121,7 @@ def test_merge_config_with_keymap_overrides() -> None:
new_config = merge_config(
prev_config,
- MarimoConfig(
+ PartialMarimoConfig(
keymap={
"preset": "vim",
"overrides": {},
@@ -130,7 +134,7 @@ def test_merge_config_with_keymap_overrides() -> None:
def test_mask_secrets() -> None:
- config = MarimoConfig(
+ config = PartialMarimoConfig(
ai={
"open_ai": {"api_key": "super_secret"},
"anthropic": {"api_key": "anthropic_secret"},
@@ -153,7 +157,7 @@ def test_mask_secrets() -> None:
def test_mask_secrets_empty() -> None:
- config = MarimoConfig(
+ config = PartialMarimoConfig(
ai={
"open_ai": {"model": "davinci"},
"google": {},
@@ -186,7 +190,7 @@ def test_mask_secrets_empty() -> None:
def test_remove_secret_placeholders() -> None:
- config = MarimoConfig(
+ config = PartialMarimoConfig(
ai={
"open_ai": {"api_key": "********"},
"google": {"api_key": "********"},
diff --git a/tests/_config/test_manager.py b/tests/_config/test_manager.py
index 15c2c53ee0..af56a87f8b 100644
--- a/tests/_config/test_manager.py
+++ b/tests/_config/test_manager.py
@@ -1,10 +1,12 @@
+from __future__ import annotations
+
import unittest
from functools import wraps
from typing import Any, Callable, TypeVar
from unittest.mock import patch
-from marimo._config.config import merge_default_config
-from marimo._config.manager import MarimoConfig, UserConfigManager
+from marimo._config.config import PartialMarimoConfig, merge_default_config
+from marimo._config.manager import UserConfigManager
from marimo._config.utils import load_config
F = TypeVar("F", bound=Callable[..., Any])
@@ -28,7 +30,7 @@ class TestUserConfigManager(unittest.TestCase):
@patch("tomlkit.dump")
@patch("marimo._config.manager.load_config")
def test_save_config(self, mock_load: Any, mock_dump: Any) -> None:
- mock_config = merge_default_config(MarimoConfig())
+ mock_config = merge_default_config(PartialMarimoConfig())
mock_load.return_value = mock_config
manager = UserConfigManager()
@@ -43,13 +45,15 @@ class TestUserConfigManager(unittest.TestCase):
@patch("tomlkit.dump")
@patch("marimo._config.manager.load_config")
def test_can_save_secrets(self, mock_load: Any, mock_dump: Any) -> None:
- mock_config = merge_default_config(MarimoConfig())
+ mock_config = merge_default_config(PartialMarimoConfig())
mock_load.return_value = mock_config
manager = UserConfigManager()
manager.save_config(
merge_default_config(
- MarimoConfig(ai={"open_ai": {"api_key": "super_secret"}})
+ PartialMarimoConfig(
+ ai={"open_ai": {"api_key": "super_secret"}}
+ )
)
)
@@ -61,7 +65,7 @@ class TestUserConfigManager(unittest.TestCase):
# Do not overwrite secrets
manager.save_config(
merge_default_config(
- MarimoConfig(ai={"open_ai": {"api_key": "********"}})
+ PartialMarimoConfig(ai={"open_ai": {"api_key": "********"}})
)
)
assert (
@@ -73,7 +77,7 @@ class TestUserConfigManager(unittest.TestCase):
@patch("marimo._config.manager.load_config")
def test_can_read_secrets(self, mock_load: Any) -> None:
mock_config = merge_default_config(
- MarimoConfig(ai={"open_ai": {"api_key": "super_secret"}})
+ PartialMarimoConfig(ai={"open_ai": {"api_key": "super_secret"}})
)
mock_load.return_value = mock_config
manager = UserConfigManager()
@@ -87,7 +91,7 @@ class TestUserConfigManager(unittest.TestCase):
@restore_config
@patch("marimo._config.manager.load_config")
def test_get_config(self, mock_load: Any) -> None:
- mock_config = merge_default_config(MarimoConfig())
+ mock_config = merge_default_config(PartialMarimoConfig())
mock_load.return_value = mock_config
manager = UserConfigManager()
diff --git a/tests/_utils/test_dataclass_to_openapi.py b/tests/_utils/test_dataclass_to_openapi.py
index 205baa61e6..f33b720981 100644
--- a/tests/_utils/test_dataclass_to_openapi.py
+++ b/tests/_utils/test_dataclass_to_openapi.py
@@ -1,7 +1,10 @@
from __future__ import annotations
import dataclasses
-from typing import Any, ClassVar, List, Literal, Optional, Union
+import sys
+from typing import Any, ClassVar, List, Literal, Optional, TypedDict, Union
+
+import pytest
from marimo._utils.dataclass_to_openapi import (
PythonTypeToOpenAPI,
@@ -142,3 +145,109 @@ def test_class_var() -> None:
"properties": {"name": {"type": "string", "enum": ["dog"]}},
"required": ["name"],
}
+
+
+def test_optional() -> None:
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={}, camel_case=False
+ ).convert(Optional[str], {})
+ assert openapi_spec == {
+ "type": "string",
+ "nullable": True,
+ }
+
+
+if sys.version_info >= (3, 11):
+ from typing import NotRequired
+
+
+ sys.version_info < (3, 11), reason="Not supported in Python < 3.11"
+)
+def test_not_required() -> None:
+ class NotRequiredDict(TypedDict):
+ not_required_item: NotRequired[str]
+ optional_item: Optional[str]
+
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={}, camel_case=False
+ ).convert(NotRequiredDict, {})
+ assert openapi_spec == {
+ "type": "object",
+ "properties": {
+ "optional_item": {"type": "string", "nullable": True},
+ "not_required_item": {"type": "string"},
+ },
+ "required": ["optional_item"],
+ }
+
+
+ sys.version_info < (3, 11), reason="Not supported in Python < 3.11"
+)
+def test_not_required_total_false() -> None:
+ class NotRequiredDictTotalFalse(TypedDict, total=False):
+ not_required_item: NotRequired[str]
+ optional_item: Optional[str]
+
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={}, camel_case=False
+ ).convert(NotRequiredDictTotalFalse, {})
+ assert openapi_spec == {
+ "type": "object",
+ "properties": {
+ "optional_item": {"type": "string", "nullable": True},
+ "not_required_item": {"type": "string"},
+ },
+ }
+
+
+ sys.version_info < (3, 11), reason="Not supported in Python < 3.11"
+)
+def test_not_required_as_dataclass() -> None:
+ @dataclasses.dataclass
+ class NotRequiredDictAsDataclass(TypedDict):
+ not_required_item: NotRequired[str]
+ optional_item: Optional[str]
+
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={}, camel_case=False
+ ).convert(NotRequiredDictAsDataclass, {})
+
+ assert NotRequiredDictAsDataclass(optional_item="hello") is not None
+
+ assert openapi_spec == {
+ "type": "object",
+ "properties": {
+ "optional_item": {"type": "string", "nullable": True},
+ "not_required_item": {"type": "string"},
+ },
+ "required": ["optional_item"],
+ }
+
+
+ sys.version_info < (3, 11), reason="Not supported in Python < 3.11"
+)
+def test_not_required_as_dataclass_total_false() -> None:
+ @dataclasses.dataclass
+ class NotRequiredDictAsDataclassTotalFalse(TypedDict, total=False):
+ not_required_item: NotRequired[str]
+ optional_item: Optional[str]
+
+ openapi_spec = PythonTypeToOpenAPI(
+ name_overrides={}, camel_case=False
+ ).convert(NotRequiredDictAsDataclassTotalFalse, {})
+
+ assert (
+ NotRequiredDictAsDataclassTotalFalse(optional_item="hello") is not None
+ )
+
+ assert openapi_spec == {
+ "type": "object",
+ "properties": {
+ "optional_item": {"type": "string", "nullable": True},
+ "not_required_item": {"type": "string"},
+ },
+ }