diff --git a/serde/se.py b/serde/se.py index b74abe4e..a3cd7885 100644 --- a/serde/se.py +++ b/serde/se.py @@ -381,8 +381,9 @@ def serializable_to_obj(object: Any) -> Any: elif is_bearable(o, dict): return {k: thisfunc(v) for k, v in o.items()} elif is_str_serializable_instance(o) or is_datetime_instance(o): + se_cls = o.__class__ if not c or c is Any else c return CACHE.serialize( - c or o.__class__, + se_cls, o, reuse_instances=reuse_instances, convert_sets=convert_sets, diff --git a/tests/test_basics.py b/tests/test_basics.py index ea7c3188..94a1d628 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -662,7 +662,6 @@ class Foo: @pytest.mark.parametrize("se,de", format_msgpack) def test_inheritance(se, de): - @serde.serde class Base: a: int @@ -1113,3 +1112,23 @@ class Foo: a: int = serde.field(skip=True) assert serde.to_dict(Foo(10)) == {} + + +def test_dict_str_any() -> None: + @serde.serde + class Foo: + a: dict[str, Any] + + # Because the dict values are typed as Any, all values will be serialized as strings + date = datetime.datetime(2024, 12, 3, 16, 55, 20, 220662) + date_str = date.isoformat() + + uuid_val = uuid.UUID("efb71d76-4337-4b27-a612-5b6f95b01d42") + uuid_str = str(uuid_val) + + foo = Foo(a={"a": uuid_val, "b": date}) + foo_se = {"a": {"a": uuid_str, "b": date_str}} + foo_de = Foo(a={"a": uuid_str, "b": date_str}) + + assert serde.to_dict(foo) == foo_se + assert serde.from_dict(Foo, foo_se) == foo_de