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: extend dataclass parsing to handle container types (#111)

Akshay Agrawale53948b8d4f0
diff --git a/marimo/_server/api/model.py b/marimo/_server/api/model.py
index 16d9098d18..bef72d2c28 100644
--- a/marimo/_server/api/model.py
+++ b/marimo/_server/api/model.py
@@ -1,6 +1,9 @@
# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import dataclasses
import json
-from typing import Type, TypeVar
+from typing import Any, Type, TypeVar, get_args, get_origin, get_type_hints
T = TypeVar("T")
@@ -13,9 +16,52 @@ def to_snake(string: str) -> str:
).lstrip("_")
+def _build_value(value: Any, cls: Type[T]) -> T:
+ # origin_cls is not None if cls is a container (such as list, tuple, set,
+ # ...)
+ origin_cls = get_origin(cls)
+ if origin_cls in (list, set):
+ (arg_type,) = get_args(cls)
+ return origin_cls(_build_value(v, arg_type) for v in value) # type: ignore # noqa: E501
+ elif origin_cls == tuple:
+ arg_types = get_args(cls)
+ if len(arg_types) == 2 and isinstance(arg_types[1], type(Ellipsis)):
+ return origin_cls(_build_value(v, arg_types[0]) for v in value) # type: ignore # noqa: E501
+ else:
+ return origin_cls(_build_value(v, t) for v, t in zip(value, arg_types)) # type: ignore # noqa: E501
+ elif origin_cls == dict:
+ key_type, value_type = get_args(cls)
+ return origin_cls( # type: ignore[no-any-return]
+ **{
+ _build_value(k, key_type): _build_value(v, value_type)
+ for k, v in value.items()
+ }
+ )
+ elif dataclasses.is_dataclass(cls):
+ return _build_dataclass(value, cls) # type: ignore[return-value]
+ else:
+ return value # type: ignore[no-any-return]
+
+
+def _build_dataclass(value: dict[Any, Any], cls: Type[T]) -> T:
+ types = get_type_hints(cls)
+ transformed = {
+ to_snake(k): _build_value(v, types[to_snake(k)])
+ for k, v in value.items()
+ }
+ return cls(**transformed)
+
+
def parse_raw(message: bytes, cls: Type[T]) -> T:
"""Utility to parse a message as JSON, and instantiate into supplied type.
+ `cls` must be a dataclass.
+
+ Supported collection types in the dataclass:
+ - List, Tuple, Set, Dict
+ - for Python 3.8 compatibility, must use collection types from
+ the typing module (e.g., typing.List[int] instead of list[int])
+
Transforms all fields in the parsed JSON from camel case to snake case.
Args:
@@ -24,5 +70,4 @@ def parse_raw(message: bytes, cls: Type[T]) -> T:
cls: the type to instantiate
"""
parsed = json.loads(message)
- transformed = {to_snake(k): v for k, v in parsed.items()}
- return cls(**transformed)
+ return _build_dataclass(parsed, cls)
diff --git a/marimo/_server/api/test_model.py b/marimo/_server/api/test_model.py
new file mode 100644
index 0000000000..75a5bb822a
--- /dev/null
+++ b/marimo/_server/api/test_model.py
@@ -0,0 +1,116 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+from dataclasses import asdict, dataclass
+from typing import Any, Dict, List, Tuple
+
+from marimo._server.api.model import parse_raw
+
+
+@dataclass
+class Config:
+ disabled: bool
+ gpu: bool
+
+
+def serialize(obj: Any) -> bytes:
+ return bytes(
+ json.dumps(asdict(obj) if not isinstance(obj, dict) else obj),
+ encoding="utf-8",
+ )
+
+
+class TestParseRaw:
+ def test_flat(self) -> None:
+ @dataclass
+ class Flat:
+ x: str
+ y: int
+
+ flat = Flat(x="hello", y=0)
+ parsed = parse_raw(serialize(flat), Flat)
+ assert parsed == flat
+
+ def test_camel_case_to_snake(self) -> None:
+ @dataclass
+ class Flat:
+ my_variable: str
+ my_other_variable: int
+
+ parsed = parse_raw(
+ serialize({"MyVariable": "0", "MyOtherVariable": 1}), Flat
+ )
+ assert parsed == Flat(my_variable="0", my_other_variable=1)
+
+ def test_nested_singleton(self) -> None:
+ @dataclass
+ class Nested:
+ config: Config
+
+ nested = Nested(Config(disabled=True, gpu=False))
+
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ def test_nested_list(self) -> None:
+ @dataclass
+ class Nested:
+ configs: List[Config]
+
+ nested = Nested(
+ configs=[
+ Config(disabled=True, gpu=False),
+ Config(disabled=False, gpu=True),
+ ]
+ )
+
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ def test_nested_dict(self) -> None:
+ @dataclass
+ class Nested:
+ configs: Dict[str, Config]
+
+ nested = Nested(
+ configs={
+ "0": Config(disabled=True, gpu=False),
+ "1": Config(disabled=False, gpu=True),
+ }
+ )
+
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ def test_nested_tuple_ellipses(self) -> None:
+ @dataclass
+ class Nested:
+ configs: Tuple[Config, ...]
+
+ nested = Nested(
+ configs=tuple(
+ [
+ Config(disabled=True, gpu=False),
+ Config(disabled=False, gpu=True),
+ ]
+ )
+ )
+
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
+
+ def test_nested_tuple_fixed(self) -> None:
+ @dataclass
+ class Nested:
+ configs: Tuple[str, Config]
+
+ nested = Nested(
+ configs=(
+ "0",
+ Config(disabled=True, gpu=False),
+ )
+ )
+
+ parsed = parse_raw(serialize(nested), Nested)
+ assert parsed == nested
diff --git a/marimo/_smoke_tests/inputs.py b/marimo/_smoke_tests/inputs.py
index a2e27d9fc3..5789b8938a 100644
--- a/marimo/_smoke_tests/inputs.py
+++ b/marimo/_smoke_tests/inputs.py
@@ -1,3 +1,4 @@
+# Copyright 2023 Marimo. All rights reserved.
import marimo
__generated_with = "0.1.8"