Skip to content

Instantly share code, notes, and snippets.

@asnramos
Forked from RHDZMOTA/serializable_helper.py
Created December 2, 2021 17:32
Show Gist options
  • Save asnramos/fe792b2e808d3d1489b739c0e1bf5c32 to your computer and use it in GitHub Desktop.
Save asnramos/fe792b2e808d3d1489b739c0e1bf5c32 to your computer and use it in GitHub Desktop.
import inspect
import json
from typing import Dict, TypeVar
SerializableDataType = TypeVar(
"SerializableDataType",
bound="Serializable"
)
class Serializable:
default_cls_encoder = json.JSONEncoder
default_cls_decoder = json.JSONDecoder
@classmethod
def from_json(cls, content: str, **kwargs) -> SerializableDataType:
kwargs["cls"] = kwargs.pop("json_cls", cls.default_cls_decoder)
instance_kwargs = json.loads(content, **kwargs)
return cls(**instance_kwargs)
@classmethod
def from_file(cls, filename: str, **kwargs) -> SerializableDataType:
with open(filename, "r") as file:
return cls.from_json(content=file.read(), **kwargs)
@classmethod
def _get_init_arglist(cls):
return inspect.getfullargspec(cls).args
def to_dict(self, error_if_not_exists: bool = False) -> Dict:
return {
arg: getattr(self, arg) if error_if_not_exists else \
getattr(self, arg, None)
for arg in self._get_init_arglist()
if arg != "self"
}
def to_json(self, **kwargs) -> str:
dictionary = self.to_dict()
kwargs["cls"] = kwargs.pop("json_cls", self.default_cls_encoder)
return json.dumps(dictionary, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment