Last active
December 2, 2021 17:32
-
-
Save RHDZMOTA/3b50b284d1892e4ac1bcffcca7dab135 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
If you have json-incompatible datatypes, you'll need to provide companion decoders & encoders classes.
Consider the a simple human class with:
name (str)
: the name is a json-compatible datatype.birthdate (datetime)
: the birthdate is json-incompatile; we need to serialize (encode) the string before transforming to JSON and decode when creating a human instance.You have two options:
Let's take a look at the second option:
You should now be able to use the
Human
class with full serialization capabilities!