Skip to content

Instantly share code, notes, and snippets.

@RHDZMOTA
Created July 15, 2020 06:18
Show Gist options
  • Save RHDZMOTA/192b2703ea207c971a4f395bed42ad23 to your computer and use it in GitHub Desktop.
Save RHDZMOTA/192b2703ea207c971a4f395bed42ad23 to your computer and use it in GitHub Desktop.
import inspect
import json
from typing import Dict, TypeVar
SerializableADT = TypeVar("SerializableADT", bound="Serializable")
class Serializable:
@classmethod
def from_json(cls, content: str) -> SerializableADT:
serializable_kwargs = json.loads(content)
return cls.__init__(**serializable_kwargs)
def to_dict(self) -> Dict:
args = inspect.getfullargspec(self.__init__).args
dictionary = self.__dict__
return {
arg: dictionary.get(arg)
for arg in args
if arg != "self"
}
def to_json(self, **kwargs) -> str:
dictionary = self.to_dict()
return json.dumps(dictionary, **kwargs)
from serializable import Serializable
class A(Serializable):
def __init__(self, a: str, value: str):
self.a = a
self.value = value
class B(Serializable):
def __init__(self, b: int):
self.b = b
def add(val: int) -> 'B':
return B(self.b + val)
a = A("hello", "world")
a.to_dict()
a.to_json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment