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.

refactor parse_dataclass.py to make Exceptions more explicit, also added some tests (#1082)

fuenfundachtzigf82c46cb3d0f
diff --git a/marimo/_utils/parse_dataclass.py b/marimo/_utils/parse_dataclass.py
index 361426add8..e219868b9d 100644
--- a/marimo/_utils/parse_dataclass.py
+++ b/marimo/_utils/parse_dataclass.py
@@ -61,8 +61,11 @@ def _build_value(value: Any, cls: Type[T]) -> T:
for arg_type in arg_types:
try:
return _build_value(value, arg_type) # type: ignore # noqa: E501
- except Exception:
+ # catch expected exceptions when conversion fails
+ except (TypeError, ValueError):
continue
+ except:
+ raise
raise ValueError(f"Value '{value}' does not fit any type of the union")
elif origin_cls is Literal:
# if its a single Literal of an enum, we can just return the enum
@@ -87,12 +90,24 @@ def _build_value(value: Any, cls: Type[T]) -> T:
return value # type: ignore[no-any-return]
-def build_dataclass(value: dict[Any, Any], cls: Type[T]) -> T:
+def build_dataclass(values: dict[Any, Any], cls: Type[T]) -> T:
+ """Returns instance of dataclass [cls] instantiated from [values]."""
+
+ if not isinstance(values, dict):
+ raise ValueError(
+ "value passed to build_dataclass needs to be a dictionary"
+ )
+
types = get_type_hints(cls)
+ snake_cased_values = {to_snake(k): v for k, v in values.items()}
+ if not snake_cased_values.keys() <= types.keys():
+ raise ValueError(
+ "values in build_dataclass do not match arguments for constructor"
+ )
+
transformed = {
- to_snake(k): _build_value(v, types[to_snake(k)])
- for k, v in value.items()
+ k: _build_value(v, types[k]) for k, v in snake_cased_values.items()
}
return cls(**transformed)
diff --git a/tests/_utils/test_parse_dataclass.py b/tests/_utils/test_parse_dataclass.py
index 8c549c6e84..ef5c70c8c6 100644
--- a/tests/_utils/test_parse_dataclass.py
+++ b/tests/_utils/test_parse_dataclass.py
@@ -53,6 +53,11 @@ def serialize(obj: Any) -> bytes:
class TestParseRaw:
+ def test_invalid_message(self) -> None:
+ with pytest.raises(ValueError) as e:
+ parse_raw(b'"string"', ConfigOne)
+ assert "needs to be a dictionary" in str(e.value)
+
def test_flat(self) -> None:
@dataclass
class Flat:
@@ -168,11 +173,18 @@ class TestParseRaw:
parsed = parse_raw(serialize(nested), Nested)
assert parsed == nested
- # handle error
+ # should raise ("invalid" is not a dict and thus cannot be converted
+ # to a dataclass)
with pytest.raises(ValueError) as e:
parsed = parse_raw(serialize({"config": "invalid"}), Nested)
assert "invalid" in str(e.value)
+ # should raise (value of key "config" is dataclass not included in
+ # Union)
+ nested = Nested(config=Config(True, True)) # type: ignore
+ with pytest.raises(ValueError) as e:
+ parsed = parse_raw(serialize(nested), Nested)
+
def test_enums(self) -> None:
@dataclass
class Nested:
@@ -212,16 +224,17 @@ class TestParseRaw:
)
assert "invalid" in str(e.value)
- def test_build_optional(self) -> None:
- @dataclass
- class TestOptional:
- x: Optional[str] = None
- parsed = build_dataclass({}, TestOptional)
- assert parsed == TestOptional(x=None)
+def test_build_optional() -> None:
+ @dataclass
+ class TestOptional:
+ x: Optional[str] = None
+
+ parsed = build_dataclass({}, TestOptional)
+ assert parsed == TestOptional(x=None)
- parsed = build_dataclass({"x": "hello"}, TestOptional)
- assert parsed == TestOptional(x="hello")
+ parsed = build_dataclass({"x": "hello"}, TestOptional)
+ assert parsed == TestOptional(x="hello")
def test_build_empty_dataclass() -> None: