-
-
Save asnramos/fe792b2e808d3d1489b739c0e1bf5c32 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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