Created
July 15, 2020 06:18
-
-
Save RHDZMOTA/192b2703ea207c971a4f395bed42ad23 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
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) |
This file contains hidden or 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
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