python-redux 0.25.2__cp314-cp314-win_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ """Mixin for serialization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ from types import NoneType
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ from immutable import Immutable, is_immutable
10
+
11
+ if TYPE_CHECKING:
12
+ from redux.basic_types import SnapshotAtom
13
+
14
+
15
+ class SerializationMixin:
16
+ """Mixin for serialization."""
17
+
18
+ @classmethod
19
+ def serialize_value(
20
+ cls: type[SerializationMixin],
21
+ obj: object | type,
22
+ ) -> SnapshotAtom:
23
+ """Serialize a value to a snapshot atom."""
24
+ if isinstance(obj, int | float | str | bool | NoneType):
25
+ return obj
26
+ if callable(obj):
27
+ return cls.serialize_value(obj())
28
+ if isinstance(obj, list | tuple):
29
+ return [cls.serialize_value(i) for i in obj]
30
+ if is_immutable(obj):
31
+ return cls._serialize_dataclass_to_dict(obj)
32
+ msg = f'Unable to serialize object with type `{type(obj)}`'
33
+ raise TypeError(msg)
34
+
35
+ @classmethod
36
+ def _serialize_dataclass_to_dict(
37
+ cls: type[SerializationMixin],
38
+ obj: Immutable,
39
+ ) -> dict[str, Any]:
40
+ result: dict[str, object] = {'_type': obj.__class__.__name__}
41
+ for field in dataclasses.fields(obj):
42
+ value = cls.serialize_value(getattr(obj, field.name))
43
+ result[field.name] = value
44
+ return result