diff --git a/src/python/models/model_item.py b/src/python/models/model_item.py index 1fef7e6a..4b68fd04 100644 --- a/src/python/models/model_item.py +++ b/src/python/models/model_item.py @@ -1,6 +1,7 @@ -from enum import Enum from typing import Any, Dict, Optional +from ..utils import serialize_value_for_qml + class ModelItem: def __new__(cls, *_args, **_kwargs) -> "ModelItem": @@ -24,14 +25,9 @@ class ModelItem: @property def serialized(self) -> Dict[str, Any]: return { - name: self._process_attr(getattr(self, name)) for name in dir(self) + name: serialize_value_for_qml(getattr(self, name)) + for name in dir(self) if not ( name.startswith("_") or name in ("parent_model", "serialized") ) } - - @staticmethod - def _process_attr(value: Any) -> Any: - if hasattr(value, "__class__") and issubclass(value.__class__, Enum): - return value.value - return value diff --git a/src/python/pyotherside_events.py b/src/python/pyotherside_events.py index de36aec4..b205b4a0 100644 --- a/src/python/pyotherside_events.py +++ b/src/python/pyotherside_events.py @@ -1,10 +1,10 @@ from dataclasses import dataclass, field -from enum import Enum from typing import Any, Dict, List, Optional, Union import pyotherside from .models import SyncId +from .utils import serialize_value_for_qml @dataclass @@ -14,20 +14,12 @@ class PyOtherSideEvent: def __post_init__(self) -> None: # CPython >= 3.6 or any Python >= 3.7 needed for correct dict order args = [ - self._process_field(getattr(self, field)) + serialize_value_for_qml(getattr(self, field)) for field in self.__dataclass_fields__ # type: ignore ] pyotherside.send(type(self).__name__, *args) - @staticmethod - def _process_field(value: Any) -> Any: - if hasattr(value, "__class__") and issubclass(value.__class__, Enum): - return value.value - - return value - - @dataclass class ExitRequested(PyOtherSideEvent): """Request for the application to exit.""" diff --git a/src/python/utils.py b/src/python/utils.py index 1b34b3da..d0411f51 100644 --- a/src/python/utils.py +++ b/src/python/utils.py @@ -3,7 +3,7 @@ import html import xml.etree.cElementTree as xml_etree # FIXME: bandit warning from enum import Enum from enum import auto as autostr -from typing import IO, Tuple, Union +from typing import IO, Any, Tuple, Union import filetype @@ -62,3 +62,10 @@ def plain2html(text: str) -> str: return html.escape(text)\ .replace("\n", "
")\ .replace("\t", " " * 4) + + +def serialize_value_for_qml(value: Any) -> Any: + if hasattr(value, "__class__") and issubclass(value.__class__, Enum): + return value.value + + return value