madpah / serializable

Pythonic library to aid with serialisation and deserialisation to/from JSON and XML.

Home Page:https://py-serializable.readthedocs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

feat: allow different/custom (de)serialization on JSON/XML

jkowalleck opened this issue · comments

current implementation for custom (de)serialize does not allow to have a differrent value returned for JSON or XML.
the custom (de)serializer has no change to tell the difference.

in some cases it is needed to retun a value for the target.

solution: inject the SerializationType.{JSON,XML} as an argument into BaseHelper.{de,}serialize() during _{as,from}_{json,xml}()

use case: https://github.com/CycloneDX/cyclonedx-python-lib/blob/afe0ba90ec211a89fdb57adc719ba09a0a6f92a1/cyclonedx/serialization/__init__.py#L88-L95


proposed changes

  class BaseHelper(ABC):
  
      def __init__(self, *args: Any, **kwargs: Any) -> None:
          pass
  
      @classmethod
      @abstractmethod
-     def serialize(cls, o: object) -> Any:
+     def serialize(cls, o: object, t: 'SerializationType') -> Any:
          raise NotImplementedError
  
      @classmethod
      @abstractmethod
-     def deserialize(cls, o: str) -> Any:
+     def deserialize(cls, o: str, t: 'SerializationType') -> Any:
          raise NotImplementedError

example implementation here:
serializable.patch.zip

adding another parameter might be appealing, but is a breaking change, right?
so it might be better to add another function to the base, that can be overritten.

maybe deserialize_json(cls, o: str).
the function would be non-abstract and raise a NotImplementedError per default.

so it could be called via

try: 
  deserialize_json(foo)
except NotImplementedError:
  deserialize(foo)